diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata-2025.3.dist-info/INSTALLER b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata-2025.3.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata-2025.3.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata-2025.3.dist-info/METADATA b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata-2025.3.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..330dd728bb0f4dde512f99e996a2e58496870bfa
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata-2025.3.dist-info/METADATA
@@ -0,0 +1,33 @@
+Metadata-Version: 2.4
+Name: tzdata
+Version: 2025.3
+Summary: Provider of IANA time zone data
+Home-page: https://github.com/python/tzdata
+Author: Python Software Foundation
+Author-email: datetime-sig@python.org
+License: Apache-2.0
+Project-URL: Bug Reports, https://github.com/python/tzdata/issues
+Project-URL: Source, https://github.com/python/tzdata
+Project-URL: Documentation, https://tzdata.readthedocs.io
+Classifier: Development Status :: 4 - Beta
+Classifier: Intended Audience :: Developers
+Classifier: Programming Language :: Python :: 2
+Classifier: Programming Language :: Python :: 3
+Requires-Python: >=2
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+License-File: licenses/LICENSE_APACHE
+Dynamic: license-file
+
+tzdata: Python package providing IANA time zone data
+====================================================
+
+This is a Python package containing ``zic``-compiled binaries for the IANA time
+zone database. It is intended to be a fallback for systems that do not have
+system time zone data installed (or don't have it installed in a standard
+location), as a part of `PEP 615 `_
+
+This repository generates a ``pip``-installable package, published on PyPI as
+`tzdata `_.
+
+For more information, see `the documentation `_.
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata-2025.3.dist-info/RECORD b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata-2025.3.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..1510acce4b02763bc247157415c68fc22530b6cd
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata-2025.3.dist-info/RECORD
@@ -0,0 +1,656 @@
+tzdata-2025.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+tzdata-2025.3.dist-info/METADATA,sha256=QiXXu1WSsgB_Zls4Yk6T263TZBP7_PPB-nzYCuewh_g,1352
+tzdata-2025.3.dist-info/RECORD,,
+tzdata-2025.3.dist-info/WHEEL,sha256=JNWh1Fm1UdwIQV075glCn4MVuCRs0sotJIq-J6rbxCU,109
+tzdata-2025.3.dist-info/licenses/LICENSE,sha256=M-jlAC01EtP8wigrmV5rrZ0zR4G5xawxhD9ASQDh87Q,592
+tzdata-2025.3.dist-info/licenses/licenses/LICENSE_APACHE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
+tzdata-2025.3.dist-info/top_level.txt,sha256=MO6QqC0xRrN67Gh9xU_nMmadwBVlYzPNkq_h4gYuzaQ,7
+tzdata/__init__.py,sha256=Ee9PzA6folcczG2ywJlO9wJ0f-UVfPeaxXtXdoP-zrE,252
+tzdata/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/Africa/Abidjan,sha256=8-f8qg6YQP9BadNWfY-1kmZEhI9JY9es-SMghDxdSG4,130
+tzdata/zoneinfo/Africa/Accra,sha256=8-f8qg6YQP9BadNWfY-1kmZEhI9JY9es-SMghDxdSG4,130
+tzdata/zoneinfo/Africa/Addis_Ababa,sha256=B4OFT1LDOtprbSpdhnZi8K6OFSONL857mtpPTTGetGY,191
+tzdata/zoneinfo/Africa/Algiers,sha256=L2nS4gLNFvuo89p3YtB-lSDYY2284SqkGH9pQQI8uwc,470
+tzdata/zoneinfo/Africa/Asmara,sha256=B4OFT1LDOtprbSpdhnZi8K6OFSONL857mtpPTTGetGY,191
+tzdata/zoneinfo/Africa/Asmera,sha256=B4OFT1LDOtprbSpdhnZi8K6OFSONL857mtpPTTGetGY,191
+tzdata/zoneinfo/Africa/Bamako,sha256=8-f8qg6YQP9BadNWfY-1kmZEhI9JY9es-SMghDxdSG4,130
+tzdata/zoneinfo/Africa/Bangui,sha256=5e8SiFccxWxSdsqWbhyKZ1xnR3JtdY7K_n7_zm7Ke-Q,180
+tzdata/zoneinfo/Africa/Banjul,sha256=8-f8qg6YQP9BadNWfY-1kmZEhI9JY9es-SMghDxdSG4,130
+tzdata/zoneinfo/Africa/Bissau,sha256=wa3uva129dJHRCi7tYt04kFOn1-osMS2afMjleO9mDw,149
+tzdata/zoneinfo/Africa/Blantyre,sha256=kQyXwJHNNK50J8gyJiNM57Ty9CXFgi1macJL5iAQp5I,131
+tzdata/zoneinfo/Africa/Brazzaville,sha256=5e8SiFccxWxSdsqWbhyKZ1xnR3JtdY7K_n7_zm7Ke-Q,180
+tzdata/zoneinfo/Africa/Bujumbura,sha256=kQyXwJHNNK50J8gyJiNM57Ty9CXFgi1macJL5iAQp5I,131
+tzdata/zoneinfo/Africa/Cairo,sha256=icuaNiEvuC6TPc2fqhDv36lpop7IDDIGO7tFGMAz0b4,1309
+tzdata/zoneinfo/Africa/Casablanca,sha256=MMps8T4AwqbEN6PIN_pkNiPMBEBqtRZRZceLN-9rxMM,1919
+tzdata/zoneinfo/Africa/Ceuta,sha256=oEIgK53afz1SYxYB_D0jR98Ss3g581yb8TnLppPaYcY,562
+tzdata/zoneinfo/Africa/Conakry,sha256=8-f8qg6YQP9BadNWfY-1kmZEhI9JY9es-SMghDxdSG4,130
+tzdata/zoneinfo/Africa/Dakar,sha256=8-f8qg6YQP9BadNWfY-1kmZEhI9JY9es-SMghDxdSG4,130
+tzdata/zoneinfo/Africa/Dar_es_Salaam,sha256=B4OFT1LDOtprbSpdhnZi8K6OFSONL857mtpPTTGetGY,191
+tzdata/zoneinfo/Africa/Djibouti,sha256=B4OFT1LDOtprbSpdhnZi8K6OFSONL857mtpPTTGetGY,191
+tzdata/zoneinfo/Africa/Douala,sha256=5e8SiFccxWxSdsqWbhyKZ1xnR3JtdY7K_n7_zm7Ke-Q,180
+tzdata/zoneinfo/Africa/El_Aaiun,sha256=6hfLbLfrD1Qy9ZZqLXr1Xw7fzeEs_FqeHN2zZJZUVJI,1830
+tzdata/zoneinfo/Africa/Freetown,sha256=8-f8qg6YQP9BadNWfY-1kmZEhI9JY9es-SMghDxdSG4,130
+tzdata/zoneinfo/Africa/Gaborone,sha256=kQyXwJHNNK50J8gyJiNM57Ty9CXFgi1macJL5iAQp5I,131
+tzdata/zoneinfo/Africa/Harare,sha256=kQyXwJHNNK50J8gyJiNM57Ty9CXFgi1macJL5iAQp5I,131
+tzdata/zoneinfo/Africa/Johannesburg,sha256=0Zrr4kNcToS_euZVM9I6nUQPmBYuW01pxz94PgIpnsg,190
+tzdata/zoneinfo/Africa/Juba,sha256=VTpoMAP-jJ6cKsDeNVr7l3LKGoKDUxGU2b1gqvDPz34,458
+tzdata/zoneinfo/Africa/Kampala,sha256=B4OFT1LDOtprbSpdhnZi8K6OFSONL857mtpPTTGetGY,191
+tzdata/zoneinfo/Africa/Khartoum,sha256=NRwOwIg4SR6XuD11k3hxBz77uoBpzejXq7vxtq2Xys8,458
+tzdata/zoneinfo/Africa/Kigali,sha256=kQyXwJHNNK50J8gyJiNM57Ty9CXFgi1macJL5iAQp5I,131
+tzdata/zoneinfo/Africa/Kinshasa,sha256=5e8SiFccxWxSdsqWbhyKZ1xnR3JtdY7K_n7_zm7Ke-Q,180
+tzdata/zoneinfo/Africa/Lagos,sha256=5e8SiFccxWxSdsqWbhyKZ1xnR3JtdY7K_n7_zm7Ke-Q,180
+tzdata/zoneinfo/Africa/Libreville,sha256=5e8SiFccxWxSdsqWbhyKZ1xnR3JtdY7K_n7_zm7Ke-Q,180
+tzdata/zoneinfo/Africa/Lome,sha256=8-f8qg6YQP9BadNWfY-1kmZEhI9JY9es-SMghDxdSG4,130
+tzdata/zoneinfo/Africa/Luanda,sha256=5e8SiFccxWxSdsqWbhyKZ1xnR3JtdY7K_n7_zm7Ke-Q,180
+tzdata/zoneinfo/Africa/Lubumbashi,sha256=kQyXwJHNNK50J8gyJiNM57Ty9CXFgi1macJL5iAQp5I,131
+tzdata/zoneinfo/Africa/Lusaka,sha256=kQyXwJHNNK50J8gyJiNM57Ty9CXFgi1macJL5iAQp5I,131
+tzdata/zoneinfo/Africa/Malabo,sha256=5e8SiFccxWxSdsqWbhyKZ1xnR3JtdY7K_n7_zm7Ke-Q,180
+tzdata/zoneinfo/Africa/Maputo,sha256=kQyXwJHNNK50J8gyJiNM57Ty9CXFgi1macJL5iAQp5I,131
+tzdata/zoneinfo/Africa/Maseru,sha256=0Zrr4kNcToS_euZVM9I6nUQPmBYuW01pxz94PgIpnsg,190
+tzdata/zoneinfo/Africa/Mbabane,sha256=0Zrr4kNcToS_euZVM9I6nUQPmBYuW01pxz94PgIpnsg,190
+tzdata/zoneinfo/Africa/Mogadishu,sha256=B4OFT1LDOtprbSpdhnZi8K6OFSONL857mtpPTTGetGY,191
+tzdata/zoneinfo/Africa/Monrovia,sha256=WM-JVfr502Vgy18Fe6iAJ2yMgOWbwwumIQh_yp53eKM,164
+tzdata/zoneinfo/Africa/Nairobi,sha256=B4OFT1LDOtprbSpdhnZi8K6OFSONL857mtpPTTGetGY,191
+tzdata/zoneinfo/Africa/Ndjamena,sha256=Tlj4ZUUNJxEhvAoo7TJKqWv1J7tEYaf1FEMez-K9xEg,160
+tzdata/zoneinfo/Africa/Niamey,sha256=5e8SiFccxWxSdsqWbhyKZ1xnR3JtdY7K_n7_zm7Ke-Q,180
+tzdata/zoneinfo/Africa/Nouakchott,sha256=8-f8qg6YQP9BadNWfY-1kmZEhI9JY9es-SMghDxdSG4,130
+tzdata/zoneinfo/Africa/Ouagadougou,sha256=8-f8qg6YQP9BadNWfY-1kmZEhI9JY9es-SMghDxdSG4,130
+tzdata/zoneinfo/Africa/Porto-Novo,sha256=5e8SiFccxWxSdsqWbhyKZ1xnR3JtdY7K_n7_zm7Ke-Q,180
+tzdata/zoneinfo/Africa/Sao_Tome,sha256=Pfiutakw5B5xr1OSg1uFvT0GwC6jVOqqxnx69GEJu50,173
+tzdata/zoneinfo/Africa/Timbuktu,sha256=8-f8qg6YQP9BadNWfY-1kmZEhI9JY9es-SMghDxdSG4,130
+tzdata/zoneinfo/Africa/Tripoli,sha256=zzMBLZZh4VQ4_ARe5k4L_rsuqKP7edKvVt8F6kvj5FM,431
+tzdata/zoneinfo/Africa/Tunis,sha256=uoAEER48RJqNeGoYBuk5IeYqjc8sHvWLvKssuVCd18g,449
+tzdata/zoneinfo/Africa/Windhoek,sha256=g1jLRko_2peGsUTg0_wZycOC4gxTAHwfV2SO9I3KdCM,638
+tzdata/zoneinfo/Africa/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tzdata/zoneinfo/Africa/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/America/Adak,sha256=q_sZgOINX4TsX9iBx1gNd6XGwBnzCjg6qpdAQhK0ieA,969
+tzdata/zoneinfo/America/Anchorage,sha256=d8oMIpYvBpmLzl5I2By4ZaFEZsg_9dxgfqpIM0QFi_Y,977
+tzdata/zoneinfo/America/Anguilla,sha256=q76GKN1Uh8iJ24Fs46UHe7tH9rr6_rlBHZLW7y9wzo0,177
+tzdata/zoneinfo/America/Antigua,sha256=q76GKN1Uh8iJ24Fs46UHe7tH9rr6_rlBHZLW7y9wzo0,177
+tzdata/zoneinfo/America/Araguaina,sha256=TawYX4lVAxq0BxUGhTDx4C8vtBRnLuWi8qLV_oXDiUo,592
+tzdata/zoneinfo/America/Argentina/Buenos_Aires,sha256=IEVOpSfI6oiJJmFNIb9Vb0bOOMIgxO5bghFw7vkHFGk,708
+tzdata/zoneinfo/America/Argentina/Catamarca,sha256=UC0fxx7ZPmjPw3D0BK-5vap-c1cBzbgR293MdmEfOx0,708
+tzdata/zoneinfo/America/Argentina/ComodRivadavia,sha256=UC0fxx7ZPmjPw3D0BK-5vap-c1cBzbgR293MdmEfOx0,708
+tzdata/zoneinfo/America/Argentina/Cordoba,sha256=9Ij3WjT9mWMKQ43LeSUIqQuDb9zS3FSlHYPVNQJTFf0,708
+tzdata/zoneinfo/America/Argentina/Jujuy,sha256=7YpjOcmVaKKpiq31rQe8TTDNExdH9jjZIhdcZv-ShUg,690
+tzdata/zoneinfo/America/Argentina/La_Rioja,sha256=mUkRD5jaWJUy2f8vNFqOlMgKPptULOBn-vf_jMgF6x8,717
+tzdata/zoneinfo/America/Argentina/Mendoza,sha256=dL4q0zgY2FKPbG8cC-Wknnpp8tF2Y7SWgWSC_G_WznI,708
+tzdata/zoneinfo/America/Argentina/Rio_Gallegos,sha256=bCpWMlEI8KWe4c3n6fn8u6WCPnxjYtVy57ERtLTZaEs,708
+tzdata/zoneinfo/America/Argentina/Salta,sha256=H_ybxVycfOe7LlUA3GngoS0jENHkQURIRhjfJQF2kfU,690
+tzdata/zoneinfo/America/Argentina/San_Juan,sha256=Mj5vIUzQl5DtsPe3iMzS7rR-88U9HKW2csQqUda4JNM,717
+tzdata/zoneinfo/America/Argentina/San_Luis,sha256=rka8BokogyvMRFH6jr8D6s1tFIpsUeqHJ_feLK5O6ds,717
+tzdata/zoneinfo/America/Argentina/Tucuman,sha256=yv3aC-hALLio2yqneLIIylZhXKDlbPJGAd_abgsj9gg,726
+tzdata/zoneinfo/America/Argentina/Ushuaia,sha256=mcmZgB1pEHX6i7nlyRzjLnG8bqAtAK1TwMdRD2pZqBE,708
+tzdata/zoneinfo/America/Argentina/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tzdata/zoneinfo/America/Argentina/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/America/Aruba,sha256=q76GKN1Uh8iJ24Fs46UHe7tH9rr6_rlBHZLW7y9wzo0,177
+tzdata/zoneinfo/America/Asuncion,sha256=3JONAueH7Ka_xq5KOrctKkKAauPe3BTg0BOTBA8UNUI,1085
+tzdata/zoneinfo/America/Atikokan,sha256=p41zBnujy9lPiiPf3WqotoyzOxhIS8F7TiDqGuwvCoE,149
+tzdata/zoneinfo/America/Atka,sha256=q_sZgOINX4TsX9iBx1gNd6XGwBnzCjg6qpdAQhK0ieA,969
+tzdata/zoneinfo/America/Bahia,sha256=_-ZFw-HzXc7byacHW_NJHtJ03ADFdqt1kaYgyWYobYw,682
+tzdata/zoneinfo/America/Bahia_Banderas,sha256=lJ8K-PrUqLTefuqpcKp_YWvfvzH0WNNrZ_LIel_0oZQ,700
+tzdata/zoneinfo/America/Barbados,sha256=gdiJf9ZKOMs9QB4ex0-crvdmhNfHpNzXTV2xTaNDCAg,278
+tzdata/zoneinfo/America/Belem,sha256=w0jv-gdBbEBZQBF2z2liKpRM9CEOWA36O1qU1nJKeCs,394
+tzdata/zoneinfo/America/Belize,sha256=uYBPJqnCGnOOeKnoz1IG9POWTvXD5kUirpFuB0PHjVo,1045
+tzdata/zoneinfo/America/Blanc-Sablon,sha256=q76GKN1Uh8iJ24Fs46UHe7tH9rr6_rlBHZLW7y9wzo0,177
+tzdata/zoneinfo/America/Boa_Vista,sha256=hYTFFNNZJdl_nSYIdfI8SQhtmfiakjCDI_15TlB-xEw,430
+tzdata/zoneinfo/America/Bogota,sha256=BqH6uClrrlT-VsBmke2Mh-IfA1R1l1h031CRUSLS1no,179
+tzdata/zoneinfo/America/Boise,sha256=Jt3omyPSPRoKE-KXVd-wxVON-CDE5oGaJA7Ar90Q2OM,999
+tzdata/zoneinfo/America/Buenos_Aires,sha256=IEVOpSfI6oiJJmFNIb9Vb0bOOMIgxO5bghFw7vkHFGk,708
+tzdata/zoneinfo/America/Cambridge_Bay,sha256=NFwNVfgxb2YMLzc-42RA-SKtNcODpukEfYf_QWWYTsI,883
+tzdata/zoneinfo/America/Campo_Grande,sha256=mngKYjaH_ENVmJ-mtURVjjFo5kHgLfYNPHZaCVSxQFE,952
+tzdata/zoneinfo/America/Cancun,sha256=YSoUxbjaL2MycKCTB3ZAK9jPVaeMhW7MkOEA8eWakKY,538
+tzdata/zoneinfo/America/Caracas,sha256=UHmUwc0mFPoidR4UDCWb4T4w_mpCBsSb4BkW3SOKIVY,190
+tzdata/zoneinfo/America/Catamarca,sha256=UC0fxx7ZPmjPw3D0BK-5vap-c1cBzbgR293MdmEfOx0,708
+tzdata/zoneinfo/America/Cayenne,sha256=9URU4o1v5759UWuh8xI9vnaANOceOeRW67XoGQuuUa8,151
+tzdata/zoneinfo/America/Cayman,sha256=p41zBnujy9lPiiPf3WqotoyzOxhIS8F7TiDqGuwvCoE,149
+tzdata/zoneinfo/America/Chicago,sha256=wntzn_RqffBZThINcltDkhfhHkTqmlDNxJEwODtUguc,1754
+tzdata/zoneinfo/America/Chihuahua,sha256=tzOmA7trhFykyUZ7QbuMA6A88BSF2o4mumo65aojzqo,691
+tzdata/zoneinfo/America/Ciudad_Juarez,sha256=mEE-VN-sqVDaHFJyFGUBYyOsYHCRspUZcSJqt26Wufg,718
+tzdata/zoneinfo/America/Coral_Harbour,sha256=p41zBnujy9lPiiPf3WqotoyzOxhIS8F7TiDqGuwvCoE,149
+tzdata/zoneinfo/America/Cordoba,sha256=9Ij3WjT9mWMKQ43LeSUIqQuDb9zS3FSlHYPVNQJTFf0,708
+tzdata/zoneinfo/America/Costa_Rica,sha256=ihoqA_tHmYm0YjTRLZu3q8PqsqqOeb1CELjWhPf_HXE,232
+tzdata/zoneinfo/America/Coyhaique,sha256=c_K3bduiI0P_lEnoJUNUZq2qF2-Svfo70xveKg9y9fc,1362
+tzdata/zoneinfo/America/Creston,sha256=rhFFPCHQiYTedfLv7ATckxeKe04jxeUvIJi4vUXMtUc,240
+tzdata/zoneinfo/America/Cuiaba,sha256=OaIle0Cr-BKe0hOik5rwdcoCbQ5LSHkHqBS2cLoCqAU,934
+tzdata/zoneinfo/America/Curacao,sha256=q76GKN1Uh8iJ24Fs46UHe7tH9rr6_rlBHZLW7y9wzo0,177
+tzdata/zoneinfo/America/Danmarkshavn,sha256=cQORuA8pR0vw3ZwYfeGkWaT1tPU66nMQ2xRKT1T1Yb4,447
+tzdata/zoneinfo/America/Dawson,sha256=BlKV0U36jqnlxM5-Pxn8OIiY5kJEcLlt3QZo-GsMzlY,1029
+tzdata/zoneinfo/America/Dawson_Creek,sha256=t4USMuIvq1VVL9gYCabraAYs31kmAqAnwf7GzEiJJNc,683
+tzdata/zoneinfo/America/Denver,sha256=m7cDkg7KS2EZ6BoQVYOk9soiBlHxO0GEeat81WxBPz4,1042
+tzdata/zoneinfo/America/Detroit,sha256=I4F8Mt9nx38AF6D-steYskBa_HHO6jKU1-W0yRFr50A,899
+tzdata/zoneinfo/America/Dominica,sha256=q76GKN1Uh8iJ24Fs46UHe7tH9rr6_rlBHZLW7y9wzo0,177
+tzdata/zoneinfo/America/Edmonton,sha256=Dq2mxcSNWZhMWRqxwwtMcaqwAIGMwkOzz-mW8fJscV8,970
+tzdata/zoneinfo/America/Eirunepe,sha256=6tKYaRpnbBSmXiwXy7_m4WW_rbVfn5LUec0keC3J7Iw,436
+tzdata/zoneinfo/America/El_Salvador,sha256=4wjsCpRH9AFk5abLAbnuv-zouhRKcwb0aenk-nWtmz0,176
+tzdata/zoneinfo/America/Ensenada,sha256=r5rqSu5QUUP6XoR2Q8D_4WQZDDhBEBCsfwsXD0CYpsg,1367
+tzdata/zoneinfo/America/Fort_Nelson,sha256=_j7IJ-hXHtV_7dSMg6pxGQLb6z_IaUMj3aJde_F49QQ,1448
+tzdata/zoneinfo/America/Fort_Wayne,sha256=5nj0KhPvvXvg8mqc5T4EscKKWC6rBWEcsBwWg2Qy8Hs,531
+tzdata/zoneinfo/America/Fortaleza,sha256=ugF4DWO3j_khONebf7CLsT9ldL-JOWey_69S0jl2LIA,484
+tzdata/zoneinfo/America/Glace_Bay,sha256=I1posPHAEfg_Lc_FQdX1B8F8_A0NeJnK72p36PE7pKM,880
+tzdata/zoneinfo/America/Godthab,sha256=LlGZ5Y_ud9JwWRvncHnUHRArQbbnNcmmrz3duMhR3Hc,965
+tzdata/zoneinfo/America/Goose_Bay,sha256=gCJA1Sk2ciUg2WInn8DmPBwRAw0FjQbYPaUJK80mtMI,1580
+tzdata/zoneinfo/America/Grand_Turk,sha256=Gp8hpMt9P3QoEHmsIX2bqGNMkUSvlwZqqNzccR-cbe8,853
+tzdata/zoneinfo/America/Grenada,sha256=q76GKN1Uh8iJ24Fs46UHe7tH9rr6_rlBHZLW7y9wzo0,177
+tzdata/zoneinfo/America/Guadeloupe,sha256=q76GKN1Uh8iJ24Fs46UHe7tH9rr6_rlBHZLW7y9wzo0,177
+tzdata/zoneinfo/America/Guatemala,sha256=BGPGI4lyN6IFF_T0kx1q2lh3U5SEhbyDqLFuW8EFCaU,212
+tzdata/zoneinfo/America/Guayaquil,sha256=8OIaCy-SirKKz4I77l6MQFDgSLHtjN0TvklLVEZ_008,179
+tzdata/zoneinfo/America/Guyana,sha256=PmnEtWtOTamsPJXEo7PcNQCy2Rp-evGyJh4cf0pjAR4,181
+tzdata/zoneinfo/America/Halifax,sha256=kO5ahBM2oTLfWS4KX15FbKXfo5wg-f9vw1_hMOISGig,1672
+tzdata/zoneinfo/America/Havana,sha256=ms5rCuq2yBM49VmTymMtFQN3c5aBN1lkd8jjzKdnNm8,1117
+tzdata/zoneinfo/America/Hermosillo,sha256=Ur1MYSAX3QbT2UX57LmD83o6s2Z-6YbYeOufKvT-zTM,258
+tzdata/zoneinfo/America/Indiana/Indianapolis,sha256=5nj0KhPvvXvg8mqc5T4EscKKWC6rBWEcsBwWg2Qy8Hs,531
+tzdata/zoneinfo/America/Indiana/Knox,sha256=KJCzXct8CTMItVLYLYeBqM6aT6b53gWCg6aDbsH58oI,1016
+tzdata/zoneinfo/America/Indiana/Marengo,sha256=ygWmq8sYee8NFwlSZyQ_tsKopFQMp9Ne557zGGbyF2Y,567
+tzdata/zoneinfo/America/Indiana/Petersburg,sha256=BIrubzHEp5QoyMaPgYbC1zSa_F3LwpXzKM8xH3rHspI,683
+tzdata/zoneinfo/America/Indiana/Tell_City,sha256=em2YMHDWEFXdZH0BKi5bLRAQ8bYDfop2T0Q8SqDh0B8,522
+tzdata/zoneinfo/America/Indiana/Vevay,sha256=dPk334e7MQwl71-avNyREBYVWuFTQcVKfltlRhrlRpw,369
+tzdata/zoneinfo/America/Indiana/Vincennes,sha256=jiODDXepmLP3gvCkBufdE3rp5cEXftBHnKne8_XOOCg,558
+tzdata/zoneinfo/America/Indiana/Winamac,sha256=hsEunaLrbxvspyV3Qm4UD7x7qOAeBtzcbbzANNMrdiw,603
+tzdata/zoneinfo/America/Indiana/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tzdata/zoneinfo/America/Indiana/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/America/Indianapolis,sha256=5nj0KhPvvXvg8mqc5T4EscKKWC6rBWEcsBwWg2Qy8Hs,531
+tzdata/zoneinfo/America/Inuvik,sha256=d_ZX-USS70HIT-_PRJKMY6mbQRvbKLvsy9ar7uL2M40,817
+tzdata/zoneinfo/America/Iqaluit,sha256=nONS7zksGHTrbEJj73LYRZW964OncQuj_V6fNjpDoQ0,855
+tzdata/zoneinfo/America/Jamaica,sha256=pDexcAMzrv9TqLWGjVOHwIDcFMLT6Vqlzjb5AbNmkoQ,339
+tzdata/zoneinfo/America/Jujuy,sha256=7YpjOcmVaKKpiq31rQe8TTDNExdH9jjZIhdcZv-ShUg,690
+tzdata/zoneinfo/America/Juneau,sha256=V8IqRaJHSH7onK1gu3YYtW_a4VkNwjx5DCvQXpFdYAo,966
+tzdata/zoneinfo/America/Kentucky/Louisville,sha256=zS2SS573D9TmQZFWtSyRIVN3ZXVN_2FpVBbtqQFMzKU,1242
+tzdata/zoneinfo/America/Kentucky/Monticello,sha256=54or2oQ9bSbM9ifRoOjV7UjRF83jSSPuxfGeXH0nIqk,972
+tzdata/zoneinfo/America/Kentucky/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tzdata/zoneinfo/America/Kentucky/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/America/Knox_IN,sha256=KJCzXct8CTMItVLYLYeBqM6aT6b53gWCg6aDbsH58oI,1016
+tzdata/zoneinfo/America/Kralendijk,sha256=q76GKN1Uh8iJ24Fs46UHe7tH9rr6_rlBHZLW7y9wzo0,177
+tzdata/zoneinfo/America/La_Paz,sha256=2iYBxnc0HIwAzlx-Q3AI9Lb0GI87VY279oGcroBZSVs,170
+tzdata/zoneinfo/America/Lima,sha256=7vNjRhxzL-X4kyba-NkzXYNAOE-cqqcXvzXTqcTXBhY,283
+tzdata/zoneinfo/America/Los_Angeles,sha256=IA0FdU9tg6Nxz0CNcIUSV5dlezsL6-uh5QjP_oaj5cg,1294
+tzdata/zoneinfo/America/Louisville,sha256=zS2SS573D9TmQZFWtSyRIVN3ZXVN_2FpVBbtqQFMzKU,1242
+tzdata/zoneinfo/America/Lower_Princes,sha256=q76GKN1Uh8iJ24Fs46UHe7tH9rr6_rlBHZLW7y9wzo0,177
+tzdata/zoneinfo/America/Maceio,sha256=dSVg0dHedT9w1QO2F1AvWoel4_h8wmuYS4guEaL-5Kk,502
+tzdata/zoneinfo/America/Managua,sha256=ZYsoyN_GIlwAIpIj1spjQDPWGQ9kFZSipjUbO8caGfw,295
+tzdata/zoneinfo/America/Manaus,sha256=9kgrhpryB94YOVoshJliiiDSf9mwjb3OZwX0HusNRrk,412
+tzdata/zoneinfo/America/Marigot,sha256=q76GKN1Uh8iJ24Fs46UHe7tH9rr6_rlBHZLW7y9wzo0,177
+tzdata/zoneinfo/America/Martinique,sha256=m3rC6Mogc6cc1a9XJ8FPIYhZaSFNdYkxaZ-pfHhG3X4,178
+tzdata/zoneinfo/America/Matamoros,sha256=KxgAMGkE7TJuug9byFsT3KN836X3OyXq77v-tFpLVvc,437
+tzdata/zoneinfo/America/Mazatlan,sha256=IN7ecQ9SDq9sDNvu_nc_xuMN2LHSiq8X6YQgmVUe6aY,690
+tzdata/zoneinfo/America/Mendoza,sha256=dL4q0zgY2FKPbG8cC-Wknnpp8tF2Y7SWgWSC_G_WznI,708
+tzdata/zoneinfo/America/Menominee,sha256=oUmJmzOZtChYrB9In-E1GqEVi2ogKjPESXlUySUGs94,917
+tzdata/zoneinfo/America/Merida,sha256=LBpOEv4xxUcL5B7wFSNa3UyE762-EiSXb1KPQNKwwCU,654
+tzdata/zoneinfo/America/Metlakatla,sha256=EVj1LkMCgry6mT8Ln_FpHxpJSU0oSncfbHGWIQ0SI_0,586
+tzdata/zoneinfo/America/Mexico_City,sha256=N90r8I8T_OD3B8Ox9M7EAY772cR8g2ew-03rvUYb1y8,773
+tzdata/zoneinfo/America/Miquelon,sha256=Eey-Id5b4HFODINweRFtbDjcgjs_myiC2UwsgYt4kVk,550
+tzdata/zoneinfo/America/Moncton,sha256=knrBNDFwHAGFr0nWJTBQ-10F_fZ5x4n3SnZtH-KI6h8,1493
+tzdata/zoneinfo/America/Monterrey,sha256=1aYsIp-Na0lDAKVrcW4wVKFAXy5BAqDG2wWLT9wTmmQ,709
+tzdata/zoneinfo/America/Montevideo,sha256=l7FjW6qscGzdvfjlbIeZ5CQ_AFWS3ZeVDS5ppMJCNM0,969
+tzdata/zoneinfo/America/Montreal,sha256=gVq023obEpKGfS-SS3GOG7oyRVzp-SIF2y_rZQKcZ2E,1717
+tzdata/zoneinfo/America/Montserrat,sha256=q76GKN1Uh8iJ24Fs46UHe7tH9rr6_rlBHZLW7y9wzo0,177
+tzdata/zoneinfo/America/Nassau,sha256=gVq023obEpKGfS-SS3GOG7oyRVzp-SIF2y_rZQKcZ2E,1717
+tzdata/zoneinfo/America/New_York,sha256=1_IgazpFmJ_JrWPVWJIlMvpzUigNX4cXa_HbecsdH6k,1744
+tzdata/zoneinfo/America/Nipigon,sha256=gVq023obEpKGfS-SS3GOG7oyRVzp-SIF2y_rZQKcZ2E,1717
+tzdata/zoneinfo/America/Nome,sha256=_-incQnh0DwK9hJqFaYzO4osUKAUB2k2lae565sblpA,975
+tzdata/zoneinfo/America/Noronha,sha256=Q0r3GtA5y2RGkOj56OTZG5tuBy1B6kfbhyrJqCgf27g,484
+tzdata/zoneinfo/America/North_Dakota/Beulah,sha256=RvaBIS60bNNRmREi6BXSWEbJSrcP7J8Nmxg8OkBcrow,1043
+tzdata/zoneinfo/America/North_Dakota/Center,sha256=M09x4Mx6hcBAwktvwv16YvPRmsuDjZEDwHT0Umkcgyo,990
+tzdata/zoneinfo/America/North_Dakota/New_Salem,sha256=mZca9gyfO2USzax7v0mLJEYBKBVmIqylWqnfLgSsVys,990
+tzdata/zoneinfo/America/North_Dakota/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tzdata/zoneinfo/America/North_Dakota/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/America/Nuuk,sha256=LlGZ5Y_ud9JwWRvncHnUHRArQbbnNcmmrz3duMhR3Hc,965
+tzdata/zoneinfo/America/Ojinaga,sha256=97mJ9VI8h1lRAREIdJdTz_MCLtwh4b36iaQ9QolETpA,718
+tzdata/zoneinfo/America/Panama,sha256=p41zBnujy9lPiiPf3WqotoyzOxhIS8F7TiDqGuwvCoE,149
+tzdata/zoneinfo/America/Pangnirtung,sha256=nONS7zksGHTrbEJj73LYRZW964OncQuj_V6fNjpDoQ0,855
+tzdata/zoneinfo/America/Paramaribo,sha256=C2v9tR6no54CRECWDFhANTl40UsA4AhHsdnGoNCb4_Q,187
+tzdata/zoneinfo/America/Phoenix,sha256=rhFFPCHQiYTedfLv7ATckxeKe04jxeUvIJi4vUXMtUc,240
+tzdata/zoneinfo/America/Port-au-Prince,sha256=wsS6VbQ__bKJ2IUMPy_Pao0CLRK5pXEBrqkaYuqs3Ns,565
+tzdata/zoneinfo/America/Port_of_Spain,sha256=q76GKN1Uh8iJ24Fs46UHe7tH9rr6_rlBHZLW7y9wzo0,177
+tzdata/zoneinfo/America/Porto_Acre,sha256=VjuQUr668phq5bcH40r94BPnZBKHzJf_MQBfM6Db96U,418
+tzdata/zoneinfo/America/Porto_Velho,sha256=9yPU8EXtKDQHLF745ETc9qZZ9Me2CK6jvgb6S53pSKg,394
+tzdata/zoneinfo/America/Puerto_Rico,sha256=q76GKN1Uh8iJ24Fs46UHe7tH9rr6_rlBHZLW7y9wzo0,177
+tzdata/zoneinfo/America/Punta_Arenas,sha256=2Aqh7bqo-mQlnMjURDkCOeEYmeXhkzKP7OxFAvhTjjA,1218
+tzdata/zoneinfo/America/Rainy_River,sha256=ANzwYGBU1PknQW4LR-H92i5c4Db95LU-UQhPhWZCjDo,1294
+tzdata/zoneinfo/America/Rankin_Inlet,sha256=JQCXQBdyc8uJTjIFO4jZuzS0OjG0gRHv8MPmdzN93CU,807
+tzdata/zoneinfo/America/Recife,sha256=3yZTwF3MJlkY0D48CQUTzCRwDCfGNq8EXXTZYlBgUTg,484
+tzdata/zoneinfo/America/Regina,sha256=_JHuns225iE-THc9NFp-RBq4PWULAuGw2OLbpOB_UMw,638
+tzdata/zoneinfo/America/Resolute,sha256=2UeJBR2ZSkn1bUZy0G0SEhBtY9vycwSRU4naK-sw044,807
+tzdata/zoneinfo/America/Rio_Branco,sha256=VjuQUr668phq5bcH40r94BPnZBKHzJf_MQBfM6Db96U,418
+tzdata/zoneinfo/America/Rosario,sha256=9Ij3WjT9mWMKQ43LeSUIqQuDb9zS3FSlHYPVNQJTFf0,708
+tzdata/zoneinfo/America/Santa_Isabel,sha256=r5rqSu5QUUP6XoR2Q8D_4WQZDDhBEBCsfwsXD0CYpsg,1367
+tzdata/zoneinfo/America/Santarem,sha256=dDEGsnrm4wrzl4sK6K8PzEroBKD7A1V7HBa8cWW4cMk,409
+tzdata/zoneinfo/America/Santiago,sha256=_QBpU8K0QqLh5m2yqWfdkypIJDkPAc3dnIAc5jRQxxU,1354
+tzdata/zoneinfo/America/Santo_Domingo,sha256=xmJo59mZXN7Wnf-3Jjl37mCC-8GfN6xmk2l_vngyfeI,317
+tzdata/zoneinfo/America/Sao_Paulo,sha256=-izrIi8GXAKJ85l_8MVLoFp0pZm0Uihw-oapbiThiJE,952
+tzdata/zoneinfo/America/Scoresbysund,sha256=wrhIEVAFI29qKT3TdOWiiJwI80AohXwwfb1mCPSAXHo,984
+tzdata/zoneinfo/America/Shiprock,sha256=m7cDkg7KS2EZ6BoQVYOk9soiBlHxO0GEeat81WxBPz4,1042
+tzdata/zoneinfo/America/Sitka,sha256=pF5yln--MOzEMDacNd_Id0HX9pAmge8POfcxyTNh1-0,956
+tzdata/zoneinfo/America/St_Barthelemy,sha256=q76GKN1Uh8iJ24Fs46UHe7tH9rr6_rlBHZLW7y9wzo0,177
+tzdata/zoneinfo/America/St_Johns,sha256=v99q_AFMPll5MMxMp98aqY40cmis2wciTfTqs2_kb0k,1878
+tzdata/zoneinfo/America/St_Kitts,sha256=q76GKN1Uh8iJ24Fs46UHe7tH9rr6_rlBHZLW7y9wzo0,177
+tzdata/zoneinfo/America/St_Lucia,sha256=q76GKN1Uh8iJ24Fs46UHe7tH9rr6_rlBHZLW7y9wzo0,177
+tzdata/zoneinfo/America/St_Thomas,sha256=q76GKN1Uh8iJ24Fs46UHe7tH9rr6_rlBHZLW7y9wzo0,177
+tzdata/zoneinfo/America/St_Vincent,sha256=q76GKN1Uh8iJ24Fs46UHe7tH9rr6_rlBHZLW7y9wzo0,177
+tzdata/zoneinfo/America/Swift_Current,sha256=F-b65Yaax23CsuhSmeTDl6Tv9du4IsvWvMbbSuwHkLM,368
+tzdata/zoneinfo/America/Tegucigalpa,sha256=KlvqBJGswa9DIXlE3acU-pgd4IFqDeBRrUz02PmlNC0,194
+tzdata/zoneinfo/America/Thule,sha256=LzL5jdmZkxRkHdA3XkoqJPG_ImllnSRhYYLQpMf_TY8,455
+tzdata/zoneinfo/America/Thunder_Bay,sha256=gVq023obEpKGfS-SS3GOG7oyRVzp-SIF2y_rZQKcZ2E,1717
+tzdata/zoneinfo/America/Tijuana,sha256=r5rqSu5QUUP6XoR2Q8D_4WQZDDhBEBCsfwsXD0CYpsg,1367
+tzdata/zoneinfo/America/Toronto,sha256=gVq023obEpKGfS-SS3GOG7oyRVzp-SIF2y_rZQKcZ2E,1717
+tzdata/zoneinfo/America/Tortola,sha256=q76GKN1Uh8iJ24Fs46UHe7tH9rr6_rlBHZLW7y9wzo0,177
+tzdata/zoneinfo/America/Vancouver,sha256=Epou71sUffvHB1rd7wT0krvo3okXAV45_TWcOFpy26Q,1330
+tzdata/zoneinfo/America/Virgin,sha256=q76GKN1Uh8iJ24Fs46UHe7tH9rr6_rlBHZLW7y9wzo0,177
+tzdata/zoneinfo/America/Whitehorse,sha256=CyY4jNd0fzNSdf1HlYGfaktApmH71tRNRlpOEO32DGs,1029
+tzdata/zoneinfo/America/Winnipeg,sha256=ANzwYGBU1PknQW4LR-H92i5c4Db95LU-UQhPhWZCjDo,1294
+tzdata/zoneinfo/America/Yakutat,sha256=pvHLVNA1mI-H9fBDnlnpI6B9XzVFQeyvI9nyIkaFNYQ,946
+tzdata/zoneinfo/America/Yellowknife,sha256=Dq2mxcSNWZhMWRqxwwtMcaqwAIGMwkOzz-mW8fJscV8,970
+tzdata/zoneinfo/America/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tzdata/zoneinfo/America/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/Antarctica/Casey,sha256=1jc-FAjvkKnmCjhz8-yQgEKrN_sVmzAi8DVoy9_K8AQ,287
+tzdata/zoneinfo/Antarctica/Davis,sha256=Pom_267rsoZl6yLvYllu_SW1kixIrSPmsd-HLztn33Y,197
+tzdata/zoneinfo/Antarctica/DumontDUrville,sha256=aDABBVtu-dydiHNODt3ReC8cNkO3wTp16c-OkFIAbhk,154
+tzdata/zoneinfo/Antarctica/Macquarie,sha256=aOZlIzIdTwevaTXoQkDlex2LSFDrg64GvRfcLnfCDAM,976
+tzdata/zoneinfo/Antarctica/Mawson,sha256=UYuiBSE0qZ-2kkBAa6Xq5g9NXg-W_R0P-rl2tlO0jHc,152
+tzdata/zoneinfo/Antarctica/McMurdo,sha256=Dgbn5VrtvJLvWz0Qbnw5KrFijP2KQosg6S6ZAooL-7k,1043
+tzdata/zoneinfo/Antarctica/Palmer,sha256=3MXfhQBaRB57_jqHZMl-M_K48NMFe4zALc7vaMyS5xw,887
+tzdata/zoneinfo/Antarctica/Rothera,sha256=XeddRL2YTDfEWzQI7nDqfW-Tfg-5EebxsHsMHyzGudI,132
+tzdata/zoneinfo/Antarctica/South_Pole,sha256=Dgbn5VrtvJLvWz0Qbnw5KrFijP2KQosg6S6ZAooL-7k,1043
+tzdata/zoneinfo/Antarctica/Syowa,sha256=RoU-lCdq8u6o6GwvFSqHHAkt8ZXcUSc7j8cJH6pLRhw,133
+tzdata/zoneinfo/Antarctica/Troll,sha256=s4z0F_uKzx3biKjEzvHwb56132XRs6IR22fCQglW5GI,158
+tzdata/zoneinfo/Antarctica/Vostok,sha256=cDp-B4wKXE8U5b_zqJIlxdGY-AIAMCTJOZG3bRZBKNc,170
+tzdata/zoneinfo/Antarctica/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tzdata/zoneinfo/Antarctica/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/Arctic/Longyearbyen,sha256=p_2ZMteF1NaQkAuDTDVjwYEMHPLgFxG8wJJq9sB2fLc,705
+tzdata/zoneinfo/Arctic/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tzdata/zoneinfo/Arctic/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/Asia/Aden,sha256=RoU-lCdq8u6o6GwvFSqHHAkt8ZXcUSc7j8cJH6pLRhw,133
+tzdata/zoneinfo/Asia/Almaty,sha256=87WNMKCF7W2V6tq5LvX5DXWoi9MuwjCAY3f9dgwui4s,618
+tzdata/zoneinfo/Asia/Amman,sha256=KOnKO4_1XRlQvLG61GTbfKImSthwBHMSnzV1ExW8i5Q,928
+tzdata/zoneinfo/Asia/Anadyr,sha256=30bdZurg4Q__lCpH509TE0U7pOcEY6qxjvuPF9ai5yc,743
+tzdata/zoneinfo/Asia/Aqtau,sha256=bRj27vG5HvGegFg5eIKNmq3dfteYmr7KmTs4JFO-7SM,606
+tzdata/zoneinfo/Asia/Aqtobe,sha256=Pm7yI5cmfzx8CGXR2mQJDjtH12KCpx8ezFKchiJVVJ4,615
+tzdata/zoneinfo/Asia/Ashgabat,sha256=OTLHdQ8jFPDvxu_IwKX_c3W3jdN6e7FGoCSEEb0XKuw,375
+tzdata/zoneinfo/Asia/Ashkhabad,sha256=OTLHdQ8jFPDvxu_IwKX_c3W3jdN6e7FGoCSEEb0XKuw,375
+tzdata/zoneinfo/Asia/Atyrau,sha256=1YG4QzLxPRZQeGHiOrbm0cRs8ERTNg1NF9dWEwW2Pi0,616
+tzdata/zoneinfo/Asia/Baghdad,sha256=zFe6LXSfuoJjGsmYTMGjJtBcAMLiKFkD7j7-VaqKwH8,630
+tzdata/zoneinfo/Asia/Bahrain,sha256=YWDWV1o3HHWxnmwlzwMWC53C84ZYPkK_gYn9-P0Xx4U,152
+tzdata/zoneinfo/Asia/Baku,sha256=_Wh6ONaRatMc9lpwGO6zB9pTE38NZ4oWg4_-sZl17mA,744
+tzdata/zoneinfo/Asia/Bangkok,sha256=zcjiwoLYvJpenDyvL8Rf9OnlzRj13sjLhzNArXxYTWQ,152
+tzdata/zoneinfo/Asia/Barnaul,sha256=UGFYJYvtgYVS8Tqsqvj6p0OQCmN3zdY9wITWg8ODG-k,753
+tzdata/zoneinfo/Asia/Beirut,sha256=FgM4gqbWFp6KuUnVn-H8UIXZgTydBeOxDdbebJ0GpUc,732
+tzdata/zoneinfo/Asia/Bishkek,sha256=RXdxVxaiE5zxX5atQl-7ZesEeZVjsCXBGZ6cJbVU9pE,618
+tzdata/zoneinfo/Asia/Brunei,sha256=3ajgII3xZ-Wc-dqXRTSMw8qQRDSjXlSBIxyE_sDRGTk,320
+tzdata/zoneinfo/Asia/Calcutta,sha256=OgC9vhvElZ5ydWfHMLpRsDRV7NRV98GQxa0UOG63mw0,220
+tzdata/zoneinfo/Asia/Chita,sha256=1Lme3ccO47R5gmTe5VCq1BSb0m_1opWibq21zvZlntg,750
+tzdata/zoneinfo/Asia/Choibalsan,sha256=--I8P6_e4BtRIe3wCSkPtwHOu_k9rPsw-KqQKHJC9vM,594
+tzdata/zoneinfo/Asia/Chongqing,sha256=v4t-2C_m5j5tmPjOqTTurJAc0Wq6hetXVc4_i0KJ6oo,393
+tzdata/zoneinfo/Asia/Chungking,sha256=v4t-2C_m5j5tmPjOqTTurJAc0Wq6hetXVc4_i0KJ6oo,393
+tzdata/zoneinfo/Asia/Colombo,sha256=QAyjK7gtXUWfLuju1M0H3_ew6iTM-bwfzO5obgvaHy8,247
+tzdata/zoneinfo/Asia/Dacca,sha256=rCGmEwbW4qkUU2QfTj5zLrydVCq8HTWl1dsqEDQOvvo,231
+tzdata/zoneinfo/Asia/Damascus,sha256=AtZTDRzHEB7QnKxFXvtWsNUI1cCCe27sAfpDfQd0MwY,1234
+tzdata/zoneinfo/Asia/Dhaka,sha256=rCGmEwbW4qkUU2QfTj5zLrydVCq8HTWl1dsqEDQOvvo,231
+tzdata/zoneinfo/Asia/Dili,sha256=5fcCHkVIZkLV8TcsqBQ8HstILEpz3ay3MGGU6sgNxLA,170
+tzdata/zoneinfo/Asia/Dubai,sha256=DZ6lBT6DGIAypvtNMB1dtoj0MBHltrH5F6EbcaDaexY,133
+tzdata/zoneinfo/Asia/Dushanbe,sha256=8qbn76rf9xu47NYVdfGvjnkf2KZxNN5J8ekFiXUz3AQ,366
+tzdata/zoneinfo/Asia/Famagusta,sha256=385fbaRnx-mdEaXqSyBKVBDDKPzCGKbynWYt75wwCug,940
+tzdata/zoneinfo/Asia/Gaza,sha256=-PC__gGODaDGgv5LLzH7ptNLbNdStPkxGY4LmebvcNU,2950
+tzdata/zoneinfo/Asia/Harbin,sha256=v4t-2C_m5j5tmPjOqTTurJAc0Wq6hetXVc4_i0KJ6oo,393
+tzdata/zoneinfo/Asia/Hebron,sha256=4FujfuE-ECIXgKW4pv0lxq2ZkAj7jDwt0rezuA0fFzg,2968
+tzdata/zoneinfo/Asia/Ho_Chi_Minh,sha256=R-ReVMreMcETG0Sifjfe5z-PgQpUsKjT6dVbEKzT3sE,236
+tzdata/zoneinfo/Asia/Hong_Kong,sha256=9AaPcyRtuXQX9zRnRTVkxX1mRs5JCbn6JTaSPvzX608,775
+tzdata/zoneinfo/Asia/Hovd,sha256=eqAvD2RfuIfSDhtqk58MECIjz5X14OHZ7aO4z14kndk,594
+tzdata/zoneinfo/Asia/Irkutsk,sha256=sWxp8g_aSfFan4ZyF9s6-pEX5Vgwxi_jNv7vwN06XIo,760
+tzdata/zoneinfo/Asia/Istanbul,sha256=KnFjsWuUgG9pmRNI59CmDEbrYbHwMF9fS4P2E9sQgG8,1200
+tzdata/zoneinfo/Asia/Jakarta,sha256=4qCZ6kix9xZriNIZsyb3xENz0IkJzZcjtENGlG_Wo4Q,248
+tzdata/zoneinfo/Asia/Jayapura,sha256=BUa0kX1iOdf0E-v7415h7l0lQv4DBCYX_3dAbYmQ0xU,171
+tzdata/zoneinfo/Asia/Jerusalem,sha256=n83o1YTeoFhfXIcnqvNfSKFJ4NvTqDv2zvi8qcFAIeM,1074
+tzdata/zoneinfo/Asia/Kabul,sha256=pNIwTfiSG71BGKvrhKqo1xdxckAx9vfcx5nJanrL81Q,159
+tzdata/zoneinfo/Asia/Kamchatka,sha256=Qix8x3s-m8UTeiwzNPBy_ZQvAzX_aaihz_PzLfTiUac,727
+tzdata/zoneinfo/Asia/Karachi,sha256=ujo4wv-3oa9tfrFT5jsLcEYcjeGeBRgG2QwdXg_ijU4,266
+tzdata/zoneinfo/Asia/Kashgar,sha256=hJyv03dhHML8K0GJGrY8b7M0OUkEXblh_RYmdZMxWtQ,133
+tzdata/zoneinfo/Asia/Kathmandu,sha256=drjxv-ByIxodnn-FATEOJ8DQgEjEj3Qihgtkd8FCxDg,161
+tzdata/zoneinfo/Asia/Katmandu,sha256=drjxv-ByIxodnn-FATEOJ8DQgEjEj3Qihgtkd8FCxDg,161
+tzdata/zoneinfo/Asia/Khandyga,sha256=fdEDOsDJkLuENybqIXtTiI4k2e24dKHDfBTww9AtbSw,775
+tzdata/zoneinfo/Asia/Kolkata,sha256=OgC9vhvElZ5ydWfHMLpRsDRV7NRV98GQxa0UOG63mw0,220
+tzdata/zoneinfo/Asia/Krasnoyarsk,sha256=buNI5S1g7eedK-PpnrLkBFFZDUyCtHxcxXDQGF2ARos,741
+tzdata/zoneinfo/Asia/Kuala_Lumpur,sha256=CVSy2aMB2U9DSAJGBqcbvLL6JNPNNwn1vIvKYFA5eF0,256
+tzdata/zoneinfo/Asia/Kuching,sha256=3ajgII3xZ-Wc-dqXRTSMw8qQRDSjXlSBIxyE_sDRGTk,320
+tzdata/zoneinfo/Asia/Kuwait,sha256=RoU-lCdq8u6o6GwvFSqHHAkt8ZXcUSc7j8cJH6pLRhw,133
+tzdata/zoneinfo/Asia/Macao,sha256=mr89i_wpMoWhAtqZrF2SGcoILcUw6rYrDkIUNADes7E,791
+tzdata/zoneinfo/Asia/Macau,sha256=mr89i_wpMoWhAtqZrF2SGcoILcUw6rYrDkIUNADes7E,791
+tzdata/zoneinfo/Asia/Magadan,sha256=wAufMGWL_s1Aw2l3myAfBFtrROVPes3dMoNuDEoNwT8,751
+tzdata/zoneinfo/Asia/Makassar,sha256=NV9j_RTuiU47mvJvfKE8daXH5AFYJ8Ki4gvHBJSxyLc,190
+tzdata/zoneinfo/Asia/Manila,sha256=FoGmIyFInHknfE103PbiD65GUwsmnYWzF5oGys03BqY,274
+tzdata/zoneinfo/Asia/Muscat,sha256=DZ6lBT6DGIAypvtNMB1dtoj0MBHltrH5F6EbcaDaexY,133
+tzdata/zoneinfo/Asia/Nicosia,sha256=TYYqWp8sK0AwBUHAp0wuuihZuQ19RXdt28bth33zOBI,597
+tzdata/zoneinfo/Asia/Novokuznetsk,sha256=aYW9rpcxpf_zrOZc2vmpcqgiuCRKMHB1lMrioI43KCw,726
+tzdata/zoneinfo/Asia/Novosibirsk,sha256=I2n4MCElad9sMcyJAAc4YdVT6ewbhR79OoAAuhEJfCY,753
+tzdata/zoneinfo/Asia/Omsk,sha256=y7u47EObB3wI8MxKHBRTFM-BEZZqhGpzDg7x5lcwJXY,741
+tzdata/zoneinfo/Asia/Oral,sha256=Q-Gf85NIvdAtU52Zkgf78rVHPlg85xyMe9Zm9ybh0po,625
+tzdata/zoneinfo/Asia/Phnom_Penh,sha256=zcjiwoLYvJpenDyvL8Rf9OnlzRj13sjLhzNArXxYTWQ,152
+tzdata/zoneinfo/Asia/Pontianak,sha256=o0x0jNTlwjiUqAzGX_HlzvCMru2zUURgQ4xzpS95xds,247
+tzdata/zoneinfo/Asia/Pyongyang,sha256=NxC5da8oTZ4StiFQnlhjlp9FTRuMM-Xwsq3Yg4y0xkA,183
+tzdata/zoneinfo/Asia/Qatar,sha256=YWDWV1o3HHWxnmwlzwMWC53C84ZYPkK_gYn9-P0Xx4U,152
+tzdata/zoneinfo/Asia/Qostanay,sha256=5tZkj1o0p4vaREsPO0YgIiw6eDf1cqO52x-0EMg_2L4,624
+tzdata/zoneinfo/Asia/Qyzylorda,sha256=JltKDEnuHmIQGYdFTAJMDDpdDA_HxjJOAHHaV7kFrlQ,624
+tzdata/zoneinfo/Asia/Rangoon,sha256=6J2DXIEdTaRKqLOGeCzogo3whaoO6PJWYamIHS8A6Qw,187
+tzdata/zoneinfo/Asia/Riyadh,sha256=RoU-lCdq8u6o6GwvFSqHHAkt8ZXcUSc7j8cJH6pLRhw,133
+tzdata/zoneinfo/Asia/Saigon,sha256=R-ReVMreMcETG0Sifjfe5z-PgQpUsKjT6dVbEKzT3sE,236
+tzdata/zoneinfo/Asia/Sakhalin,sha256=M_TBd-03j-3Yc9KwhGEoBTwSJxWO1lPBG7ndst16PGo,755
+tzdata/zoneinfo/Asia/Samarkand,sha256=KZ_q-6GMDVgJb8RFqcrbVcPC0WLczolClC4nZA1HVNU,366
+tzdata/zoneinfo/Asia/Seoul,sha256=ZKcLb7zJtl52Lb0l64m29AwTcUbtyNvU0IHq-s2reN4,415
+tzdata/zoneinfo/Asia/Shanghai,sha256=v4t-2C_m5j5tmPjOqTTurJAc0Wq6hetXVc4_i0KJ6oo,393
+tzdata/zoneinfo/Asia/Singapore,sha256=CVSy2aMB2U9DSAJGBqcbvLL6JNPNNwn1vIvKYFA5eF0,256
+tzdata/zoneinfo/Asia/Srednekolymsk,sha256=06mojetFbDd4ag1p8NK0Fg6rF2OOnZMFRRC90N2ATZc,742
+tzdata/zoneinfo/Asia/Taipei,sha256=oEwscvT3aoMXjQNt2X0VfuHzLkeORN2npcEJI2h-5s8,511
+tzdata/zoneinfo/Asia/Tashkent,sha256=0vpN2gI9GY50z1nea6zCPFf2B6VCu6XQQHx4l6rhnTI,366
+tzdata/zoneinfo/Asia/Tbilisi,sha256=ON_Uzv2VTSk6mRefNU-aI-qkqtCoUX6oECVqpeS42eI,629
+tzdata/zoneinfo/Asia/Tehran,sha256=ZaxewB83IdYIGVpJvcp8esyz3iffAgxEzsj7cMraQ3c,812
+tzdata/zoneinfo/Asia/Tel_Aviv,sha256=n83o1YTeoFhfXIcnqvNfSKFJ4NvTqDv2zvi8qcFAIeM,1074
+tzdata/zoneinfo/Asia/Thimbu,sha256=N6d_vfFvYORfMnr1fHJjYSt4DBORSbLi_2T-r2dJBnI,154
+tzdata/zoneinfo/Asia/Thimphu,sha256=N6d_vfFvYORfMnr1fHJjYSt4DBORSbLi_2T-r2dJBnI,154
+tzdata/zoneinfo/Asia/Tokyo,sha256=WaOHFDDw07k-YZ-jCkOkHR6IvdSf8m8J0PQFpQBwb5Y,213
+tzdata/zoneinfo/Asia/Tomsk,sha256=Bf7GoFTcUeP2hYyuYpruJji33tcEoLP-80o38A6i4zU,753
+tzdata/zoneinfo/Asia/Ujung_Pandang,sha256=NV9j_RTuiU47mvJvfKE8daXH5AFYJ8Ki4gvHBJSxyLc,190
+tzdata/zoneinfo/Asia/Ulaanbaatar,sha256=--I8P6_e4BtRIe3wCSkPtwHOu_k9rPsw-KqQKHJC9vM,594
+tzdata/zoneinfo/Asia/Ulan_Bator,sha256=--I8P6_e4BtRIe3wCSkPtwHOu_k9rPsw-KqQKHJC9vM,594
+tzdata/zoneinfo/Asia/Urumqi,sha256=hJyv03dhHML8K0GJGrY8b7M0OUkEXblh_RYmdZMxWtQ,133
+tzdata/zoneinfo/Asia/Ust-Nera,sha256=6NkuV1zOms-4qHQhq-cGc-cqEVgKHk7qd3MLDM-e2BA,771
+tzdata/zoneinfo/Asia/Vientiane,sha256=zcjiwoLYvJpenDyvL8Rf9OnlzRj13sjLhzNArXxYTWQ,152
+tzdata/zoneinfo/Asia/Vladivostok,sha256=zkOXuEDgpxX8HQGgDlh9SbAQzHOaNxX2XSI6Y4gMD-k,742
+tzdata/zoneinfo/Asia/Yakutsk,sha256=xD6zA4E228dC1mIUQ7cMO-9LORSfE-Fok0awGDG6juk,741
+tzdata/zoneinfo/Asia/Yangon,sha256=6J2DXIEdTaRKqLOGeCzogo3whaoO6PJWYamIHS8A6Qw,187
+tzdata/zoneinfo/Asia/Yekaterinburg,sha256=q17eUyqOEK2LJYKXYLCJqylj-vmaCG2vSNMttqrQTRk,760
+tzdata/zoneinfo/Asia/Yerevan,sha256=pLEBdchA8H9l-9hdA6FjHmwaj5T1jupK0u-bor1KKa0,708
+tzdata/zoneinfo/Asia/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tzdata/zoneinfo/Asia/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/Atlantic/Azores,sha256=6XBp-rgg8hERTe2c-bTKahYPlkDn2sROBuqo9wAdtPE,1401
+tzdata/zoneinfo/Atlantic/Bermuda,sha256=PuxqD2cD99Pzjb8hH99Dws053d_zXnZHjeH0kZ8LSLI,1024
+tzdata/zoneinfo/Atlantic/Canary,sha256=XMmxBlscPIWXhiauKy_d5bxX4xjNMM-5Vw84FwZkT00,478
+tzdata/zoneinfo/Atlantic/Cape_Verde,sha256=E5ss6xpIpD0g_VEDsFMFi-ltsebp98PBSpULoVxIAyU,175
+tzdata/zoneinfo/Atlantic/Faeroe,sha256=Iw0qB0mBuviH5w3Qy8jaxCOes07ZHh2wkW8MPUWJqj0,441
+tzdata/zoneinfo/Atlantic/Faroe,sha256=Iw0qB0mBuviH5w3Qy8jaxCOes07ZHh2wkW8MPUWJqj0,441
+tzdata/zoneinfo/Atlantic/Jan_Mayen,sha256=p_2ZMteF1NaQkAuDTDVjwYEMHPLgFxG8wJJq9sB2fLc,705
+tzdata/zoneinfo/Atlantic/Madeira,sha256=2F3vLmp7OTm4ZMSLxyIVQQ6iXeGUkKKPeUdiGmqVuuI,1372
+tzdata/zoneinfo/Atlantic/Reykjavik,sha256=8-f8qg6YQP9BadNWfY-1kmZEhI9JY9es-SMghDxdSG4,130
+tzdata/zoneinfo/Atlantic/South_Georgia,sha256=kPGfCLQD2C6_Xc5TyAmqmXP-GYdLLPucpBn3S7ybWu8,132
+tzdata/zoneinfo/Atlantic/St_Helena,sha256=8-f8qg6YQP9BadNWfY-1kmZEhI9JY9es-SMghDxdSG4,130
+tzdata/zoneinfo/Atlantic/Stanley,sha256=QqQd8IWklNapMKjN5vF7vvVn4K-yl3VKvM5zkCKabCM,789
+tzdata/zoneinfo/Atlantic/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tzdata/zoneinfo/Atlantic/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/Australia/ACT,sha256=gg1FqGioj4HHMdWyx1i07QAAObYmCoBDP44PCUpgS1k,904
+tzdata/zoneinfo/Australia/Adelaide,sha256=Gk1SdGRVmB233I-WETXAMCZz7L7HVzoN4aUoIcgNr3g,921
+tzdata/zoneinfo/Australia/Brisbane,sha256=2kVWz9CI_qtfdb55g0iL59gUBC7lnO3GUalIQxtHADY,289
+tzdata/zoneinfo/Australia/Broken_Hill,sha256=dzk9LvGA_xRStnAIjAFuTJ8Uwz_s7qGWGQmiXPgDsLY,941
+tzdata/zoneinfo/Australia/Canberra,sha256=gg1FqGioj4HHMdWyx1i07QAAObYmCoBDP44PCUpgS1k,904
+tzdata/zoneinfo/Australia/Currie,sha256=1IAVgf0AA3sBPXFhaxGfu9UQ_cpd4GNpsQ9xio2l4y0,1003
+tzdata/zoneinfo/Australia/Darwin,sha256=ZoexbhgdUlV4leV-dhBu6AxDVkJy43xrPb9UQ3EQCdI,234
+tzdata/zoneinfo/Australia/Eucla,sha256=3NqsFfMzR6-lSUPViNXBAOyJPqyokisse7uDXurURpk,314
+tzdata/zoneinfo/Australia/Hobart,sha256=1IAVgf0AA3sBPXFhaxGfu9UQ_cpd4GNpsQ9xio2l4y0,1003
+tzdata/zoneinfo/Australia/LHI,sha256=82i9JWWcApPQK7eex9rH1bc6kt_6_OFLTdL_uLoRqto,692
+tzdata/zoneinfo/Australia/Lindeman,sha256=iHkCc0QJ7iaQffiTTXQVJ2swsC7QJxLUMHQOGCFlkTk,325
+tzdata/zoneinfo/Australia/Lord_Howe,sha256=82i9JWWcApPQK7eex9rH1bc6kt_6_OFLTdL_uLoRqto,692
+tzdata/zoneinfo/Australia/Melbourne,sha256=X7JPMEj_SYWyfgWFMkp6FOmT6GfyjR-lF9hFGgTavnE,904
+tzdata/zoneinfo/Australia/NSW,sha256=gg1FqGioj4HHMdWyx1i07QAAObYmCoBDP44PCUpgS1k,904
+tzdata/zoneinfo/Australia/North,sha256=ZoexbhgdUlV4leV-dhBu6AxDVkJy43xrPb9UQ3EQCdI,234
+tzdata/zoneinfo/Australia/Perth,sha256=ZsuelcBC1YfWugH2CrlOXQcSDD4gGUJCobB1W-aupHo,306
+tzdata/zoneinfo/Australia/Queensland,sha256=2kVWz9CI_qtfdb55g0iL59gUBC7lnO3GUalIQxtHADY,289
+tzdata/zoneinfo/Australia/South,sha256=Gk1SdGRVmB233I-WETXAMCZz7L7HVzoN4aUoIcgNr3g,921
+tzdata/zoneinfo/Australia/Sydney,sha256=gg1FqGioj4HHMdWyx1i07QAAObYmCoBDP44PCUpgS1k,904
+tzdata/zoneinfo/Australia/Tasmania,sha256=1IAVgf0AA3sBPXFhaxGfu9UQ_cpd4GNpsQ9xio2l4y0,1003
+tzdata/zoneinfo/Australia/Victoria,sha256=X7JPMEj_SYWyfgWFMkp6FOmT6GfyjR-lF9hFGgTavnE,904
+tzdata/zoneinfo/Australia/West,sha256=ZsuelcBC1YfWugH2CrlOXQcSDD4gGUJCobB1W-aupHo,306
+tzdata/zoneinfo/Australia/Yancowinna,sha256=dzk9LvGA_xRStnAIjAFuTJ8Uwz_s7qGWGQmiXPgDsLY,941
+tzdata/zoneinfo/Australia/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tzdata/zoneinfo/Australia/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/Brazil/Acre,sha256=VjuQUr668phq5bcH40r94BPnZBKHzJf_MQBfM6Db96U,418
+tzdata/zoneinfo/Brazil/DeNoronha,sha256=Q0r3GtA5y2RGkOj56OTZG5tuBy1B6kfbhyrJqCgf27g,484
+tzdata/zoneinfo/Brazil/East,sha256=-izrIi8GXAKJ85l_8MVLoFp0pZm0Uihw-oapbiThiJE,952
+tzdata/zoneinfo/Brazil/West,sha256=9kgrhpryB94YOVoshJliiiDSf9mwjb3OZwX0HusNRrk,412
+tzdata/zoneinfo/Brazil/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tzdata/zoneinfo/Brazil/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/CET,sha256=sQ-VQqhQnwpj68p449gEMt2GuOopZAAoD-vZz6dugog,1103
+tzdata/zoneinfo/CST6CDT,sha256=wntzn_RqffBZThINcltDkhfhHkTqmlDNxJEwODtUguc,1754
+tzdata/zoneinfo/Canada/Atlantic,sha256=kO5ahBM2oTLfWS4KX15FbKXfo5wg-f9vw1_hMOISGig,1672
+tzdata/zoneinfo/Canada/Central,sha256=ANzwYGBU1PknQW4LR-H92i5c4Db95LU-UQhPhWZCjDo,1294
+tzdata/zoneinfo/Canada/Eastern,sha256=gVq023obEpKGfS-SS3GOG7oyRVzp-SIF2y_rZQKcZ2E,1717
+tzdata/zoneinfo/Canada/Mountain,sha256=Dq2mxcSNWZhMWRqxwwtMcaqwAIGMwkOzz-mW8fJscV8,970
+tzdata/zoneinfo/Canada/Newfoundland,sha256=v99q_AFMPll5MMxMp98aqY40cmis2wciTfTqs2_kb0k,1878
+tzdata/zoneinfo/Canada/Pacific,sha256=Epou71sUffvHB1rd7wT0krvo3okXAV45_TWcOFpy26Q,1330
+tzdata/zoneinfo/Canada/Saskatchewan,sha256=_JHuns225iE-THc9NFp-RBq4PWULAuGw2OLbpOB_UMw,638
+tzdata/zoneinfo/Canada/Yukon,sha256=CyY4jNd0fzNSdf1HlYGfaktApmH71tRNRlpOEO32DGs,1029
+tzdata/zoneinfo/Canada/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tzdata/zoneinfo/Canada/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/Chile/Continental,sha256=_QBpU8K0QqLh5m2yqWfdkypIJDkPAc3dnIAc5jRQxxU,1354
+tzdata/zoneinfo/Chile/EasterIsland,sha256=EwVM74XjsboPVxK9bWmdd4nTrtvasP1zlLdxrMB_YaE,1174
+tzdata/zoneinfo/Chile/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tzdata/zoneinfo/Chile/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/Cuba,sha256=ms5rCuq2yBM49VmTymMtFQN3c5aBN1lkd8jjzKdnNm8,1117
+tzdata/zoneinfo/EET,sha256=8f1niwVI4ymziTT2KBJV5pjfp2GtH_hB9sy3lgbGE0U,682
+tzdata/zoneinfo/EST,sha256=p41zBnujy9lPiiPf3WqotoyzOxhIS8F7TiDqGuwvCoE,149
+tzdata/zoneinfo/EST5EDT,sha256=1_IgazpFmJ_JrWPVWJIlMvpzUigNX4cXa_HbecsdH6k,1744
+tzdata/zoneinfo/Egypt,sha256=icuaNiEvuC6TPc2fqhDv36lpop7IDDIGO7tFGMAz0b4,1309
+tzdata/zoneinfo/Eire,sha256=EcADNuAvExj-dkqylGfF8q_vv_-mRPqN0k9bCDtJW3E,1496
+tzdata/zoneinfo/Etc/GMT,sha256=3EoHVxsQiE5PTzRQydGhy_TAPvU9Bu0uTqFS2eul1dc,111
+tzdata/zoneinfo/Etc/GMT+0,sha256=3EoHVxsQiE5PTzRQydGhy_TAPvU9Bu0uTqFS2eul1dc,111
+tzdata/zoneinfo/Etc/GMT+1,sha256=5L9o8TEUgtB11poIag85vRdq08LMDZmZ6DPn7UqPL_g,113
+tzdata/zoneinfo/Etc/GMT+10,sha256=IvBxiqQU76qzNbuxRo8Ah9rPQSRGQGKp_SRs5u1PPkM,114
+tzdata/zoneinfo/Etc/GMT+11,sha256=9MfFpFp_rt9PksMjQ23VOlir3hzTlnLz_5V2tfonhbU,114
+tzdata/zoneinfo/Etc/GMT+12,sha256=l26XCFp9IbgXGvMw7NHgHzIZbHry2B5qGYfhMDHFVrw,114
+tzdata/zoneinfo/Etc/GMT+2,sha256=YbbqH7B6jNoQEIjyV4-8a2cXD9lGC3vQKnEkY2ucDGI,113
+tzdata/zoneinfo/Etc/GMT+3,sha256=q3D9DLfmTBUAo4YMnNUNUUKrAkKSwM5Q-vesd9A6SZQ,113
+tzdata/zoneinfo/Etc/GMT+4,sha256=UghKME3laXSDZ7q74YDb4FcLnzNqXQydcZpQHvssP2k,113
+tzdata/zoneinfo/Etc/GMT+5,sha256=TZ5qaoELlszW_Z5FdqAEMKk8Y_xu5XhZBNZUco55SrM,113
+tzdata/zoneinfo/Etc/GMT+6,sha256=_2k3LZ5x8hVjMwwmCx6GqUwW-v1IvOkBrJjYH5bD6Qw,113
+tzdata/zoneinfo/Etc/GMT+7,sha256=Di8J430WGr98Ww95tdfIo8hGxkVQfJvlx55ansDuoeQ,113
+tzdata/zoneinfo/Etc/GMT+8,sha256=OIIlUFhZwL2ctx3fxINbY2HDDAmSQ7i2ZAUgX7Exjgw,113
+tzdata/zoneinfo/Etc/GMT+9,sha256=1vpkIoPqBiwDWzH-fLFxwNbmdKRY7mqdiJhYQImVxaw,113
+tzdata/zoneinfo/Etc/GMT-0,sha256=3EoHVxsQiE5PTzRQydGhy_TAPvU9Bu0uTqFS2eul1dc,111
+tzdata/zoneinfo/Etc/GMT-1,sha256=S81S9Z0-V-0B5U-0S0Pnbx8fv2iHtwE1LrlZk-ckLto,114
+tzdata/zoneinfo/Etc/GMT-10,sha256=VvdG5IpXB_xJX4omzfrrHblkRUzkbCZXPhTrLngc7vk,115
+tzdata/zoneinfo/Etc/GMT-11,sha256=2sYLfVuDFSy7Kc1WOPiY1EqquHw5Xx4HbDA1QOL1hc4,115
+tzdata/zoneinfo/Etc/GMT-12,sha256=ifHVhk5fczZG3GDy_Nv7YsLNaxf8stB4MrzgWUCINlU,115
+tzdata/zoneinfo/Etc/GMT-13,sha256=CMkORdXsaSyL-4N0n37Cyc1lCr22ZsWyug9_QZVe0E0,115
+tzdata/zoneinfo/Etc/GMT-14,sha256=NK07ElwueU0OP8gORtcXUUug_3v4d04uxfVHMUnLM9U,115
+tzdata/zoneinfo/Etc/GMT-2,sha256=QMToMLcif1S4SNPOMxMtBLqc1skUYnIhbUAjKEdAf9w,114
+tzdata/zoneinfo/Etc/GMT-3,sha256=10GMvfulaJwDQiHiWEJiU_YURyjDfPcl5ugnYBugN3E,114
+tzdata/zoneinfo/Etc/GMT-4,sha256=c6Kx3v41GRkrvky8k71db_UJbpyyp2OZCsjDSvjkr6s,114
+tzdata/zoneinfo/Etc/GMT-5,sha256=94TvO8e_8t52bs8ry70nAquvgK8qJKQTI7lQnVCHX-U,114
+tzdata/zoneinfo/Etc/GMT-6,sha256=3fH8eX--0iDijmYAQHQ0IUXheezaj6-aadZsQNAB4fE,114
+tzdata/zoneinfo/Etc/GMT-7,sha256=DnsTJ3NUYYGLUwFb_L15U_GbaMF-acLVsPyTNySyH-M,114
+tzdata/zoneinfo/Etc/GMT-8,sha256=kvGQUwONDBG7nhEp_wESc4xl4xNXiXEivxAv09nkr_g,114
+tzdata/zoneinfo/Etc/GMT-9,sha256=U1WRFGWQAW91JXK99gY1K9d0rFZYDWHzDUR3z71Lh6Y,114
+tzdata/zoneinfo/Etc/GMT0,sha256=3EoHVxsQiE5PTzRQydGhy_TAPvU9Bu0uTqFS2eul1dc,111
+tzdata/zoneinfo/Etc/Greenwich,sha256=3EoHVxsQiE5PTzRQydGhy_TAPvU9Bu0uTqFS2eul1dc,111
+tzdata/zoneinfo/Etc/UCT,sha256=_dzh5kihcyrCmv2aFhUbKXPN8ILn7AxpD35CvmtZi5M,111
+tzdata/zoneinfo/Etc/UTC,sha256=_dzh5kihcyrCmv2aFhUbKXPN8ILn7AxpD35CvmtZi5M,111
+tzdata/zoneinfo/Etc/Universal,sha256=_dzh5kihcyrCmv2aFhUbKXPN8ILn7AxpD35CvmtZi5M,111
+tzdata/zoneinfo/Etc/Zulu,sha256=_dzh5kihcyrCmv2aFhUbKXPN8ILn7AxpD35CvmtZi5M,111
+tzdata/zoneinfo/Etc/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tzdata/zoneinfo/Etc/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/Europe/Amsterdam,sha256=sQ-VQqhQnwpj68p449gEMt2GuOopZAAoD-vZz6dugog,1103
+tzdata/zoneinfo/Europe/Andorra,sha256=leuTyE4uduIBX0aHb_7PK_KlslpWSyS6e0SS84hKFrE,389
+tzdata/zoneinfo/Europe/Astrakhan,sha256=P3E5UDgQ4gqsMi-KdMAWwOSStogdcNl9rLMVUdpFLXI,726
+tzdata/zoneinfo/Europe/Athens,sha256=8f1niwVI4ymziTT2KBJV5pjfp2GtH_hB9sy3lgbGE0U,682
+tzdata/zoneinfo/Europe/Belfast,sha256=Z2VB8LitRXx0TAk_gHWJrcrZCeP9A_kBeH0IeG7tvTM,1599
+tzdata/zoneinfo/Europe/Belgrade,sha256=qMlk8-qnognZplD7FsaMAD6aX8Yv-7sQ-oSdVPs2YtY,478
+tzdata/zoneinfo/Europe/Berlin,sha256=p_2ZMteF1NaQkAuDTDVjwYEMHPLgFxG8wJJq9sB2fLc,705
+tzdata/zoneinfo/Europe/Bratislava,sha256=pukw4zdc3LUffYp0iFr_if0UuGHrt1yzOdD5HBbBRpo,723
+tzdata/zoneinfo/Europe/Brussels,sha256=sQ-VQqhQnwpj68p449gEMt2GuOopZAAoD-vZz6dugog,1103
+tzdata/zoneinfo/Europe/Bucharest,sha256=iY74H96aaTMJvmqAhzUoSI8SjZUtPvv4PGF4ClwFm6U,661
+tzdata/zoneinfo/Europe/Budapest,sha256=qNr-valoDI1mevuQXqOMkOhIcT194EczOKIijxrDMV8,766
+tzdata/zoneinfo/Europe/Busingen,sha256=GZBiscMM_rI3XshMVt9SvlGJGYamKTt6Ek06YlCfRek,497
+tzdata/zoneinfo/Europe/Chisinau,sha256=5TPhkCtxxa0ByLCv7YxOrc5Vtdui2v2VX8vrSopPkPs,755
+tzdata/zoneinfo/Europe/Copenhagen,sha256=p_2ZMteF1NaQkAuDTDVjwYEMHPLgFxG8wJJq9sB2fLc,705
+tzdata/zoneinfo/Europe/Dublin,sha256=EcADNuAvExj-dkqylGfF8q_vv_-mRPqN0k9bCDtJW3E,1496
+tzdata/zoneinfo/Europe/Gibraltar,sha256=t1hglDTLUIFqs91nY5lulN7oxkoAXHnh0zjyaKG2bG8,1220
+tzdata/zoneinfo/Europe/Guernsey,sha256=Z2VB8LitRXx0TAk_gHWJrcrZCeP9A_kBeH0IeG7tvTM,1599
+tzdata/zoneinfo/Europe/Helsinki,sha256=ccpK9ZmPCZkMXoddNQ_DyONPKAuub-FPNtRpL6znpWM,481
+tzdata/zoneinfo/Europe/Isle_of_Man,sha256=Z2VB8LitRXx0TAk_gHWJrcrZCeP9A_kBeH0IeG7tvTM,1599
+tzdata/zoneinfo/Europe/Istanbul,sha256=KnFjsWuUgG9pmRNI59CmDEbrYbHwMF9fS4P2E9sQgG8,1200
+tzdata/zoneinfo/Europe/Jersey,sha256=Z2VB8LitRXx0TAk_gHWJrcrZCeP9A_kBeH0IeG7tvTM,1599
+tzdata/zoneinfo/Europe/Kaliningrad,sha256=57ov9G8m25w1pPdJF8zoFWzq5I6UoBMVsk2eHPelbA8,904
+tzdata/zoneinfo/Europe/Kiev,sha256=BYnoDd7Ov50wd4mMEpddK-c5PfKFbumSbFNHY-Hia_I,558
+tzdata/zoneinfo/Europe/Kirov,sha256=KqXGcIbMGTuOoKZYBG-5bj7kVzFbKyGMA99PA0414D0,735
+tzdata/zoneinfo/Europe/Kyiv,sha256=BYnoDd7Ov50wd4mMEpddK-c5PfKFbumSbFNHY-Hia_I,558
+tzdata/zoneinfo/Europe/Lisbon,sha256=RNL2z4RzfmoeDa-RQQnpQla-ykC0DJoRt6BOi92u5Ow,1463
+tzdata/zoneinfo/Europe/Ljubljana,sha256=qMlk8-qnognZplD7FsaMAD6aX8Yv-7sQ-oSdVPs2YtY,478
+tzdata/zoneinfo/Europe/London,sha256=Z2VB8LitRXx0TAk_gHWJrcrZCeP9A_kBeH0IeG7tvTM,1599
+tzdata/zoneinfo/Europe/Luxembourg,sha256=sQ-VQqhQnwpj68p449gEMt2GuOopZAAoD-vZz6dugog,1103
+tzdata/zoneinfo/Europe/Madrid,sha256=ylsyHdv8iOB-DQPtL6DIMs5dDdjn2QolIAqOJImMOyE,897
+tzdata/zoneinfo/Europe/Malta,sha256=irX_nDD-BXYObaduu_vhPe1F31xmgL364dSOaT_OVco,928
+tzdata/zoneinfo/Europe/Mariehamn,sha256=ccpK9ZmPCZkMXoddNQ_DyONPKAuub-FPNtRpL6znpWM,481
+tzdata/zoneinfo/Europe/Minsk,sha256=86iP_xDtidkUCqjkoKhH5_El3VI21fSgoIiXl_BzUaU,808
+tzdata/zoneinfo/Europe/Monaco,sha256=zViOd5xXN9cOTkcVja-reUWwJrK7NEVMxHdBgVRZsGg,1105
+tzdata/zoneinfo/Europe/Moscow,sha256=7S4KCZ-0RrJBZoNDjT9W-fxaYqFsdUmn9Zy8k1s2TIo,908
+tzdata/zoneinfo/Europe/Nicosia,sha256=TYYqWp8sK0AwBUHAp0wuuihZuQ19RXdt28bth33zOBI,597
+tzdata/zoneinfo/Europe/Oslo,sha256=p_2ZMteF1NaQkAuDTDVjwYEMHPLgFxG8wJJq9sB2fLc,705
+tzdata/zoneinfo/Europe/Paris,sha256=zViOd5xXN9cOTkcVja-reUWwJrK7NEVMxHdBgVRZsGg,1105
+tzdata/zoneinfo/Europe/Podgorica,sha256=qMlk8-qnognZplD7FsaMAD6aX8Yv-7sQ-oSdVPs2YtY,478
+tzdata/zoneinfo/Europe/Prague,sha256=pukw4zdc3LUffYp0iFr_if0UuGHrt1yzOdD5HBbBRpo,723
+tzdata/zoneinfo/Europe/Riga,sha256=PU8amev-8XVvl4B_JUOOOM1ofSMbotp-3MPGPHpPoTw,694
+tzdata/zoneinfo/Europe/Rome,sha256=hr0moG_jBXs2zyndejOPJSSv-BFu8I0AWqIRTqYSKGk,947
+tzdata/zoneinfo/Europe/Samara,sha256=Vc60AJe-0-b8prNiFwZTUS1bCbWxxuEnnNcgp8YkQRY,732
+tzdata/zoneinfo/Europe/San_Marino,sha256=hr0moG_jBXs2zyndejOPJSSv-BFu8I0AWqIRTqYSKGk,947
+tzdata/zoneinfo/Europe/Sarajevo,sha256=qMlk8-qnognZplD7FsaMAD6aX8Yv-7sQ-oSdVPs2YtY,478
+tzdata/zoneinfo/Europe/Saratov,sha256=0fN3eVFVewG-DSVk9xJABDQB1S_Nyn37bHOjj5X8Bm0,726
+tzdata/zoneinfo/Europe/Simferopol,sha256=y2Nybf9LGVNqNdW_GPS-NIDRLriyH_pyxKpT0zmATK4,865
+tzdata/zoneinfo/Europe/Skopje,sha256=qMlk8-qnognZplD7FsaMAD6aX8Yv-7sQ-oSdVPs2YtY,478
+tzdata/zoneinfo/Europe/Sofia,sha256=LQjC-OJkL4TzZcqD-JUofDAg1-qJui_2Ri6Eoii2MuQ,592
+tzdata/zoneinfo/Europe/Stockholm,sha256=p_2ZMteF1NaQkAuDTDVjwYEMHPLgFxG8wJJq9sB2fLc,705
+tzdata/zoneinfo/Europe/Tallinn,sha256=R6yRfPqESOYQWftlncDWo_fQak61eeiEQKwg_C-C7W8,675
+tzdata/zoneinfo/Europe/Tirane,sha256=I-alATWRd8mfSgvnr3dN_F9vbTB66alvz2GQo0LUbPc,604
+tzdata/zoneinfo/Europe/Tiraspol,sha256=5TPhkCtxxa0ByLCv7YxOrc5Vtdui2v2VX8vrSopPkPs,755
+tzdata/zoneinfo/Europe/Ulyanovsk,sha256=2vK0XahtB_dKjDDXccjMjbQ2bAOfKDe66uMDqtjzHm4,760
+tzdata/zoneinfo/Europe/Uzhgorod,sha256=BYnoDd7Ov50wd4mMEpddK-c5PfKFbumSbFNHY-Hia_I,558
+tzdata/zoneinfo/Europe/Vaduz,sha256=GZBiscMM_rI3XshMVt9SvlGJGYamKTt6Ek06YlCfRek,497
+tzdata/zoneinfo/Europe/Vatican,sha256=hr0moG_jBXs2zyndejOPJSSv-BFu8I0AWqIRTqYSKGk,947
+tzdata/zoneinfo/Europe/Vienna,sha256=q8_UF23-KHqc2ay4ju0qT1TuBSpRTnlB7i6vElk4eJw,658
+tzdata/zoneinfo/Europe/Vilnius,sha256=hXvv1PaQndapT7hdywPO3738Y3ZqbW_hJx87khyaOPM,676
+tzdata/zoneinfo/Europe/Volgograd,sha256=v3P6iFJ-rThJprVNDxB7ZYDrimtsW7IvQi_gJpZiJOQ,753
+tzdata/zoneinfo/Europe/Warsaw,sha256=6I9aUfFoFXpBrC3YpO4OmoeUGchMYSK0dxsaKjPZOkw,923
+tzdata/zoneinfo/Europe/Zagreb,sha256=qMlk8-qnognZplD7FsaMAD6aX8Yv-7sQ-oSdVPs2YtY,478
+tzdata/zoneinfo/Europe/Zaporozhye,sha256=BYnoDd7Ov50wd4mMEpddK-c5PfKFbumSbFNHY-Hia_I,558
+tzdata/zoneinfo/Europe/Zurich,sha256=GZBiscMM_rI3XshMVt9SvlGJGYamKTt6Ek06YlCfRek,497
+tzdata/zoneinfo/Europe/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tzdata/zoneinfo/Europe/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/Factory,sha256=0ytXntCnQnMWvqJgue4mdUUQRr1YxXxnnCTyZxhgr3Y,113
+tzdata/zoneinfo/GB,sha256=Z2VB8LitRXx0TAk_gHWJrcrZCeP9A_kBeH0IeG7tvTM,1599
+tzdata/zoneinfo/GB-Eire,sha256=Z2VB8LitRXx0TAk_gHWJrcrZCeP9A_kBeH0IeG7tvTM,1599
+tzdata/zoneinfo/GMT,sha256=3EoHVxsQiE5PTzRQydGhy_TAPvU9Bu0uTqFS2eul1dc,111
+tzdata/zoneinfo/GMT+0,sha256=3EoHVxsQiE5PTzRQydGhy_TAPvU9Bu0uTqFS2eul1dc,111
+tzdata/zoneinfo/GMT-0,sha256=3EoHVxsQiE5PTzRQydGhy_TAPvU9Bu0uTqFS2eul1dc,111
+tzdata/zoneinfo/GMT0,sha256=3EoHVxsQiE5PTzRQydGhy_TAPvU9Bu0uTqFS2eul1dc,111
+tzdata/zoneinfo/Greenwich,sha256=3EoHVxsQiE5PTzRQydGhy_TAPvU9Bu0uTqFS2eul1dc,111
+tzdata/zoneinfo/HST,sha256=HapXKaoeDzLNRL4RLQGtTMVnqf522H3LuRgr6NLIj_A,221
+tzdata/zoneinfo/Hongkong,sha256=9AaPcyRtuXQX9zRnRTVkxX1mRs5JCbn6JTaSPvzX608,775
+tzdata/zoneinfo/Iceland,sha256=8-f8qg6YQP9BadNWfY-1kmZEhI9JY9es-SMghDxdSG4,130
+tzdata/zoneinfo/Indian/Antananarivo,sha256=B4OFT1LDOtprbSpdhnZi8K6OFSONL857mtpPTTGetGY,191
+tzdata/zoneinfo/Indian/Chagos,sha256=J_aS7rs0ZG1dPTGeokXxNJpF4Pds8u1ct49cRtX7giY,152
+tzdata/zoneinfo/Indian/Christmas,sha256=zcjiwoLYvJpenDyvL8Rf9OnlzRj13sjLhzNArXxYTWQ,152
+tzdata/zoneinfo/Indian/Cocos,sha256=6J2DXIEdTaRKqLOGeCzogo3whaoO6PJWYamIHS8A6Qw,187
+tzdata/zoneinfo/Indian/Comoro,sha256=B4OFT1LDOtprbSpdhnZi8K6OFSONL857mtpPTTGetGY,191
+tzdata/zoneinfo/Indian/Kerguelen,sha256=lEhfD1j4QnZ-wtuTU51fw6-yvc4WZz2eY8CYjMzWQ44,152
+tzdata/zoneinfo/Indian/Mahe,sha256=DZ6lBT6DGIAypvtNMB1dtoj0MBHltrH5F6EbcaDaexY,133
+tzdata/zoneinfo/Indian/Maldives,sha256=lEhfD1j4QnZ-wtuTU51fw6-yvc4WZz2eY8CYjMzWQ44,152
+tzdata/zoneinfo/Indian/Mauritius,sha256=R6pdJalrHVK5LlGOmEsyD66_-c5a9ptJM-xE71Fo8hQ,179
+tzdata/zoneinfo/Indian/Mayotte,sha256=B4OFT1LDOtprbSpdhnZi8K6OFSONL857mtpPTTGetGY,191
+tzdata/zoneinfo/Indian/Reunion,sha256=DZ6lBT6DGIAypvtNMB1dtoj0MBHltrH5F6EbcaDaexY,133
+tzdata/zoneinfo/Indian/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tzdata/zoneinfo/Indian/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/Iran,sha256=ZaxewB83IdYIGVpJvcp8esyz3iffAgxEzsj7cMraQ3c,812
+tzdata/zoneinfo/Israel,sha256=n83o1YTeoFhfXIcnqvNfSKFJ4NvTqDv2zvi8qcFAIeM,1074
+tzdata/zoneinfo/Jamaica,sha256=pDexcAMzrv9TqLWGjVOHwIDcFMLT6Vqlzjb5AbNmkoQ,339
+tzdata/zoneinfo/Japan,sha256=WaOHFDDw07k-YZ-jCkOkHR6IvdSf8m8J0PQFpQBwb5Y,213
+tzdata/zoneinfo/Kwajalein,sha256=S-ZFi6idKzDaelLy7DRjGPeD0s7oVud3xLMxZKNlBk8,219
+tzdata/zoneinfo/Libya,sha256=zzMBLZZh4VQ4_ARe5k4L_rsuqKP7edKvVt8F6kvj5FM,431
+tzdata/zoneinfo/MET,sha256=sQ-VQqhQnwpj68p449gEMt2GuOopZAAoD-vZz6dugog,1103
+tzdata/zoneinfo/MST,sha256=rhFFPCHQiYTedfLv7ATckxeKe04jxeUvIJi4vUXMtUc,240
+tzdata/zoneinfo/MST7MDT,sha256=m7cDkg7KS2EZ6BoQVYOk9soiBlHxO0GEeat81WxBPz4,1042
+tzdata/zoneinfo/Mexico/BajaNorte,sha256=r5rqSu5QUUP6XoR2Q8D_4WQZDDhBEBCsfwsXD0CYpsg,1367
+tzdata/zoneinfo/Mexico/BajaSur,sha256=IN7ecQ9SDq9sDNvu_nc_xuMN2LHSiq8X6YQgmVUe6aY,690
+tzdata/zoneinfo/Mexico/General,sha256=N90r8I8T_OD3B8Ox9M7EAY772cR8g2ew-03rvUYb1y8,773
+tzdata/zoneinfo/Mexico/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tzdata/zoneinfo/Mexico/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/NZ,sha256=Dgbn5VrtvJLvWz0Qbnw5KrFijP2KQosg6S6ZAooL-7k,1043
+tzdata/zoneinfo/NZ-CHAT,sha256=pnhY_Lb8V4eo6cK3yL6JZL086SI_etG6rCycppJfTHg,808
+tzdata/zoneinfo/Navajo,sha256=m7cDkg7KS2EZ6BoQVYOk9soiBlHxO0GEeat81WxBPz4,1042
+tzdata/zoneinfo/PRC,sha256=v4t-2C_m5j5tmPjOqTTurJAc0Wq6hetXVc4_i0KJ6oo,393
+tzdata/zoneinfo/PST8PDT,sha256=IA0FdU9tg6Nxz0CNcIUSV5dlezsL6-uh5QjP_oaj5cg,1294
+tzdata/zoneinfo/Pacific/Apia,sha256=3HDEfICrLIehq3VLq4_r_DhQgFniSd_lXnOjdZgI6hQ,407
+tzdata/zoneinfo/Pacific/Auckland,sha256=Dgbn5VrtvJLvWz0Qbnw5KrFijP2KQosg6S6ZAooL-7k,1043
+tzdata/zoneinfo/Pacific/Bougainville,sha256=rqdn1Y4HSarx-vjPk00lsHNfhj3IQgKCViAsumuN_IY,201
+tzdata/zoneinfo/Pacific/Chatham,sha256=pnhY_Lb8V4eo6cK3yL6JZL086SI_etG6rCycppJfTHg,808
+tzdata/zoneinfo/Pacific/Chuuk,sha256=aDABBVtu-dydiHNODt3ReC8cNkO3wTp16c-OkFIAbhk,154
+tzdata/zoneinfo/Pacific/Easter,sha256=EwVM74XjsboPVxK9bWmdd4nTrtvasP1zlLdxrMB_YaE,1174
+tzdata/zoneinfo/Pacific/Efate,sha256=LiX_rTfipQh_Vnqb_m7OGxyBtyAUC9UANVKHUpLoCcU,342
+tzdata/zoneinfo/Pacific/Enderbury,sha256=ojOG-oqi25HOnY6BFhav_3bmWg1LDILT4v-kxOFVuqI,172
+tzdata/zoneinfo/Pacific/Fakaofo,sha256=Uf8zeML2X8doPg8CX-p0mMGP-IOj7aHAMe7ULD5khxA,153
+tzdata/zoneinfo/Pacific/Fiji,sha256=umCNhtTuBziTXne-WAxzvYvGKqZxTYOTwK-tJhYh4MQ,396
+tzdata/zoneinfo/Pacific/Funafuti,sha256=CQNWIL2DFpej6Qcvgt40z8pekS1QyNpUdzmqLyj7bY4,134
+tzdata/zoneinfo/Pacific/Galapagos,sha256=Z1KJPZSvO8M_Pay9WLcNAxzjo8imPrQ7FnXNOXfZl8c,175
+tzdata/zoneinfo/Pacific/Gambier,sha256=yIh86hjpDk1wRWTVJROOGqn9tkc7e9_O6zNxqs-wBoM,132
+tzdata/zoneinfo/Pacific/Guadalcanal,sha256=Ui8PN0th4sb1-n0Z8ceszNCeSiE0Yu47QskNMr8r8Yw,134
+tzdata/zoneinfo/Pacific/Guam,sha256=i57eM6syriUFvAbrVALnziCw_I4lENyzBcJdOaH71yU,350
+tzdata/zoneinfo/Pacific/Honolulu,sha256=HapXKaoeDzLNRL4RLQGtTMVnqf522H3LuRgr6NLIj_A,221
+tzdata/zoneinfo/Pacific/Johnston,sha256=HapXKaoeDzLNRL4RLQGtTMVnqf522H3LuRgr6NLIj_A,221
+tzdata/zoneinfo/Pacific/Kanton,sha256=ojOG-oqi25HOnY6BFhav_3bmWg1LDILT4v-kxOFVuqI,172
+tzdata/zoneinfo/Pacific/Kiritimati,sha256=cUVGmMRBgllfuYJ3X0B0zg0Bf-LPo9l7Le5ju882dx4,174
+tzdata/zoneinfo/Pacific/Kosrae,sha256=pQMLJXilygPhlkm0jCo5JuVmpmYJgLIdiTVxeP59ZEg,242
+tzdata/zoneinfo/Pacific/Kwajalein,sha256=S-ZFi6idKzDaelLy7DRjGPeD0s7oVud3xLMxZKNlBk8,219
+tzdata/zoneinfo/Pacific/Majuro,sha256=CQNWIL2DFpej6Qcvgt40z8pekS1QyNpUdzmqLyj7bY4,134
+tzdata/zoneinfo/Pacific/Marquesas,sha256=ilprkRvn-N1XjptSI_0ZwUjeuokP-5l64uKjRBp0kxw,139
+tzdata/zoneinfo/Pacific/Midway,sha256=ZQ2Rh1E2ZZBVMGPNaBWS_cqKCZV-DOLBjWaX7Dhe95Y,146
+tzdata/zoneinfo/Pacific/Nauru,sha256=wahZONjreNAmYwhQ2CWdKMAE3SVm4S2aYvMZqcAlSYc,183
+tzdata/zoneinfo/Pacific/Niue,sha256=8WWebtgCnrMBKjuLNEYEWlktNI2op2kkKgk0Vcz8GaM,154
+tzdata/zoneinfo/Pacific/Norfolk,sha256=vL8G6W5CScYqp76g0b15UPIYHw2Lt60qOktHUF7caDs,237
+tzdata/zoneinfo/Pacific/Noumea,sha256=ezUyn7AYWBblrZbStlItJYu7XINCLiihrCBZB-Bl-Qw,198
+tzdata/zoneinfo/Pacific/Pago_Pago,sha256=ZQ2Rh1E2ZZBVMGPNaBWS_cqKCZV-DOLBjWaX7Dhe95Y,146
+tzdata/zoneinfo/Pacific/Palau,sha256=VkLRsKUUVXo3zrhAXn9iM-pKySbGIVfzWoopDhmceMA,148
+tzdata/zoneinfo/Pacific/Pitcairn,sha256=AJh6olJxXQzCMWKOE5ye4jHfgg1VA-9-gCZ5MbrX_8E,153
+tzdata/zoneinfo/Pacific/Pohnpei,sha256=Ui8PN0th4sb1-n0Z8ceszNCeSiE0Yu47QskNMr8r8Yw,134
+tzdata/zoneinfo/Pacific/Ponape,sha256=Ui8PN0th4sb1-n0Z8ceszNCeSiE0Yu47QskNMr8r8Yw,134
+tzdata/zoneinfo/Pacific/Port_Moresby,sha256=aDABBVtu-dydiHNODt3ReC8cNkO3wTp16c-OkFIAbhk,154
+tzdata/zoneinfo/Pacific/Rarotonga,sha256=J6a2mOrTp4bsZNovj3HjJK9AVJ89PhdEpQMMVD__i18,406
+tzdata/zoneinfo/Pacific/Saipan,sha256=i57eM6syriUFvAbrVALnziCw_I4lENyzBcJdOaH71yU,350
+tzdata/zoneinfo/Pacific/Samoa,sha256=ZQ2Rh1E2ZZBVMGPNaBWS_cqKCZV-DOLBjWaX7Dhe95Y,146
+tzdata/zoneinfo/Pacific/Tahiti,sha256=Ivcs04hthxEQj1I_6aACc70By0lmxlvhgGFYh843e14,133
+tzdata/zoneinfo/Pacific/Tarawa,sha256=CQNWIL2DFpej6Qcvgt40z8pekS1QyNpUdzmqLyj7bY4,134
+tzdata/zoneinfo/Pacific/Tongatapu,sha256=mjGjNSUATfw0yLGB0zsLxz3_L1uWxPANML8K4HQQIMY,237
+tzdata/zoneinfo/Pacific/Truk,sha256=aDABBVtu-dydiHNODt3ReC8cNkO3wTp16c-OkFIAbhk,154
+tzdata/zoneinfo/Pacific/Wake,sha256=CQNWIL2DFpej6Qcvgt40z8pekS1QyNpUdzmqLyj7bY4,134
+tzdata/zoneinfo/Pacific/Wallis,sha256=CQNWIL2DFpej6Qcvgt40z8pekS1QyNpUdzmqLyj7bY4,134
+tzdata/zoneinfo/Pacific/Yap,sha256=aDABBVtu-dydiHNODt3ReC8cNkO3wTp16c-OkFIAbhk,154
+tzdata/zoneinfo/Pacific/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tzdata/zoneinfo/Pacific/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/Poland,sha256=6I9aUfFoFXpBrC3YpO4OmoeUGchMYSK0dxsaKjPZOkw,923
+tzdata/zoneinfo/Portugal,sha256=RNL2z4RzfmoeDa-RQQnpQla-ykC0DJoRt6BOi92u5Ow,1463
+tzdata/zoneinfo/ROC,sha256=oEwscvT3aoMXjQNt2X0VfuHzLkeORN2npcEJI2h-5s8,511
+tzdata/zoneinfo/ROK,sha256=ZKcLb7zJtl52Lb0l64m29AwTcUbtyNvU0IHq-s2reN4,415
+tzdata/zoneinfo/Singapore,sha256=CVSy2aMB2U9DSAJGBqcbvLL6JNPNNwn1vIvKYFA5eF0,256
+tzdata/zoneinfo/Turkey,sha256=KnFjsWuUgG9pmRNI59CmDEbrYbHwMF9fS4P2E9sQgG8,1200
+tzdata/zoneinfo/UCT,sha256=_dzh5kihcyrCmv2aFhUbKXPN8ILn7AxpD35CvmtZi5M,111
+tzdata/zoneinfo/US/Alaska,sha256=d8oMIpYvBpmLzl5I2By4ZaFEZsg_9dxgfqpIM0QFi_Y,977
+tzdata/zoneinfo/US/Aleutian,sha256=q_sZgOINX4TsX9iBx1gNd6XGwBnzCjg6qpdAQhK0ieA,969
+tzdata/zoneinfo/US/Arizona,sha256=rhFFPCHQiYTedfLv7ATckxeKe04jxeUvIJi4vUXMtUc,240
+tzdata/zoneinfo/US/Central,sha256=wntzn_RqffBZThINcltDkhfhHkTqmlDNxJEwODtUguc,1754
+tzdata/zoneinfo/US/East-Indiana,sha256=5nj0KhPvvXvg8mqc5T4EscKKWC6rBWEcsBwWg2Qy8Hs,531
+tzdata/zoneinfo/US/Eastern,sha256=1_IgazpFmJ_JrWPVWJIlMvpzUigNX4cXa_HbecsdH6k,1744
+tzdata/zoneinfo/US/Hawaii,sha256=HapXKaoeDzLNRL4RLQGtTMVnqf522H3LuRgr6NLIj_A,221
+tzdata/zoneinfo/US/Indiana-Starke,sha256=KJCzXct8CTMItVLYLYeBqM6aT6b53gWCg6aDbsH58oI,1016
+tzdata/zoneinfo/US/Michigan,sha256=I4F8Mt9nx38AF6D-steYskBa_HHO6jKU1-W0yRFr50A,899
+tzdata/zoneinfo/US/Mountain,sha256=m7cDkg7KS2EZ6BoQVYOk9soiBlHxO0GEeat81WxBPz4,1042
+tzdata/zoneinfo/US/Pacific,sha256=IA0FdU9tg6Nxz0CNcIUSV5dlezsL6-uh5QjP_oaj5cg,1294
+tzdata/zoneinfo/US/Samoa,sha256=ZQ2Rh1E2ZZBVMGPNaBWS_cqKCZV-DOLBjWaX7Dhe95Y,146
+tzdata/zoneinfo/US/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tzdata/zoneinfo/US/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/UTC,sha256=_dzh5kihcyrCmv2aFhUbKXPN8ILn7AxpD35CvmtZi5M,111
+tzdata/zoneinfo/Universal,sha256=_dzh5kihcyrCmv2aFhUbKXPN8ILn7AxpD35CvmtZi5M,111
+tzdata/zoneinfo/W-SU,sha256=7S4KCZ-0RrJBZoNDjT9W-fxaYqFsdUmn9Zy8k1s2TIo,908
+tzdata/zoneinfo/WET,sha256=RNL2z4RzfmoeDa-RQQnpQla-ykC0DJoRt6BOi92u5Ow,1463
+tzdata/zoneinfo/Zulu,sha256=_dzh5kihcyrCmv2aFhUbKXPN8ILn7AxpD35CvmtZi5M,111
+tzdata/zoneinfo/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tzdata/zoneinfo/__pycache__/__init__.cpython-310.pyc,,
+tzdata/zoneinfo/iso3166.tab,sha256=g3yAeFCAyEM_2dTqh-ePFhrHpAOJMBxRU9T5AZi66yo,4841
+tzdata/zoneinfo/leapseconds,sha256=VRQ0gZCj758PZf7of8pZtNbZKScCrg6ElgARFZp8J2c,3694
+tzdata/zoneinfo/tzdata.zi,sha256=5JWrRFruKp1mB84rtCLX9PUJ1sqoIrJvXPtJq97TqpA,107441
+tzdata/zoneinfo/zone.tab,sha256=WGtCB-bHZyLegq3Npr9J12H2aFF_RaZz9k2oOzM-7MQ,18822
+tzdata/zoneinfo/zone1970.tab,sha256=6dn-MJQqiA91a3P2SWZ9hkeh7PITEUlEXZzCTGXk7o8,17605
+tzdata/zoneinfo/zonenow.tab,sha256=oVuFMStmwzwt9UceOp1cVf2YFT-NbrR4eNijSIsGVqU,8002
+tzdata/zones,sha256=UCfmEKENGYPShuIfoftxjw00cERGyzf3B-gXB7s8EkQ,9102
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata-2025.3.dist-info/WHEEL b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata-2025.3.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..5f133dbb5cfac001f2e84cda817210c03ce6484e
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata-2025.3.dist-info/WHEEL
@@ -0,0 +1,6 @@
+Wheel-Version: 1.0
+Generator: setuptools (80.9.0)
+Root-Is-Purelib: true
+Tag: py2-none-any
+Tag: py3-none-any
+
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata-2025.3.dist-info/licenses/LICENSE b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata-2025.3.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..c2f84aeb06f7a520b7cf17bdd9c9c3854dc4c469
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata-2025.3.dist-info/licenses/LICENSE
@@ -0,0 +1,15 @@
+Apache Software License 2.0
+
+Copyright (c) 2020, Paul Ganssle (Google)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata-2025.3.dist-info/licenses/licenses/LICENSE_APACHE b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata-2025.3.dist-info/licenses/licenses/LICENSE_APACHE
new file mode 100644
index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata-2025.3.dist-info/licenses/licenses/LICENSE_APACHE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata-2025.3.dist-info/top_level.txt b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata-2025.3.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..0883ff0705bf11267d4d921b9bf48392b3e23889
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata-2025.3.dist-info/top_level.txt
@@ -0,0 +1 @@
+tzdata
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Buenos_Aires b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Buenos_Aires
new file mode 100644
index 0000000000000000000000000000000000000000..d6f999b8605c9f73653a16e2ddbd5a49b96c0f56
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Buenos_Aires differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Catamarca b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Catamarca
new file mode 100644
index 0000000000000000000000000000000000000000..1dcc8d85434c9d016f170cb2f16811ebef327b77
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Catamarca differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/ComodRivadavia b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/ComodRivadavia
new file mode 100644
index 0000000000000000000000000000000000000000..1dcc8d85434c9d016f170cb2f16811ebef327b77
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/ComodRivadavia differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Cordoba b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Cordoba
new file mode 100644
index 0000000000000000000000000000000000000000..35a52e53d123b5ef5d293b3af19046630f02bb66
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Cordoba differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Jujuy b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Jujuy
new file mode 100644
index 0000000000000000000000000000000000000000..b275f27c0287415674d2ccc850c3d612f4a45b0f
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Jujuy differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/La_Rioja b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/La_Rioja
new file mode 100644
index 0000000000000000000000000000000000000000..23fca12205222be27c167e597df5086520f699cf
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/La_Rioja differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Mendoza b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Mendoza
new file mode 100644
index 0000000000000000000000000000000000000000..691c56978a033586e3302db2ef600e4b0ffd6366
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Mendoza differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Rio_Gallegos b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Rio_Gallegos
new file mode 100644
index 0000000000000000000000000000000000000000..991d1fae69ee1602fc6a07e6e85a3b62d66650c2
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Rio_Gallegos differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Salta b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Salta
new file mode 100644
index 0000000000000000000000000000000000000000..58863e0436d16ef8ff8ba3d96b452086e4ae8ff5
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Salta differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/San_Juan b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/San_Juan
new file mode 100644
index 0000000000000000000000000000000000000000..7eba33c1c5b13cbd9b7566f450d524a45cf8b65e
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/San_Juan differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/San_Luis b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/San_Luis
new file mode 100644
index 0000000000000000000000000000000000000000..0a81cbddfa2813041472b716baa91c35a8451379
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/San_Luis differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Tucuman b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Tucuman
new file mode 100644
index 0000000000000000000000000000000000000000..10556d5d856a0f33afd8da2b07a2005e7be80fb0
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Tucuman differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Ushuaia b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Ushuaia
new file mode 100644
index 0000000000000000000000000000000000000000..e0317502769271ad0c038493df2ad2b90ec402d4
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/Ushuaia differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Argentina/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Indianapolis b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Indianapolis
new file mode 100644
index 0000000000000000000000000000000000000000..6b08d15bdaba6cf94dcb2681887154f4d265d8ba
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Indianapolis differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Knox b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Knox
new file mode 100644
index 0000000000000000000000000000000000000000..b187d5f8c75685af67913e9360b50ecad19fe6ad
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Knox differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Marengo b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Marengo
new file mode 100644
index 0000000000000000000000000000000000000000..a730fe666b6522026ec2eb74f94616699178a346
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Marengo differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Petersburg b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Petersburg
new file mode 100644
index 0000000000000000000000000000000000000000..341a0235ef488ee623aba36a8b5928122774d2fb
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Petersburg differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Tell_City b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Tell_City
new file mode 100644
index 0000000000000000000000000000000000000000..76e1f6285b552c11ceae9bc6cdbd6a308419b0e8
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Tell_City differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Vevay b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Vevay
new file mode 100644
index 0000000000000000000000000000000000000000..f2acf6cbbd653929e826366aec83f443d11c66e7
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Vevay differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Vincennes b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Vincennes
new file mode 100644
index 0000000000000000000000000000000000000000..c255f89b6da9916832a8b6a9bb7620859ce33d91
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Vincennes differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Winamac b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Winamac
new file mode 100644
index 0000000000000000000000000000000000000000..679d321e3b691b5403d9c9493367651360ea6f15
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/Winamac differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Indiana/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Kentucky/Louisville b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Kentucky/Louisville
new file mode 100644
index 0000000000000000000000000000000000000000..f2136d6ed41bb7dc0646b91bab366efb46bacb78
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Kentucky/Louisville differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Kentucky/Monticello b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Kentucky/Monticello
new file mode 100644
index 0000000000000000000000000000000000000000..d9f54a18bbe6885a05a7f42a056bc892b7a641e8
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Kentucky/Monticello differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Kentucky/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Kentucky/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Lima b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Lima
new file mode 100644
index 0000000000000000000000000000000000000000..b643c5517f923f075d58897764ba6885197f5758
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Lima differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Los_Angeles b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Los_Angeles
new file mode 100644
index 0000000000000000000000000000000000000000..aaf07787ad92b65eadae63b64bba290f9f961507
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Los_Angeles differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Louisville b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Louisville
new file mode 100644
index 0000000000000000000000000000000000000000..f2136d6ed41bb7dc0646b91bab366efb46bacb78
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Louisville differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Lower_Princes b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Lower_Princes
new file mode 100644
index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Lower_Princes differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Maceio b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Maceio
new file mode 100644
index 0000000000000000000000000000000000000000..dbb8d57d91d6640c1282fab3a063567d1f663f88
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Maceio differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Managua b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Managua
new file mode 100644
index 0000000000000000000000000000000000000000..86ef76bf2241b6abde0f4790d23b180db4b4b1cc
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Managua differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Manaus b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Manaus
new file mode 100644
index 0000000000000000000000000000000000000000..59c952ebc65169dce30078a3e1ee371e0da52ae4
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Manaus differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Marigot b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Marigot
new file mode 100644
index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Marigot differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Martinique b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Martinique
new file mode 100644
index 0000000000000000000000000000000000000000..25c0232d95492333e8c1aef7321a24a331e2e24a
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Martinique differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Matamoros b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Matamoros
new file mode 100644
index 0000000000000000000000000000000000000000..993ac47559c154e52af8fba1bcd7c9d0e3bea880
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Matamoros differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Mazatlan b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Mazatlan
new file mode 100644
index 0000000000000000000000000000000000000000..5aa6039ea4cb36077f048782b54c6275c25e86b3
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Mazatlan differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Mendoza b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Mendoza
new file mode 100644
index 0000000000000000000000000000000000000000..691c56978a033586e3302db2ef600e4b0ffd6366
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Mendoza differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Menominee b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Menominee
new file mode 100644
index 0000000000000000000000000000000000000000..28d2c56e1a991556b5aca45108e3415f3ebfe868
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Menominee differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Merida b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Merida
new file mode 100644
index 0000000000000000000000000000000000000000..e5c7d8cc2d2a986374f35561d8b629110b481a66
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Merida differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Metlakatla b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Metlakatla
new file mode 100644
index 0000000000000000000000000000000000000000..71b0eab085dbbb48050d7b6a271ebb1a29fb1926
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Metlakatla differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Mexico_City b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Mexico_City
new file mode 100644
index 0000000000000000000000000000000000000000..18112346129a885b5d5fa27109682b63784f72c0
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Mexico_City differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Miquelon b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Miquelon
new file mode 100644
index 0000000000000000000000000000000000000000..ba95cb0b3f755ab94154a54fd8cf6e6b9cdb0556
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Miquelon differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Moncton b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Moncton
new file mode 100644
index 0000000000000000000000000000000000000000..020e33d976179e8f61a6040caaef3c8eb7f348bc
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Moncton differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Monterrey b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Monterrey
new file mode 100644
index 0000000000000000000000000000000000000000..c1e05464513a451ab3cc49452e39da2b04e01de0
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Monterrey differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Montevideo b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Montevideo
new file mode 100644
index 0000000000000000000000000000000000000000..4b2fb3e560f6ad26b30b2215d26b3d6176d076b2
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Montevideo differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Montreal b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Montreal
new file mode 100644
index 0000000000000000000000000000000000000000..668e70d765dc3fb0eda16fb0f1932af607b53412
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Montreal differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Montserrat b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Montserrat
new file mode 100644
index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Montserrat differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Nassau b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Nassau
new file mode 100644
index 0000000000000000000000000000000000000000..668e70d765dc3fb0eda16fb0f1932af607b53412
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Nassau differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/New_York b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/New_York
new file mode 100644
index 0000000000000000000000000000000000000000..2b6c2eea14df07392729ae9f5712a44ec4f02bae
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/New_York differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Nipigon b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Nipigon
new file mode 100644
index 0000000000000000000000000000000000000000..668e70d765dc3fb0eda16fb0f1932af607b53412
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Nipigon differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Nome b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Nome
new file mode 100644
index 0000000000000000000000000000000000000000..23ead1c004ffd82c03b69b44e147daef4c07c961
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Nome differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Noronha b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Noronha
new file mode 100644
index 0000000000000000000000000000000000000000..9e74745ca79137918281337fa270c5fec4bd7da1
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Noronha differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/Beulah b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/Beulah
new file mode 100644
index 0000000000000000000000000000000000000000..becf4383301e2d90db0c0c06659b588d25042ee5
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/Beulah differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/Center b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/Center
new file mode 100644
index 0000000000000000000000000000000000000000..d03bda045d31662adc65450b33e9665c54fdb245
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/Center differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/New_Salem b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/New_Salem
new file mode 100644
index 0000000000000000000000000000000000000000..ecefc15d8cdf601347e114ff25b3bb2df4d56a57
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/New_Salem differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/North_Dakota/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Nuuk b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Nuuk
new file mode 100644
index 0000000000000000000000000000000000000000..310774ea4fdd1798782a41f905d16e3548cd191e
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Nuuk differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Ojinaga b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Ojinaga
new file mode 100644
index 0000000000000000000000000000000000000000..1dd08b1cafd4b36ce963bdc42a075665fa723b54
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Ojinaga differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Panama b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Panama
new file mode 100644
index 0000000000000000000000000000000000000000..9154643f4c9189998392afb8a93e2e2eb9eaecf5
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Panama differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Pangnirtung b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Pangnirtung
new file mode 100644
index 0000000000000000000000000000000000000000..95e055cb55d19335fa96f1a8d81fb5620f790771
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Pangnirtung differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Paramaribo b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Paramaribo
new file mode 100644
index 0000000000000000000000000000000000000000..24f925a2dd33d487e41cb38b9c3b4c420af69c1d
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Paramaribo differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Phoenix b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Phoenix
new file mode 100644
index 0000000000000000000000000000000000000000..c2bd2f949b248b835c98216b4dc66f9f6eb0265e
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Phoenix differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Port-au-Prince b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Port-au-Prince
new file mode 100644
index 0000000000000000000000000000000000000000..3e75731baa7c47f2a60ad07733d6f8467ccfbebf
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Port-au-Prince differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Port_of_Spain b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Port_of_Spain
new file mode 100644
index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Port_of_Spain differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Porto_Acre b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Porto_Acre
new file mode 100644
index 0000000000000000000000000000000000000000..fb5185ca60283bd56f795e9a956274c0b6e63325
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Porto_Acre differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Porto_Velho b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Porto_Velho
new file mode 100644
index 0000000000000000000000000000000000000000..7f8047d9396f92476873c9dbedb4598d9d238046
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Porto_Velho differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Puerto_Rico b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Puerto_Rico
new file mode 100644
index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Puerto_Rico differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Punta_Arenas b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Punta_Arenas
new file mode 100644
index 0000000000000000000000000000000000000000..aa839ea7d42eb9822002e66322c4ae195f1644b5
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Punta_Arenas differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Rainy_River b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Rainy_River
new file mode 100644
index 0000000000000000000000000000000000000000..7e646d18e18851bfde743b379e52df4ec5b5a20f
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Rainy_River differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Rankin_Inlet b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Rankin_Inlet
new file mode 100644
index 0000000000000000000000000000000000000000..6d1d90dede9888571eb09299dbd0b3e7dcfb1cc9
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Rankin_Inlet differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Recife b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Recife
new file mode 100644
index 0000000000000000000000000000000000000000..305abcb8a2217834e8333a2c486ccd389199a334
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Recife differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Regina b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Regina
new file mode 100644
index 0000000000000000000000000000000000000000..a3f8217a544ebb0993473bbffaae8e2d723c4ec3
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Regina differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Resolute b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Resolute
new file mode 100644
index 0000000000000000000000000000000000000000..97eb8a9c1fbbf56b8e32a1bea34f68e263e2a9d7
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Resolute differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Rio_Branco b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Rio_Branco
new file mode 100644
index 0000000000000000000000000000000000000000..fb5185ca60283bd56f795e9a956274c0b6e63325
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Rio_Branco differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Rosario b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Rosario
new file mode 100644
index 0000000000000000000000000000000000000000..35a52e53d123b5ef5d293b3af19046630f02bb66
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Rosario differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Santa_Isabel b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Santa_Isabel
new file mode 100644
index 0000000000000000000000000000000000000000..0d8c993bd1cf2fa2cbf002421ec9c0fb2b29645b
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Santa_Isabel differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Santarem b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Santarem
new file mode 100644
index 0000000000000000000000000000000000000000..f81d144206ac5bd2029d59beac0bb82801ebe67a
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Santarem differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Santiago b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Santiago
new file mode 100644
index 0000000000000000000000000000000000000000..d3fc9b8343369abf5f14be781397f426c5969608
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Santiago differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Santo_Domingo b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Santo_Domingo
new file mode 100644
index 0000000000000000000000000000000000000000..3e0785086639e483597890d2b53b9bc4c4ccfe91
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Santo_Domingo differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Sao_Paulo b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Sao_Paulo
new file mode 100644
index 0000000000000000000000000000000000000000..a16da2c4d5a980cd944d86c34ea8a2f597e39b71
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Sao_Paulo differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Scoresbysund b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Scoresbysund
new file mode 100644
index 0000000000000000000000000000000000000000..fc1b11cbe876cabb53fc1d42db25b0aabd967fc0
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Scoresbysund differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Shiprock b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Shiprock
new file mode 100644
index 0000000000000000000000000000000000000000..09e54e5c7c5bb2384e37626d4b985cfad29ed29b
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Shiprock differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Sitka b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Sitka
new file mode 100644
index 0000000000000000000000000000000000000000..36681ed78eaf0b46f8d142884cf7ae8903a18907
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Sitka differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/St_Barthelemy b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/St_Barthelemy
new file mode 100644
index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/St_Barthelemy differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/St_Johns b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/St_Johns
new file mode 100644
index 0000000000000000000000000000000000000000..94d790baaccb72298bb577041cf3c8400339a7da
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/St_Johns differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/St_Kitts b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/St_Kitts
new file mode 100644
index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/St_Kitts differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/St_Lucia b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/St_Lucia
new file mode 100644
index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/St_Lucia differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/St_Thomas b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/St_Thomas
new file mode 100644
index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/St_Thomas differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/St_Vincent b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/St_Vincent
new file mode 100644
index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/St_Vincent differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Swift_Current b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Swift_Current
new file mode 100644
index 0000000000000000000000000000000000000000..bdbb494487de8aeb624c950e470ebba223d16961
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Swift_Current differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Tegucigalpa b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Tegucigalpa
new file mode 100644
index 0000000000000000000000000000000000000000..38036a32831d149c6c737dfa49f0947f066288b1
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Tegucigalpa differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Thule b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Thule
new file mode 100644
index 0000000000000000000000000000000000000000..f38dc56bf20d9db68515ea7602c9edb39fabae8d
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Thule differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Thunder_Bay b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Thunder_Bay
new file mode 100644
index 0000000000000000000000000000000000000000..668e70d765dc3fb0eda16fb0f1932af607b53412
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Thunder_Bay differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Tijuana b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Tijuana
new file mode 100644
index 0000000000000000000000000000000000000000..0d8c993bd1cf2fa2cbf002421ec9c0fb2b29645b
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Tijuana differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Toronto b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Toronto
new file mode 100644
index 0000000000000000000000000000000000000000..668e70d765dc3fb0eda16fb0f1932af607b53412
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Toronto differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Tortola b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Tortola
new file mode 100644
index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Tortola differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Vancouver b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Vancouver
new file mode 100644
index 0000000000000000000000000000000000000000..c998491112ea5e4430b8266498cf7f23e1266bc5
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Vancouver differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Virgin b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Virgin
new file mode 100644
index 0000000000000000000000000000000000000000..47b4dc34160dd3ff97ebc35ccdc99fcf49c7ffbb
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Virgin differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Whitehorse b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Whitehorse
new file mode 100644
index 0000000000000000000000000000000000000000..40baa9aba2a879f7a38a5a0f67e16e7a2d677a5e
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Whitehorse differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Winnipeg b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Winnipeg
new file mode 100644
index 0000000000000000000000000000000000000000..7e646d18e18851bfde743b379e52df4ec5b5a20f
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Winnipeg differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Yakutat b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Yakutat
new file mode 100644
index 0000000000000000000000000000000000000000..773feba89d36ffab4baf105b8f0ae69584a74014
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Yakutat differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Yellowknife b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Yellowknife
new file mode 100644
index 0000000000000000000000000000000000000000..645ee9453073acf4cff9f9420b358a8ebbe40f93
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/Yellowknife differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/America/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Casey b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Casey
new file mode 100644
index 0000000000000000000000000000000000000000..84f1c61e5c7c35090fd2e628e307cff72389fb02
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Casey differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Davis b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Davis
new file mode 100644
index 0000000000000000000000000000000000000000..3ec32224f2982db46a19d1a159f9017286fd1413
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Davis differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/DumontDUrville b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/DumontDUrville
new file mode 100644
index 0000000000000000000000000000000000000000..5d8fc3a1b253d1df3a0184013469c6e46f6f6f75
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/DumontDUrville differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Macquarie b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Macquarie
new file mode 100644
index 0000000000000000000000000000000000000000..99a8e60edffca85f5caf8eda9d05d85a4978e665
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Macquarie differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Mawson b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Mawson
new file mode 100644
index 0000000000000000000000000000000000000000..05e4c6c5867330a5af95cd6816ade311a0cac82d
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Mawson differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/McMurdo b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/McMurdo
new file mode 100644
index 0000000000000000000000000000000000000000..afb3929318475d4f0ea9d6c9e94d0f5f81d8b82e
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/McMurdo differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Palmer b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Palmer
new file mode 100644
index 0000000000000000000000000000000000000000..32c1941634aec9e7721fcf8e9b323e7d99c7f337
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Palmer differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Rothera b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Rothera
new file mode 100644
index 0000000000000000000000000000000000000000..ea49c00b2240fbd608425793b225d6e10a58ddef
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Rothera differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/South_Pole b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/South_Pole
new file mode 100644
index 0000000000000000000000000000000000000000..afb3929318475d4f0ea9d6c9e94d0f5f81d8b82e
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/South_Pole differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Syowa b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Syowa
new file mode 100644
index 0000000000000000000000000000000000000000..01c47ccb86ccbde2bf9ad0803298e8df87178a34
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Syowa differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Troll b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Troll
new file mode 100644
index 0000000000000000000000000000000000000000..2359c44bd00ed44d2cdbf4f0aa0d9cea507814ed
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Troll differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Vostok b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Vostok
new file mode 100644
index 0000000000000000000000000000000000000000..4ce8f74784e970731f5f44b84f73780087890fa5
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/Vostok differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Antarctica/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Arctic/Longyearbyen b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Arctic/Longyearbyen
new file mode 100644
index 0000000000000000000000000000000000000000..465546bd396ae5eb75076f13ba9c29b0c926c835
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Arctic/Longyearbyen differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Arctic/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Arctic/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Aden b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Aden
new file mode 100644
index 0000000000000000000000000000000000000000..01c47ccb86ccbde2bf9ad0803298e8df87178a34
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Aden differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Almaty b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Almaty
new file mode 100644
index 0000000000000000000000000000000000000000..02f047d70fc811f8cc17f2c08ddc1f328576fb94
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Almaty differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Amman b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Amman
new file mode 100644
index 0000000000000000000000000000000000000000..a3f9dff57148554c4207d71df64851aee2b28b19
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Amman differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Anadyr b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Anadyr
new file mode 100644
index 0000000000000000000000000000000000000000..551884d322bcd2201b4b9898ec765141277e6eee
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Anadyr differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Aqtau b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Aqtau
new file mode 100644
index 0000000000000000000000000000000000000000..3a40d1175a7d81d8a307d0e546a1fe9a40888b29
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Aqtau differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Aqtobe b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Aqtobe
new file mode 100644
index 0000000000000000000000000000000000000000..62c5840a83e29b4fcedba95e438581cec96b3cf6
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Aqtobe differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Ashgabat b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Ashgabat
new file mode 100644
index 0000000000000000000000000000000000000000..8482167269080ead3a6046ae5e64b56d48dac1dd
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Ashgabat differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Ashkhabad b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Ashkhabad
new file mode 100644
index 0000000000000000000000000000000000000000..8482167269080ead3a6046ae5e64b56d48dac1dd
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Ashkhabad differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Atyrau b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Atyrau
new file mode 100644
index 0000000000000000000000000000000000000000..cb2c82f657c7380462b3ea38d5e58cc3d692e0b2
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Atyrau differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Baghdad b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Baghdad
new file mode 100644
index 0000000000000000000000000000000000000000..a3ce97599100c0e514afa0764879c3f104be87e9
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Baghdad differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Bahrain b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Bahrain
new file mode 100644
index 0000000000000000000000000000000000000000..7409d74983c8d0cd8347a663c3bfbc1c041124da
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Bahrain differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Baku b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Baku
new file mode 100644
index 0000000000000000000000000000000000000000..96203d7a4266cd8646032165950374761090e318
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Baku differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Bangkok b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Bangkok
new file mode 100644
index 0000000000000000000000000000000000000000..ed687d2985c208171adcaa3401496b05325edca4
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Bangkok differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Barnaul b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Barnaul
new file mode 100644
index 0000000000000000000000000000000000000000..ff976dd3b27ac5f14dcbac2362f1b4638c5684aa
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Barnaul differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Beirut b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Beirut
new file mode 100644
index 0000000000000000000000000000000000000000..55dce5722cc9d913164747da068f37d3529e799f
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Beirut differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Bishkek b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Bishkek
new file mode 100644
index 0000000000000000000000000000000000000000..fe7832cdf99ed9da3b64e3b8f6c5cd0b8b4c8de7
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Bishkek differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Brunei b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Brunei
new file mode 100644
index 0000000000000000000000000000000000000000..59bc6e40b7bb0b4eb199dd8c17f416ee00ca4158
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Brunei differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Calcutta b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Calcutta
new file mode 100644
index 0000000000000000000000000000000000000000..00bc80a65e9a7aa470d63fba1ce1b29ef173d922
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Calcutta differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Chita b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Chita
new file mode 100644
index 0000000000000000000000000000000000000000..9d49cd35cd5e52c5ff0f2c0cc6bd3f4f6e856915
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Chita differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Choibalsan b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Choibalsan
new file mode 100644
index 0000000000000000000000000000000000000000..6f5d3a15abbe48b8a4dc72aadc88c416160a56a6
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Choibalsan differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Chongqing b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Chongqing
new file mode 100644
index 0000000000000000000000000000000000000000..d6b66984a2f36ae36b35e174756707aa7286c292
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Chongqing differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Chungking b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Chungking
new file mode 100644
index 0000000000000000000000000000000000000000..d6b66984a2f36ae36b35e174756707aa7286c292
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Chungking differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Colombo b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Colombo
new file mode 100644
index 0000000000000000000000000000000000000000..3eeb1b72b68993e26a2452afe98a6420ac66bafb
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Colombo differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Dacca b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Dacca
new file mode 100644
index 0000000000000000000000000000000000000000..28136808b6d1029676448d8711265d8c55cb4bae
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Dacca differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Damascus b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Damascus
new file mode 100644
index 0000000000000000000000000000000000000000..bd1624de5148d5670e4585dfcb445d8b270c02df
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Damascus differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Dhaka b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Dhaka
new file mode 100644
index 0000000000000000000000000000000000000000..28136808b6d1029676448d8711265d8c55cb4bae
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Dhaka differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Dili b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Dili
new file mode 100644
index 0000000000000000000000000000000000000000..22e705ca1ab1218e9f36b9f4f607258389853c8b
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Dili differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Dubai b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Dubai
new file mode 100644
index 0000000000000000000000000000000000000000..58d75bc26eec90272e97696f40483eb56c2b8b45
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Dubai differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Dushanbe b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Dushanbe
new file mode 100644
index 0000000000000000000000000000000000000000..d83fb076a256817ca0a3ec4e43c7768e6680dc84
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Dushanbe differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Famagusta b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Famagusta
new file mode 100644
index 0000000000000000000000000000000000000000..cc44179564afe36db0f1f7aab0a19cbc3e4fa4d0
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Famagusta differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Gaza b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Gaza
new file mode 100644
index 0000000000000000000000000000000000000000..0d79662716b445f61e5577bdb09e7c91e4a40d28
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Gaza differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Harbin b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Harbin
new file mode 100644
index 0000000000000000000000000000000000000000..d6b66984a2f36ae36b35e174756707aa7286c292
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Harbin differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Hebron b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Hebron
new file mode 100644
index 0000000000000000000000000000000000000000..53a3c14312bc770bf9bca1d2e7518763fec7a485
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Hebron differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Ho_Chi_Minh b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Ho_Chi_Minh
new file mode 100644
index 0000000000000000000000000000000000000000..86e21b0f524426287fb3b21a82369283c4040c0e
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Ho_Chi_Minh differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Hong_Kong b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Hong_Kong
new file mode 100644
index 0000000000000000000000000000000000000000..c80e364801be87687625f72e8e2c3dbd0f7ae4bc
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Hong_Kong differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Hovd b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Hovd
new file mode 100644
index 0000000000000000000000000000000000000000..6e08a261274e48f93eb5e221ba294e54ca671b94
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Hovd differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Irkutsk b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Irkutsk
new file mode 100644
index 0000000000000000000000000000000000000000..550e2a08773b328683ab10fb9feddee2038e9e58
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Irkutsk differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Istanbul b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Istanbul
new file mode 100644
index 0000000000000000000000000000000000000000..c89186687300068ac4e8505cc0012a1dbf6a9960
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Istanbul differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Jakarta b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Jakarta
new file mode 100644
index 0000000000000000000000000000000000000000..c9752d2f23ebbb8b1ca5b8ac604c6f24be5d0def
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Jakarta differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Jayapura b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Jayapura
new file mode 100644
index 0000000000000000000000000000000000000000..7c22f539d948e5757a0847892da344309b582473
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Jayapura differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Jerusalem b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Jerusalem
new file mode 100644
index 0000000000000000000000000000000000000000..4c49bbf52440631eca750cacb7d79f259eeb8bd2
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Jerusalem differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kabul b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kabul
new file mode 100644
index 0000000000000000000000000000000000000000..660ce4cf695702ee8c6eef5c0e2419de37d6df74
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kabul differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kamchatka b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kamchatka
new file mode 100644
index 0000000000000000000000000000000000000000..c65155402db6a465c05a8cd71ec7a0fc0f792762
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kamchatka differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Karachi b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Karachi
new file mode 100644
index 0000000000000000000000000000000000000000..e56d5afdafb27c656a39e1dcdf1e3d2b880efa87
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Karachi differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kashgar b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kashgar
new file mode 100644
index 0000000000000000000000000000000000000000..69ff7f6fb4973efb1185cad9f553f8c770c75934
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kashgar differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kathmandu b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kathmandu
new file mode 100644
index 0000000000000000000000000000000000000000..3a0d330ffd2f08396290960527fc8fc186356161
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kathmandu differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Katmandu b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Katmandu
new file mode 100644
index 0000000000000000000000000000000000000000..3a0d330ffd2f08396290960527fc8fc186356161
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Katmandu differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Khandyga b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Khandyga
new file mode 100644
index 0000000000000000000000000000000000000000..aeb733202acd5d9d2a19a54fc64c226302887423
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Khandyga differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kolkata b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kolkata
new file mode 100644
index 0000000000000000000000000000000000000000..00bc80a65e9a7aa470d63fba1ce1b29ef173d922
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kolkata differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Krasnoyarsk b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Krasnoyarsk
new file mode 100644
index 0000000000000000000000000000000000000000..e0d4fcb5c3d781943a65dc53cca9fab5d1905f9f
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Krasnoyarsk differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kuala_Lumpur b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kuala_Lumpur
new file mode 100644
index 0000000000000000000000000000000000000000..dbbdea3c8149004cfd525a0fc26e5da72b20e8a1
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kuala_Lumpur differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kuching b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kuching
new file mode 100644
index 0000000000000000000000000000000000000000..59bc6e40b7bb0b4eb199dd8c17f416ee00ca4158
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kuching differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kuwait b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kuwait
new file mode 100644
index 0000000000000000000000000000000000000000..01c47ccb86ccbde2bf9ad0803298e8df87178a34
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Kuwait differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Macao b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Macao
new file mode 100644
index 0000000000000000000000000000000000000000..c22f75e42db6b12db3c837056436cb77d176b83e
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Macao differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Macau b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Macau
new file mode 100644
index 0000000000000000000000000000000000000000..c22f75e42db6b12db3c837056436cb77d176b83e
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Macau differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Magadan b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Magadan
new file mode 100644
index 0000000000000000000000000000000000000000..16bac8444656c393288dcc0209a96c7c3f487a19
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Magadan differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Makassar b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Makassar
new file mode 100644
index 0000000000000000000000000000000000000000..5990010b649745369501c7641c401bcad4345b85
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Makassar differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Manila b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Manila
new file mode 100644
index 0000000000000000000000000000000000000000..145bb6fb162e192da18e0991c00578d43475b384
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Manila differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Muscat b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Muscat
new file mode 100644
index 0000000000000000000000000000000000000000..58d75bc26eec90272e97696f40483eb56c2b8b45
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Muscat differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Nicosia b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Nicosia
new file mode 100644
index 0000000000000000000000000000000000000000..390347f442a486e296689c189e3346695bba5105
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Nicosia differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Novokuznetsk b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Novokuznetsk
new file mode 100644
index 0000000000000000000000000000000000000000..9378d50539dfa8f1dabcb40d3720f64906d36202
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Novokuznetsk differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Novosibirsk b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Novosibirsk
new file mode 100644
index 0000000000000000000000000000000000000000..65a9fa2cd2e8548b13f1d0895bcba46fa11600a4
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Novosibirsk differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Omsk b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Omsk
new file mode 100644
index 0000000000000000000000000000000000000000..dc0ed422f6193fb5d7dcb59dd0eb3e06eec8d4de
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Omsk differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Oral b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Oral
new file mode 100644
index 0000000000000000000000000000000000000000..25a63ec8b9951c94fc00a8c6c9d18d2151b26dde
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Oral differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Phnom_Penh b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Phnom_Penh
new file mode 100644
index 0000000000000000000000000000000000000000..ed687d2985c208171adcaa3401496b05325edca4
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Phnom_Penh differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Pontianak b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Pontianak
new file mode 100644
index 0000000000000000000000000000000000000000..285bed2c63a5debe034a661431d2a1c03dfb0dad
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Pontianak differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Pyongyang b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Pyongyang
new file mode 100644
index 0000000000000000000000000000000000000000..57240cf89fb33139a92451ec2eb99cb67b2f49c1
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Pyongyang differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Qatar b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Qatar
new file mode 100644
index 0000000000000000000000000000000000000000..7409d74983c8d0cd8347a663c3bfbc1c041124da
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Qatar differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Qostanay b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Qostanay
new file mode 100644
index 0000000000000000000000000000000000000000..109fe41562e89a026f828125f960498f62fb5d95
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Qostanay differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Qyzylorda b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Qyzylorda
new file mode 100644
index 0000000000000000000000000000000000000000..fe4d6c6d6d44f0f6b7dd1f55702c4d640270a1fc
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Qyzylorda differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Rangoon b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Rangoon
new file mode 100644
index 0000000000000000000000000000000000000000..14b2ad09ead50a62d5e2b426396c51f9beb293be
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Rangoon differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Riyadh b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Riyadh
new file mode 100644
index 0000000000000000000000000000000000000000..01c47ccb86ccbde2bf9ad0803298e8df87178a34
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Riyadh differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Saigon b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Saigon
new file mode 100644
index 0000000000000000000000000000000000000000..86e21b0f524426287fb3b21a82369283c4040c0e
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Saigon differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Sakhalin b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Sakhalin
new file mode 100644
index 0000000000000000000000000000000000000000..69f0faad1e7247882721bb81a7242ddd4b1d269f
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Sakhalin differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Samarkand b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Samarkand
new file mode 100644
index 0000000000000000000000000000000000000000..c43e27c5d4bd341649b3aa32de068d76618c81ed
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Samarkand differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Seoul b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Seoul
new file mode 100644
index 0000000000000000000000000000000000000000..1755147fab44e07b7527ce1eaf3ae991473fb222
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Seoul differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Shanghai b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Shanghai
new file mode 100644
index 0000000000000000000000000000000000000000..d6b66984a2f36ae36b35e174756707aa7286c292
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Shanghai differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Singapore b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Singapore
new file mode 100644
index 0000000000000000000000000000000000000000..dbbdea3c8149004cfd525a0fc26e5da72b20e8a1
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Singapore differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Srednekolymsk b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Srednekolymsk
new file mode 100644
index 0000000000000000000000000000000000000000..7fdee5cbee2b1ba0904a672dde16240404466fb9
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Srednekolymsk differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Taipei b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Taipei
new file mode 100644
index 0000000000000000000000000000000000000000..35d89d036d07c3f28dec64092ab1b533c21ae2bc
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Taipei differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Tashkent b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Tashkent
new file mode 100644
index 0000000000000000000000000000000000000000..65ee428ce1c5093a4b3dd29512d98a33b4c753a0
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Tashkent differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Tbilisi b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Tbilisi
new file mode 100644
index 0000000000000000000000000000000000000000..166e4341d6ce65728367641a467a925800044df6
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Tbilisi differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Tehran b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Tehran
new file mode 100644
index 0000000000000000000000000000000000000000..6fd31e075a29223eeea3f9a1a747b4531775f8ef
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Tehran differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Tel_Aviv b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Tel_Aviv
new file mode 100644
index 0000000000000000000000000000000000000000..4c49bbf52440631eca750cacb7d79f259eeb8bd2
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Tel_Aviv differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Thimbu b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Thimbu
new file mode 100644
index 0000000000000000000000000000000000000000..0edc72cfe46b1976bff562929501f202a205d0cc
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Thimbu differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Thimphu b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Thimphu
new file mode 100644
index 0000000000000000000000000000000000000000..0edc72cfe46b1976bff562929501f202a205d0cc
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Thimphu differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Tokyo b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Tokyo
new file mode 100644
index 0000000000000000000000000000000000000000..1aa066ce38fce7bd0a680f51d6f075718d153a77
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Tokyo differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Tomsk b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Tomsk
new file mode 100644
index 0000000000000000000000000000000000000000..c3c307d7b99f39328cf289360526399c55984af6
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Tomsk differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Ujung_Pandang b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Ujung_Pandang
new file mode 100644
index 0000000000000000000000000000000000000000..5990010b649745369501c7641c401bcad4345b85
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Ujung_Pandang differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Ulaanbaatar b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Ulaanbaatar
new file mode 100644
index 0000000000000000000000000000000000000000..6f5d3a15abbe48b8a4dc72aadc88c416160a56a6
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Ulaanbaatar differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Ulan_Bator b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Ulan_Bator
new file mode 100644
index 0000000000000000000000000000000000000000..6f5d3a15abbe48b8a4dc72aadc88c416160a56a6
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Ulan_Bator differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Urumqi b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Urumqi
new file mode 100644
index 0000000000000000000000000000000000000000..69ff7f6fb4973efb1185cad9f553f8c770c75934
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Urumqi differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Ust-Nera b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Ust-Nera
new file mode 100644
index 0000000000000000000000000000000000000000..c39331e3aa7d7c3c9f38e8ef83e739f0d09194b3
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Ust-Nera differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Vientiane b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Vientiane
new file mode 100644
index 0000000000000000000000000000000000000000..ed687d2985c208171adcaa3401496b05325edca4
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Vientiane differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Vladivostok b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Vladivostok
new file mode 100644
index 0000000000000000000000000000000000000000..72a3d4e87a0d6f568eeb84b4a9dfae0b679d23ff
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Vladivostok differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Yakutsk b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Yakutsk
new file mode 100644
index 0000000000000000000000000000000000000000..336f932e8d458b5096d4aa9483f3177f8d5888eb
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Yakutsk differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Yangon b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Yangon
new file mode 100644
index 0000000000000000000000000000000000000000..14b2ad09ead50a62d5e2b426396c51f9beb293be
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Yangon differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Yekaterinburg b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Yekaterinburg
new file mode 100644
index 0000000000000000000000000000000000000000..a3bf7f29b6f14debfbd0f8ccb45f1ea338009ef7
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Yekaterinburg differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Yerevan b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Yerevan
new file mode 100644
index 0000000000000000000000000000000000000000..6dd927cb94101609afa1d505129296370cd8aabe
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/Yerevan differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Asia/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Azores b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Azores
new file mode 100644
index 0000000000000000000000000000000000000000..cda1c1d225ae261ae433579e56d94a84ae2acd38
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Azores differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Bermuda b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Bermuda
new file mode 100644
index 0000000000000000000000000000000000000000..abc75ea7ef87f054cdcea06728b99e3540108860
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Bermuda differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Canary b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Canary
new file mode 100644
index 0000000000000000000000000000000000000000..5ab3243a5f01f5056127f160cfe693c33edf0531
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Canary differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Cape_Verde b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Cape_Verde
new file mode 100644
index 0000000000000000000000000000000000000000..8f7de1c0a19a8d3e0e749626c76c8d4dbd3c4de7
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Cape_Verde differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Faeroe b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Faeroe
new file mode 100644
index 0000000000000000000000000000000000000000..9558bf7180acab14d3b3f63c956f5224f680b2a3
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Faeroe differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Faroe b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Faroe
new file mode 100644
index 0000000000000000000000000000000000000000..9558bf7180acab14d3b3f63c956f5224f680b2a3
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Faroe differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Jan_Mayen b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Jan_Mayen
new file mode 100644
index 0000000000000000000000000000000000000000..465546bd396ae5eb75076f13ba9c29b0c926c835
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Jan_Mayen differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Madeira b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Madeira
new file mode 100644
index 0000000000000000000000000000000000000000..21e84571ee1694758dd244ed0702fbae962648e6
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Madeira differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Reykjavik b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Reykjavik
new file mode 100644
index 0000000000000000000000000000000000000000..8906e88c819d9ad3b794eb6356a240a74a95ffae
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Reykjavik differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/South_Georgia b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/South_Georgia
new file mode 100644
index 0000000000000000000000000000000000000000..7fa5f4683538498b93d1e639c14256c1f033c354
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/South_Georgia differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/St_Helena b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/St_Helena
new file mode 100644
index 0000000000000000000000000000000000000000..8906e88c819d9ad3b794eb6356a240a74a95ffae
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/St_Helena differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Stanley b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Stanley
new file mode 100644
index 0000000000000000000000000000000000000000..1a4c8ea86361731f4d7e854ac66d96a5ce6b2dbf
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/Stanley differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Atlantic/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/ACT b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/ACT
new file mode 100644
index 0000000000000000000000000000000000000000..1975a3a4bd0ed93db1d10a2c562eb5bc3baaa489
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/ACT differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Adelaide b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Adelaide
new file mode 100644
index 0000000000000000000000000000000000000000..3bfbbc563cf97dc2548ff8974ab23dcde28e8744
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Adelaide differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Brisbane b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Brisbane
new file mode 100644
index 0000000000000000000000000000000000000000..dc9a980a65923b6629d788e4e03b4358ac151c15
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Brisbane differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Broken_Hill b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Broken_Hill
new file mode 100644
index 0000000000000000000000000000000000000000..947b50995f4045ee6562cae21120dc8a05687653
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Broken_Hill differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Canberra b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Canberra
new file mode 100644
index 0000000000000000000000000000000000000000..1975a3a4bd0ed93db1d10a2c562eb5bc3baaa489
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Canberra differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Currie b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Currie
new file mode 100644
index 0000000000000000000000000000000000000000..dc2ef554dc389f4a34146329935e5c3581a0f2f4
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Currie differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Darwin b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Darwin
new file mode 100644
index 0000000000000000000000000000000000000000..a6a67300dd5ef87e421c9749702039a6bdbb928f
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Darwin differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Eucla b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Eucla
new file mode 100644
index 0000000000000000000000000000000000000000..9080f5cdb1216ef6397e7de6205173caa794c646
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Eucla differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Hobart b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Hobart
new file mode 100644
index 0000000000000000000000000000000000000000..dc2ef554dc389f4a34146329935e5c3581a0f2f4
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Hobart differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/LHI b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/LHI
new file mode 100644
index 0000000000000000000000000000000000000000..4d4ec8ceea9a96956864eddff4900fc4fb9ba8f1
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/LHI differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Lindeman b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Lindeman
new file mode 100644
index 0000000000000000000000000000000000000000..131d77b54a2087ada0bb3a27d03bf752f84326a7
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Lindeman differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Lord_Howe b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Lord_Howe
new file mode 100644
index 0000000000000000000000000000000000000000..4d4ec8ceea9a96956864eddff4900fc4fb9ba8f1
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Lord_Howe differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Melbourne b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Melbourne
new file mode 100644
index 0000000000000000000000000000000000000000..d3f195ac2fac23afd46cc16650e0a2454f5a3923
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Melbourne differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/NSW b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/NSW
new file mode 100644
index 0000000000000000000000000000000000000000..1975a3a4bd0ed93db1d10a2c562eb5bc3baaa489
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/NSW differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/North b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/North
new file mode 100644
index 0000000000000000000000000000000000000000..a6a67300dd5ef87e421c9749702039a6bdbb928f
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/North differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Perth b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Perth
new file mode 100644
index 0000000000000000000000000000000000000000..4f771828c9b54d9bcaef82639425df4b3559b5e1
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Perth differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Queensland b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Queensland
new file mode 100644
index 0000000000000000000000000000000000000000..dc9a980a65923b6629d788e4e03b4358ac151c15
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Queensland differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/South b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/South
new file mode 100644
index 0000000000000000000000000000000000000000..3bfbbc563cf97dc2548ff8974ab23dcde28e8744
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/South differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Sydney b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Sydney
new file mode 100644
index 0000000000000000000000000000000000000000..1975a3a4bd0ed93db1d10a2c562eb5bc3baaa489
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Sydney differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Tasmania b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Tasmania
new file mode 100644
index 0000000000000000000000000000000000000000..dc2ef554dc389f4a34146329935e5c3581a0f2f4
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Tasmania differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Victoria b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Victoria
new file mode 100644
index 0000000000000000000000000000000000000000..d3f195ac2fac23afd46cc16650e0a2454f5a3923
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Victoria differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/West b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/West
new file mode 100644
index 0000000000000000000000000000000000000000..4f771828c9b54d9bcaef82639425df4b3559b5e1
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/West differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Yancowinna b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Yancowinna
new file mode 100644
index 0000000000000000000000000000000000000000..947b50995f4045ee6562cae21120dc8a05687653
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/Yancowinna differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Australia/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Brazil/Acre b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Brazil/Acre
new file mode 100644
index 0000000000000000000000000000000000000000..fb5185ca60283bd56f795e9a956274c0b6e63325
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Brazil/Acre differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Brazil/DeNoronha b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Brazil/DeNoronha
new file mode 100644
index 0000000000000000000000000000000000000000..9e74745ca79137918281337fa270c5fec4bd7da1
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Brazil/DeNoronha differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Brazil/East b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Brazil/East
new file mode 100644
index 0000000000000000000000000000000000000000..a16da2c4d5a980cd944d86c34ea8a2f597e39b71
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Brazil/East differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Brazil/West b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Brazil/West
new file mode 100644
index 0000000000000000000000000000000000000000..59c952ebc65169dce30078a3e1ee371e0da52ae4
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Brazil/West differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Brazil/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Brazil/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Atlantic b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Atlantic
new file mode 100644
index 0000000000000000000000000000000000000000..9fa850a7d4c36dea84149bc0ea2fcd3581d61a8c
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Atlantic differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Central b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Central
new file mode 100644
index 0000000000000000000000000000000000000000..7e646d18e18851bfde743b379e52df4ec5b5a20f
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Central differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Eastern b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Eastern
new file mode 100644
index 0000000000000000000000000000000000000000..668e70d765dc3fb0eda16fb0f1932af607b53412
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Eastern differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Mountain b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Mountain
new file mode 100644
index 0000000000000000000000000000000000000000..645ee9453073acf4cff9f9420b358a8ebbe40f93
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Mountain differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Newfoundland b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Newfoundland
new file mode 100644
index 0000000000000000000000000000000000000000..94d790baaccb72298bb577041cf3c8400339a7da
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Newfoundland differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Pacific b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Pacific
new file mode 100644
index 0000000000000000000000000000000000000000..c998491112ea5e4430b8266498cf7f23e1266bc5
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Pacific differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Saskatchewan b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Saskatchewan
new file mode 100644
index 0000000000000000000000000000000000000000..a3f8217a544ebb0993473bbffaae8e2d723c4ec3
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Saskatchewan differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Yukon b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Yukon
new file mode 100644
index 0000000000000000000000000000000000000000..40baa9aba2a879f7a38a5a0f67e16e7a2d677a5e
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/Yukon differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Canada/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Chile/Continental b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Chile/Continental
new file mode 100644
index 0000000000000000000000000000000000000000..d3fc9b8343369abf5f14be781397f426c5969608
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Chile/Continental differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Chile/EasterIsland b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Chile/EasterIsland
new file mode 100644
index 0000000000000000000000000000000000000000..54dff005b876339f5c1ff3dc0aeae1519c29b368
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Chile/EasterIsland differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Chile/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Chile/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT
new file mode 100644
index 0000000000000000000000000000000000000000..157573b1d340e0f57a0dd4d9698bd3798cbf7136
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+0 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+0
new file mode 100644
index 0000000000000000000000000000000000000000..157573b1d340e0f57a0dd4d9698bd3798cbf7136
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+0 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+1 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+1
new file mode 100644
index 0000000000000000000000000000000000000000..98d5dcf917c6f1d9bd0018db0dc4dd0590e6a8ca
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+1 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+10 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+10
new file mode 100644
index 0000000000000000000000000000000000000000..ecb287e667868e92d97cdf5fee601e09cded0ff2
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+10 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+11 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+11
new file mode 100644
index 0000000000000000000000000000000000000000..e941412971a4d805e311e8e4e7eb37e10994e4be
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+11 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+12 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+12
new file mode 100644
index 0000000000000000000000000000000000000000..9c95bd0736da8932cd70e1d9590f8a3ab676c620
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+12 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+2 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+2
new file mode 100644
index 0000000000000000000000000000000000000000..6d5ce3db7323d63f73e9e92b6f4d3d6b77632a94
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+2 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+3 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+3
new file mode 100644
index 0000000000000000000000000000000000000000..5ef7be71fd96e4ef66fce3ab675303559dbb22a3
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+3 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+4 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+4
new file mode 100644
index 0000000000000000000000000000000000000000..75f16216f0d39ff98d969cd1f6703473f6fea50f
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+4 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+5 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+5
new file mode 100644
index 0000000000000000000000000000000000000000..589990ae8966d1af67f1e05c21e14149adec2089
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+5 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+6 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+6
new file mode 100644
index 0000000000000000000000000000000000000000..fcb60ca2465a3e0c4febd41ac1a05bbb39fd96ed
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+6 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+7 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+7
new file mode 100644
index 0000000000000000000000000000000000000000..c0427a40eef929dcf25451be77c74af6e9111065
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+7 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+8 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+8
new file mode 100644
index 0000000000000000000000000000000000000000..9bdc2283c07d8dae0bb0147c7a7c648ac6a30405
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+8 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+9 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+9
new file mode 100644
index 0000000000000000000000000000000000000000..ca7a81f656f206f32586fdd294a2b385bb519b6a
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+9 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-0 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-0
new file mode 100644
index 0000000000000000000000000000000000000000..157573b1d340e0f57a0dd4d9698bd3798cbf7136
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-0 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-1 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-1
new file mode 100644
index 0000000000000000000000000000000000000000..cb45601c958da687b3e3d63366aa259a8a1c5376
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-1 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-10 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-10
new file mode 100644
index 0000000000000000000000000000000000000000..11d988e10a3e318a7cba485d995872636d1acaf0
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-10 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-11 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-11
new file mode 100644
index 0000000000000000000000000000000000000000..f4c5d5cc29b5c1687e9728b6b63cd2a5328c9dfb
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-11 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-12 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-12
new file mode 100644
index 0000000000000000000000000000000000000000..cd397b02cdde1d348db020ce46785285feb312ba
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-12 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-13 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-13
new file mode 100644
index 0000000000000000000000000000000000000000..8fad7c6b0bef4b13898a94f4004726837cde975e
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-13 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-14 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-14
new file mode 100644
index 0000000000000000000000000000000000000000..a595e60eeae161b68617bb401d4acc53dbac1846
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-14 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-2 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-2
new file mode 100644
index 0000000000000000000000000000000000000000..97b44a9baecfd5bd30393142c63323160353bf2f
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-2 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-3 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-3
new file mode 100644
index 0000000000000000000000000000000000000000..4eb17ff0057b8843a0b840c6fef4b77accfe43b5
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-3 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-4 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-4
new file mode 100644
index 0000000000000000000000000000000000000000..13aef80cbbcf0c938b8d11d92b0755e146a501d2
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-4 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-5 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-5
new file mode 100644
index 0000000000000000000000000000000000000000..83a28169552f4fd39e9d0322398d787aad303e3c
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-5 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-6 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-6
new file mode 100644
index 0000000000000000000000000000000000000000..79a983e5454a35f134cd4ad736ed912f3deae64f
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-6 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-7 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-7
new file mode 100644
index 0000000000000000000000000000000000000000..e136690e165a933fbad2fdc0aba8d97886714fe0
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-7 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-8 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-8
new file mode 100644
index 0000000000000000000000000000000000000000..bc70fe416fdbe3abb2c636a7bc1485b79e03af13
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-8 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-9 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-9
new file mode 100644
index 0000000000000000000000000000000000000000..d18cedd524f4cc132106d822fa8bb9bd3779edab
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-9 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT0 b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT0
new file mode 100644
index 0000000000000000000000000000000000000000..157573b1d340e0f57a0dd4d9698bd3798cbf7136
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT0 differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/Greenwich b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/Greenwich
new file mode 100644
index 0000000000000000000000000000000000000000..157573b1d340e0f57a0dd4d9698bd3798cbf7136
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/Greenwich differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/UCT b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/UCT
new file mode 100644
index 0000000000000000000000000000000000000000..00841a62213e6cccf7f0b7353e5e8ae214185486
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/UCT differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/UTC b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/UTC
new file mode 100644
index 0000000000000000000000000000000000000000..00841a62213e6cccf7f0b7353e5e8ae214185486
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/UTC differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/Universal b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/Universal
new file mode 100644
index 0000000000000000000000000000000000000000..00841a62213e6cccf7f0b7353e5e8ae214185486
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/Universal differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/Zulu b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/Zulu
new file mode 100644
index 0000000000000000000000000000000000000000..00841a62213e6cccf7f0b7353e5e8ae214185486
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/Zulu differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Etc/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Amsterdam b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Amsterdam
new file mode 100644
index 0000000000000000000000000000000000000000..31973271d2f87f7e9df4e8b0a1481f09a9e5407d
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Amsterdam differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Andorra b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Andorra
new file mode 100644
index 0000000000000000000000000000000000000000..38685d4219d244f56f665c8afb92eaa6737badb8
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Andorra differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Astrakhan b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Astrakhan
new file mode 100644
index 0000000000000000000000000000000000000000..aff8d82d2a2de0857f78217cc9d04a112d1e1a08
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Astrakhan differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Athens b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Athens
new file mode 100644
index 0000000000000000000000000000000000000000..231bf9c3b713e3676dbd8f3ced867973c601e104
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Athens differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Belfast b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Belfast
new file mode 100644
index 0000000000000000000000000000000000000000..b9e95d92623c6cc4c35b16f7ceba3006f5ce4934
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Belfast differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Belgrade b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Belgrade
new file mode 100644
index 0000000000000000000000000000000000000000..a1bf9281ed1bc2c9b82ee64efdca60b4af762ede
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Belgrade differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Berlin b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Berlin
new file mode 100644
index 0000000000000000000000000000000000000000..465546bd396ae5eb75076f13ba9c29b0c926c835
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Berlin differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Bratislava b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Bratislava
new file mode 100644
index 0000000000000000000000000000000000000000..fb7c145ac4c8ab8f39731e75db8c384b7dc4ee11
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Bratislava differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Brussels b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Brussels
new file mode 100644
index 0000000000000000000000000000000000000000..31973271d2f87f7e9df4e8b0a1481f09a9e5407d
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Brussels differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Bucharest b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Bucharest
new file mode 100644
index 0000000000000000000000000000000000000000..c4a391e73b97e1342d352c5cc15a0bace202deef
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Bucharest differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Budapest b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Budapest
new file mode 100644
index 0000000000000000000000000000000000000000..940be4670a64ece1265dd28523d78a80f9008dd2
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Budapest differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Busingen b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Busingen
new file mode 100644
index 0000000000000000000000000000000000000000..388df2969f2dc56738183bd4f0d5755c4533a797
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Busingen differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Chisinau b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Chisinau
new file mode 100644
index 0000000000000000000000000000000000000000..9152e68594bb66cc756e0407654a203952fbd4e5
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Chisinau differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Copenhagen b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Copenhagen
new file mode 100644
index 0000000000000000000000000000000000000000..465546bd396ae5eb75076f13ba9c29b0c926c835
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Copenhagen differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Dublin b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Dublin
new file mode 100644
index 0000000000000000000000000000000000000000..17d2b1582df89d5794f20fb028956dd9da154922
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Dublin differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Gibraltar b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Gibraltar
new file mode 100644
index 0000000000000000000000000000000000000000..017bb2e34746c8a11c6955d49cc492c974412801
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Gibraltar differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Guernsey b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Guernsey
new file mode 100644
index 0000000000000000000000000000000000000000..b9e95d92623c6cc4c35b16f7ceba3006f5ce4934
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Guernsey differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Helsinki b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Helsinki
new file mode 100644
index 0000000000000000000000000000000000000000..ff5e56530570974516d249927952c69da601b664
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Helsinki differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Isle_of_Man b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Isle_of_Man
new file mode 100644
index 0000000000000000000000000000000000000000..b9e95d92623c6cc4c35b16f7ceba3006f5ce4934
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Isle_of_Man differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Istanbul b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Istanbul
new file mode 100644
index 0000000000000000000000000000000000000000..c89186687300068ac4e8505cc0012a1dbf6a9960
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Istanbul differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Jersey b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Jersey
new file mode 100644
index 0000000000000000000000000000000000000000..b9e95d92623c6cc4c35b16f7ceba3006f5ce4934
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Jersey differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Kaliningrad b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Kaliningrad
new file mode 100644
index 0000000000000000000000000000000000000000..0ec475647055bd235131c6620aa46da7f43209ac
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Kaliningrad differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Kiev b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Kiev
new file mode 100644
index 0000000000000000000000000000000000000000..753a6c86f38586797589233f4528837f5b09151c
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Kiev differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Kirov b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Kirov
new file mode 100644
index 0000000000000000000000000000000000000000..bfac56111d9cc81a93cce85205c685880433b96f
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Kirov differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Kyiv b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Kyiv
new file mode 100644
index 0000000000000000000000000000000000000000..753a6c86f38586797589233f4528837f5b09151c
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Kyiv differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Lisbon b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Lisbon
new file mode 100644
index 0000000000000000000000000000000000000000..7e9aae727b2b660e7f5e383121f445daf033a9c5
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Lisbon differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Ljubljana b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Ljubljana
new file mode 100644
index 0000000000000000000000000000000000000000..a1bf9281ed1bc2c9b82ee64efdca60b4af762ede
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Ljubljana differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/London b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/London
new file mode 100644
index 0000000000000000000000000000000000000000..b9e95d92623c6cc4c35b16f7ceba3006f5ce4934
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/London differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Luxembourg b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Luxembourg
new file mode 100644
index 0000000000000000000000000000000000000000..31973271d2f87f7e9df4e8b0a1481f09a9e5407d
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Luxembourg differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Madrid b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Madrid
new file mode 100644
index 0000000000000000000000000000000000000000..60bdf4d07e6ef544ff18013b272dfb851f1cc27c
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Madrid differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Malta b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Malta
new file mode 100644
index 0000000000000000000000000000000000000000..27539c2243ff2c6be1fe890995485be2df39bf77
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Malta differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Mariehamn b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Mariehamn
new file mode 100644
index 0000000000000000000000000000000000000000..ff5e56530570974516d249927952c69da601b664
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Mariehamn differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Minsk b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Minsk
new file mode 100644
index 0000000000000000000000000000000000000000..30d3a672bf64d0d787ac92bc75d9bc1cc62855c9
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Minsk differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Monaco b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Monaco
new file mode 100644
index 0000000000000000000000000000000000000000..00a27264c2cb3e28f2f46e5c267e12d575236a9d
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Monaco differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Moscow b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Moscow
new file mode 100644
index 0000000000000000000000000000000000000000..5e6b6de6451b4408fb71ef73950712a0827d49a6
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Moscow differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Nicosia b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Nicosia
new file mode 100644
index 0000000000000000000000000000000000000000..390347f442a486e296689c189e3346695bba5105
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Nicosia differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Oslo b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Oslo
new file mode 100644
index 0000000000000000000000000000000000000000..465546bd396ae5eb75076f13ba9c29b0c926c835
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Oslo differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Paris b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Paris
new file mode 100644
index 0000000000000000000000000000000000000000..00a27264c2cb3e28f2f46e5c267e12d575236a9d
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Paris differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Podgorica b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Podgorica
new file mode 100644
index 0000000000000000000000000000000000000000..a1bf9281ed1bc2c9b82ee64efdca60b4af762ede
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Podgorica differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Prague b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Prague
new file mode 100644
index 0000000000000000000000000000000000000000..fb7c145ac4c8ab8f39731e75db8c384b7dc4ee11
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Prague differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Riga b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Riga
new file mode 100644
index 0000000000000000000000000000000000000000..d99170b6420d4b91ec0c0e4652136f765974e0d8
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Riga differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Rome b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Rome
new file mode 100644
index 0000000000000000000000000000000000000000..639ca3be4062496b10a8dee26be3733cf457fbdd
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Rome differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Samara b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Samara
new file mode 100644
index 0000000000000000000000000000000000000000..8d0c26e5c85294b799e1f346994b04948d3175fe
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Samara differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/San_Marino b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/San_Marino
new file mode 100644
index 0000000000000000000000000000000000000000..639ca3be4062496b10a8dee26be3733cf457fbdd
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/San_Marino differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Sarajevo b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Sarajevo
new file mode 100644
index 0000000000000000000000000000000000000000..a1bf9281ed1bc2c9b82ee64efdca60b4af762ede
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Sarajevo differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Saratov b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Saratov
new file mode 100644
index 0000000000000000000000000000000000000000..2684d8f8b89f7807ed4a0fcba89822b24a0166bb
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Saratov differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Simferopol b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Simferopol
new file mode 100644
index 0000000000000000000000000000000000000000..298b8326ca7ab3e86b5f508fd06fc744b4a142f6
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Simferopol differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Skopje b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Skopje
new file mode 100644
index 0000000000000000000000000000000000000000..a1bf9281ed1bc2c9b82ee64efdca60b4af762ede
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Skopje differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Sofia b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Sofia
new file mode 100644
index 0000000000000000000000000000000000000000..89450685cd149950dc6d65d1b4f076d96c3dc9a0
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Sofia differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Stockholm b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Stockholm
new file mode 100644
index 0000000000000000000000000000000000000000..465546bd396ae5eb75076f13ba9c29b0c926c835
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Stockholm differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Tallinn b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Tallinn
new file mode 100644
index 0000000000000000000000000000000000000000..fbebdc6255b547b1f3a547f0f92cc8148f05f186
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Tallinn differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Tirane b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Tirane
new file mode 100644
index 0000000000000000000000000000000000000000..743a7337ffd8c404d1da0d2d078ea1cd8459affe
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Tirane differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Tiraspol b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Tiraspol
new file mode 100644
index 0000000000000000000000000000000000000000..9152e68594bb66cc756e0407654a203952fbd4e5
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Tiraspol differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Ulyanovsk b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Ulyanovsk
new file mode 100644
index 0000000000000000000000000000000000000000..bb842cb1f5087d422630f76f17c3a5eee6490a6b
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Ulyanovsk differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Uzhgorod b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Uzhgorod
new file mode 100644
index 0000000000000000000000000000000000000000..753a6c86f38586797589233f4528837f5b09151c
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Uzhgorod differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Vaduz b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Vaduz
new file mode 100644
index 0000000000000000000000000000000000000000..388df2969f2dc56738183bd4f0d5755c4533a797
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Vaduz differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Vatican b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Vatican
new file mode 100644
index 0000000000000000000000000000000000000000..639ca3be4062496b10a8dee26be3733cf457fbdd
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Vatican differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Vienna b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Vienna
new file mode 100644
index 0000000000000000000000000000000000000000..75339e98d0a72f2792924294d7a9e560dba4648f
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Vienna differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Vilnius b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Vilnius
new file mode 100644
index 0000000000000000000000000000000000000000..43c3d7f1089366e1c48297906c2693712ac6d99c
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Vilnius differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Volgograd b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Volgograd
new file mode 100644
index 0000000000000000000000000000000000000000..0715d58bc1873c8bae589a08752cbbae562692c7
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Volgograd differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Warsaw b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Warsaw
new file mode 100644
index 0000000000000000000000000000000000000000..efe1a40f2a8ffd499d22cd83e6b5df6c6c1e8e5c
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Warsaw differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Zagreb b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Zagreb
new file mode 100644
index 0000000000000000000000000000000000000000..a1bf9281ed1bc2c9b82ee64efdca60b4af762ede
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Zagreb differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Zaporozhye b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Zaporozhye
new file mode 100644
index 0000000000000000000000000000000000000000..753a6c86f38586797589233f4528837f5b09151c
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Zaporozhye differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Zurich b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Zurich
new file mode 100644
index 0000000000000000000000000000000000000000..388df2969f2dc56738183bd4f0d5755c4533a797
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/Zurich differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Europe/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Antananarivo b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Antananarivo
new file mode 100644
index 0000000000000000000000000000000000000000..5f4ebcb7f9789c4ecda13ac66c2e768851113004
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Antananarivo differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Chagos b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Chagos
new file mode 100644
index 0000000000000000000000000000000000000000..8b8ce226b6b7f67229577b837775e7d448348bde
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Chagos differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Christmas b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Christmas
new file mode 100644
index 0000000000000000000000000000000000000000..ed687d2985c208171adcaa3401496b05325edca4
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Christmas differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Cocos b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Cocos
new file mode 100644
index 0000000000000000000000000000000000000000..14b2ad09ead50a62d5e2b426396c51f9beb293be
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Cocos differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Comoro b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Comoro
new file mode 100644
index 0000000000000000000000000000000000000000..5f4ebcb7f9789c4ecda13ac66c2e768851113004
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Comoro differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Kerguelen b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Kerguelen
new file mode 100644
index 0000000000000000000000000000000000000000..58a82e4eb701ecb0413f908c57080646be392bba
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Kerguelen differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Mahe b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Mahe
new file mode 100644
index 0000000000000000000000000000000000000000..58d75bc26eec90272e97696f40483eb56c2b8b45
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Mahe differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Maldives b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Maldives
new file mode 100644
index 0000000000000000000000000000000000000000..58a82e4eb701ecb0413f908c57080646be392bba
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Maldives differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Mauritius b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Mauritius
new file mode 100644
index 0000000000000000000000000000000000000000..7c1113488200c4d45ddb533bbebd899e2073f750
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Mauritius differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Mayotte b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Mayotte
new file mode 100644
index 0000000000000000000000000000000000000000..5f4ebcb7f9789c4ecda13ac66c2e768851113004
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Mayotte differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Reunion b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Reunion
new file mode 100644
index 0000000000000000000000000000000000000000..58d75bc26eec90272e97696f40483eb56c2b8b45
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/Reunion differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Indian/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Mexico/BajaNorte b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Mexico/BajaNorte
new file mode 100644
index 0000000000000000000000000000000000000000..0d8c993bd1cf2fa2cbf002421ec9c0fb2b29645b
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Mexico/BajaNorte differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Mexico/BajaSur b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Mexico/BajaSur
new file mode 100644
index 0000000000000000000000000000000000000000..5aa6039ea4cb36077f048782b54c6275c25e86b3
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Mexico/BajaSur differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Mexico/General b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Mexico/General
new file mode 100644
index 0000000000000000000000000000000000000000..18112346129a885b5d5fa27109682b63784f72c0
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Mexico/General differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Mexico/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Mexico/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Apia b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Apia
new file mode 100644
index 0000000000000000000000000000000000000000..a6b835aab4c5e2e2a31bda0afdc8646b57d19a87
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Apia differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Auckland b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Auckland
new file mode 100644
index 0000000000000000000000000000000000000000..afb3929318475d4f0ea9d6c9e94d0f5f81d8b82e
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Auckland differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Bougainville b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Bougainville
new file mode 100644
index 0000000000000000000000000000000000000000..7c667093c50d33ce9161662a732fcf6c5092a38b
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Bougainville differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Chatham b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Chatham
new file mode 100644
index 0000000000000000000000000000000000000000..f06065ebd18315683f60cf87839d477a1d699f01
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Chatham differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Chuuk b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Chuuk
new file mode 100644
index 0000000000000000000000000000000000000000..5d8fc3a1b253d1df3a0184013469c6e46f6f6f75
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Chuuk differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Easter b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Easter
new file mode 100644
index 0000000000000000000000000000000000000000..54dff005b876339f5c1ff3dc0aeae1519c29b368
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Easter differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Efate b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Efate
new file mode 100644
index 0000000000000000000000000000000000000000..bf7471dd3fc26b7fba883acf0e0bf0a69687b31e
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Efate differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Enderbury b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Enderbury
new file mode 100644
index 0000000000000000000000000000000000000000..2b6a06088ef603f03fb482b628347ff72970fe3d
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Enderbury differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Fakaofo b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Fakaofo
new file mode 100644
index 0000000000000000000000000000000000000000..b7b30213e154012a5275c1384b41dbff29860644
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Fakaofo differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Fiji b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Fiji
new file mode 100644
index 0000000000000000000000000000000000000000..610b850b1dec4966d570eb36f9a8b35fd6aacd68
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Fiji differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Funafuti b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Funafuti
new file mode 100644
index 0000000000000000000000000000000000000000..6bc216823e007c8dbdd6a5e8402b2e0cc5eaf3fc
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Funafuti differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Galapagos b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Galapagos
new file mode 100644
index 0000000000000000000000000000000000000000..a9403eca467d3b2ccf85b76bf2d94678a2ce3030
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Galapagos differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Gambier b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Gambier
new file mode 100644
index 0000000000000000000000000000000000000000..ddfc34ffc0971e01ec4f13b78ddfa40033853cd1
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Gambier differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Guadalcanal b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Guadalcanal
new file mode 100644
index 0000000000000000000000000000000000000000..720c679017404f9b9ecec0687c09a879abf6d256
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Guadalcanal differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Guam b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Guam
new file mode 100644
index 0000000000000000000000000000000000000000..bf9a2d955fc23bb6c2043472e8292d4adc20d4ed
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Guam differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Honolulu b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Honolulu
new file mode 100644
index 0000000000000000000000000000000000000000..40e3d492e6c22c30041c31f159d4fe0ee9451c03
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Honolulu differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Johnston b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Johnston
new file mode 100644
index 0000000000000000000000000000000000000000..40e3d492e6c22c30041c31f159d4fe0ee9451c03
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Johnston differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kanton b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kanton
new file mode 100644
index 0000000000000000000000000000000000000000..2b6a06088ef603f03fb482b628347ff72970fe3d
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kanton differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kiritimati b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kiritimati
new file mode 100644
index 0000000000000000000000000000000000000000..2f676d3bf5c8599994bcabd402ca30efa4cde5dd
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kiritimati differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kosrae b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kosrae
new file mode 100644
index 0000000000000000000000000000000000000000..f5d58242c8198bfd7139883e1299b0706704bd32
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kosrae differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kwajalein b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kwajalein
new file mode 100644
index 0000000000000000000000000000000000000000..9416d522d0a3e19ab6b81317f5b94961c55e91fc
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Kwajalein differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Majuro b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Majuro
new file mode 100644
index 0000000000000000000000000000000000000000..6bc216823e007c8dbdd6a5e8402b2e0cc5eaf3fc
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Majuro differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Marquesas b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Marquesas
new file mode 100644
index 0000000000000000000000000000000000000000..6ea24b72cd9552c973510d1c17ace66fd35e1cc5
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Marquesas differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Midway b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Midway
new file mode 100644
index 0000000000000000000000000000000000000000..001289ceecff85fe0d0f376a6bc394329445f13f
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Midway differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Nauru b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Nauru
new file mode 100644
index 0000000000000000000000000000000000000000..ae13aac7792a04fe97b0a746f546e52d32f484c5
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Nauru differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Niue b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Niue
new file mode 100644
index 0000000000000000000000000000000000000000..be874e2472c2a79ed0d4de3011abd8831812911f
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Niue differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Norfolk b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Norfolk
new file mode 100644
index 0000000000000000000000000000000000000000..0c0bdbda2a72022180bde561f6693268e27beb6b
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Norfolk differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Noumea b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Noumea
new file mode 100644
index 0000000000000000000000000000000000000000..824f814160ee4a95cc6a6d5553b3c1aacc907895
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Noumea differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Pago_Pago b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Pago_Pago
new file mode 100644
index 0000000000000000000000000000000000000000..001289ceecff85fe0d0f376a6bc394329445f13f
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Pago_Pago differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Palau b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Palau
new file mode 100644
index 0000000000000000000000000000000000000000..bc8eb7a55b8a20a8c800507b620d0afef1d477a4
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Palau differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Pitcairn b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Pitcairn
new file mode 100644
index 0000000000000000000000000000000000000000..8a4ba4d30a6b7da8399f20a8b98c91169e04ae40
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Pitcairn differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Pohnpei b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Pohnpei
new file mode 100644
index 0000000000000000000000000000000000000000..720c679017404f9b9ecec0687c09a879abf6d256
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Pohnpei differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Ponape b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Ponape
new file mode 100644
index 0000000000000000000000000000000000000000..720c679017404f9b9ecec0687c09a879abf6d256
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Ponape differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Port_Moresby b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Port_Moresby
new file mode 100644
index 0000000000000000000000000000000000000000..5d8fc3a1b253d1df3a0184013469c6e46f6f6f75
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Port_Moresby differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Rarotonga b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Rarotonga
new file mode 100644
index 0000000000000000000000000000000000000000..7220bda0adb9f04d704cb893a5d1ee8bd9173b82
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Rarotonga differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Saipan b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Saipan
new file mode 100644
index 0000000000000000000000000000000000000000..bf9a2d955fc23bb6c2043472e8292d4adc20d4ed
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Saipan differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Samoa b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Samoa
new file mode 100644
index 0000000000000000000000000000000000000000..001289ceecff85fe0d0f376a6bc394329445f13f
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Samoa differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Tahiti b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Tahiti
new file mode 100644
index 0000000000000000000000000000000000000000..50a064fa0166a0dc22f89cdadf957a545d3f6544
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Tahiti differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Tarawa b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Tarawa
new file mode 100644
index 0000000000000000000000000000000000000000..6bc216823e007c8dbdd6a5e8402b2e0cc5eaf3fc
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Tarawa differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Tongatapu b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Tongatapu
new file mode 100644
index 0000000000000000000000000000000000000000..f28c8401845f84a68a46d45ec2f5b1383a0274b8
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Tongatapu differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Truk b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Truk
new file mode 100644
index 0000000000000000000000000000000000000000..5d8fc3a1b253d1df3a0184013469c6e46f6f6f75
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Truk differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Wake b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Wake
new file mode 100644
index 0000000000000000000000000000000000000000..6bc216823e007c8dbdd6a5e8402b2e0cc5eaf3fc
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Wake differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Wallis b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Wallis
new file mode 100644
index 0000000000000000000000000000000000000000..6bc216823e007c8dbdd6a5e8402b2e0cc5eaf3fc
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Wallis differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Yap b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Yap
new file mode 100644
index 0000000000000000000000000000000000000000..5d8fc3a1b253d1df3a0184013469c6e46f6f6f75
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/Yap differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/Pacific/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Alaska b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Alaska
new file mode 100644
index 0000000000000000000000000000000000000000..cdf0572be31d3052a98494e3d01802b83737f23c
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Alaska differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Aleutian b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Aleutian
new file mode 100644
index 0000000000000000000000000000000000000000..b1497bda631efdcb6635ffb6b0ee6f7da9e2a280
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Aleutian differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Arizona b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Arizona
new file mode 100644
index 0000000000000000000000000000000000000000..c2bd2f949b248b835c98216b4dc66f9f6eb0265e
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Arizona differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Central b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Central
new file mode 100644
index 0000000000000000000000000000000000000000..b016880653929aa40dd5ac0e82e4094a9d787cdf
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Central differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/East-Indiana b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/East-Indiana
new file mode 100644
index 0000000000000000000000000000000000000000..6b08d15bdaba6cf94dcb2681887154f4d265d8ba
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/East-Indiana differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Eastern b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Eastern
new file mode 100644
index 0000000000000000000000000000000000000000..2b6c2eea14df07392729ae9f5712a44ec4f02bae
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Eastern differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Hawaii b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Hawaii
new file mode 100644
index 0000000000000000000000000000000000000000..40e3d492e6c22c30041c31f159d4fe0ee9451c03
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Hawaii differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Indiana-Starke b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Indiana-Starke
new file mode 100644
index 0000000000000000000000000000000000000000..b187d5f8c75685af67913e9360b50ecad19fe6ad
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Indiana-Starke differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Michigan b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Michigan
new file mode 100644
index 0000000000000000000000000000000000000000..6eb3ac46ec56985b52488ae6a8d80247c2adcd4a
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Michigan differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Mountain b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Mountain
new file mode 100644
index 0000000000000000000000000000000000000000..09e54e5c7c5bb2384e37626d4b985cfad29ed29b
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Mountain differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Pacific b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Pacific
new file mode 100644
index 0000000000000000000000000000000000000000..aaf07787ad92b65eadae63b64bba290f9f961507
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Pacific differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Samoa b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Samoa
new file mode 100644
index 0000000000000000000000000000000000000000..001289ceecff85fe0d0f376a6bc394329445f13f
Binary files /dev/null and b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/Samoa differ
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/tzdata/zoneinfo/US/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3-2.6.3.dist-info/INSTALLER b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3-2.6.3.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3-2.6.3.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3-2.6.3.dist-info/METADATA b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3-2.6.3.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..b75670fb69f700549164c9ebfc8486eaed0d73ae
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3-2.6.3.dist-info/METADATA
@@ -0,0 +1,164 @@
+Metadata-Version: 2.4
+Name: urllib3
+Version: 2.6.3
+Summary: HTTP library with thread-safe connection pooling, file post, and more.
+Project-URL: Changelog, https://github.com/urllib3/urllib3/blob/main/CHANGES.rst
+Project-URL: Documentation, https://urllib3.readthedocs.io
+Project-URL: Code, https://github.com/urllib3/urllib3
+Project-URL: Issue tracker, https://github.com/urllib3/urllib3/issues
+Author-email: Andrey Petrov
+Maintainer-email: Seth Michael Larson , Quentin Pradet , Illia Volochii
+License-Expression: MIT
+License-File: LICENSE.txt
+Keywords: filepost,http,httplib,https,pooling,ssl,threadsafe,urllib
+Classifier: Environment :: Web Environment
+Classifier: Intended Audience :: Developers
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
+Classifier: Programming Language :: Python :: Free Threading :: 2 - Beta
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Internet :: WWW/HTTP
+Classifier: Topic :: Software Development :: Libraries
+Requires-Python: >=3.9
+Provides-Extra: brotli
+Requires-Dist: brotli>=1.2.0; (platform_python_implementation == 'CPython') and extra == 'brotli'
+Requires-Dist: brotlicffi>=1.2.0.0; (platform_python_implementation != 'CPython') and extra == 'brotli'
+Provides-Extra: h2
+Requires-Dist: h2<5,>=4; extra == 'h2'
+Provides-Extra: socks
+Requires-Dist: pysocks!=1.5.7,<2.0,>=1.5.6; extra == 'socks'
+Provides-Extra: zstd
+Requires-Dist: backports-zstd>=1.0.0; (python_version < '3.14') and extra == 'zstd'
+Description-Content-Type: text/markdown
+
+
+
+urllib3 is a powerful, *user-friendly* HTTP client for Python.
+urllib3 brings many critical features that are missing from the Python
+standard libraries:
+
+- Thread safety.
+- Connection pooling.
+- Client-side SSL/TLS verification.
+- File uploads with multipart encoding.
+- Helpers for retrying requests and dealing with HTTP redirects.
+- Support for gzip, deflate, brotli, and zstd encoding.
+- Proxy support for HTTP and SOCKS.
+- 100% test coverage.
+
+... and many more features, but most importantly: Our maintainers have a 15+
+year track record of maintaining urllib3 with the highest code standards and
+attention to security and safety.
+
+[Much of the Python ecosystem already uses urllib3](https://urllib3.readthedocs.io/en/stable/#who-uses)
+and you should too.
+
+
+## Installing
+
+urllib3 can be installed with [pip](https://pip.pypa.io):
+
+```bash
+$ python -m pip install urllib3
+```
+
+Alternatively, you can grab the latest source code from [GitHub](https://github.com/urllib3/urllib3):
+
+```bash
+$ git clone https://github.com/urllib3/urllib3.git
+$ cd urllib3
+$ pip install .
+```
+
+## Getting Started
+
+urllib3 is easy to use:
+
+```python3
+>>> import urllib3
+>>> resp = urllib3.request("GET", "http://httpbin.org/robots.txt")
+>>> resp.status
+200
+>>> resp.data
+b"User-agent: *\nDisallow: /deny\n"
+```
+
+urllib3 has usage and reference documentation at [urllib3.readthedocs.io](https://urllib3.readthedocs.io).
+
+
+## Community
+
+urllib3 has a [community Discord channel](https://discord.gg/urllib3) for asking questions and
+collaborating with other contributors. Drop by and say hello 👋
+
+
+## Contributing
+
+urllib3 happily accepts contributions. Please see our
+[contributing documentation](https://urllib3.readthedocs.io/en/latest/contributing.html)
+for some tips on getting started.
+
+
+## Security Disclosures
+
+To report a security vulnerability, please use the
+[Tidelift security contact](https://tidelift.com/security).
+Tidelift will coordinate the fix and disclosure with maintainers.
+
+
+## Maintainers
+
+Meet our maintainers since 2008:
+
+- Current Lead: [@illia-v](https://github.com/illia-v) (Illia Volochii)
+- [@sethmlarson](https://github.com/sethmlarson) (Seth M. Larson)
+- [@pquentin](https://github.com/pquentin) (Quentin Pradet)
+- [@theacodes](https://github.com/theacodes) (Thea Flowers)
+- [@haikuginger](https://github.com/haikuginger) (Jess Shapiro)
+- [@lukasa](https://github.com/lukasa) (Cory Benfield)
+- [@sigmavirus24](https://github.com/sigmavirus24) (Ian Stapleton Cordasco)
+- [@shazow](https://github.com/shazow) (Andrey Petrov)
+
+👋
+
+
+## Sponsorship
+
+If your company benefits from this library, please consider [sponsoring its
+development](https://urllib3.readthedocs.io/en/latest/sponsors.html).
+
+
+## For Enterprise
+
+Professional support for urllib3 is available as part of the [Tidelift
+Subscription][1]. Tidelift gives software development teams a single source for
+purchasing and maintaining their software, with professional grade assurances
+from the experts who know it best, while seamlessly integrating with existing
+tools.
+
+[1]: https://tidelift.com/subscription/pkg/pypi-urllib3?utm_source=pypi-urllib3&utm_medium=referral&utm_campaign=readme
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3-2.6.3.dist-info/RECORD b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3-2.6.3.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..f55a9012637e5a4240d67912fe2100d1cfb09e5a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3-2.6.3.dist-info/RECORD
@@ -0,0 +1,79 @@
+urllib3-2.6.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+urllib3-2.6.3.dist-info/METADATA,sha256=6ROQzJr0mwGXOPHXObXNklEwwy6dPmrMCGPCHF2Ygu8,6901
+urllib3-2.6.3.dist-info/RECORD,,
+urllib3-2.6.3.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
+urllib3-2.6.3.dist-info/licenses/LICENSE.txt,sha256=Ew46ZNX91dCWp1JpRjSn2d8oRGnehuVzIQAmgEHj1oY,1093
+urllib3/__init__.py,sha256=JMo1tg1nIV1AeJ2vENC_Txfl0e5h6Gzl9DGVk1rWRbo,6979
+urllib3/__pycache__/__init__.cpython-310.pyc,,
+urllib3/__pycache__/_base_connection.cpython-310.pyc,,
+urllib3/__pycache__/_collections.cpython-310.pyc,,
+urllib3/__pycache__/_request_methods.cpython-310.pyc,,
+urllib3/__pycache__/_version.cpython-310.pyc,,
+urllib3/__pycache__/connection.cpython-310.pyc,,
+urllib3/__pycache__/connectionpool.cpython-310.pyc,,
+urllib3/__pycache__/exceptions.cpython-310.pyc,,
+urllib3/__pycache__/fields.cpython-310.pyc,,
+urllib3/__pycache__/filepost.cpython-310.pyc,,
+urllib3/__pycache__/poolmanager.cpython-310.pyc,,
+urllib3/__pycache__/response.cpython-310.pyc,,
+urllib3/_base_connection.py,sha256=T1cwH3RhzsrBh6Bz3AOGVDboRsE7veijqZPXXQTR2Rg,5568
+urllib3/_collections.py,sha256=UvV7UqtGTSKdvw8N_LxWuEikZLm5gB1zFfTZYH9KhAk,17595
+urllib3/_request_methods.py,sha256=gCeF85SO_UU4WoPwYHIoz_tw-eM_EVOkLFp8OFsC7DA,9931
+urllib3/_version.py,sha256=vKE8or0mmqgsFpVb7FYms-nNOVCPPAEifgxVrTaPByw,704
+urllib3/connection.py,sha256=1ZR2gqfFdIzTYIUwF0K5nftg26hLqU5nr1yHTdKb7WA,42800
+urllib3/connectionpool.py,sha256=ZEhudsa8BIubD2M0XoxBBsjxbsXwMgUScH7oQ9i-j1Y,43371
+urllib3/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+urllib3/contrib/__pycache__/__init__.cpython-310.pyc,,
+urllib3/contrib/__pycache__/pyopenssl.cpython-310.pyc,,
+urllib3/contrib/__pycache__/socks.cpython-310.pyc,,
+urllib3/contrib/emscripten/__init__.py,sha256=wyXve8rmqX7s2KqRQBxD5Wl48jzWPn5-1u_XoQBELVc,836
+urllib3/contrib/emscripten/__pycache__/__init__.cpython-310.pyc,,
+urllib3/contrib/emscripten/__pycache__/connection.cpython-310.pyc,,
+urllib3/contrib/emscripten/__pycache__/fetch.cpython-310.pyc,,
+urllib3/contrib/emscripten/__pycache__/request.cpython-310.pyc,,
+urllib3/contrib/emscripten/__pycache__/response.cpython-310.pyc,,
+urllib3/contrib/emscripten/connection.py,sha256=giElsBoUsKVURbZzb8GCrJmqW23Xnvj2aNyQVF42slg,8960
+urllib3/contrib/emscripten/emscripten_fetch_worker.js,sha256=z1k3zZ4_hDKd3-tN7wzz8LHjHC2pxN_uu8B3k9D9A3c,3677
+urllib3/contrib/emscripten/fetch.py,sha256=5xcd--viFxZd2nBy0aK73dtJ9Tsh1yYZU_SUXwnwibk,23520
+urllib3/contrib/emscripten/request.py,sha256=mL28szy1KvE3NJhWor5jNmarp8gwplDU-7gwGZY5g0Q,566
+urllib3/contrib/emscripten/response.py,sha256=7oVPENYZHuzEGRtG40HonpH5tAIYHsGcHPbJt2Z0U-Y,9507
+urllib3/contrib/pyopenssl.py,sha256=4awTja4o3beTGTGmmWo_3rBoEgzje95Q4bgWz4iiSx8,19724
+urllib3/contrib/socks.py,sha256=eB2eWfu8Wz1fn-qvr_qE_dZAceck2Ncv7XQ15DlvVbU,7547
+urllib3/exceptions.py,sha256=eeQ77nJjF97bP6SvCK4gmx6BpQZKU8yjvM-AIDwZdX8,9952
+urllib3/fields.py,sha256=FCf7UULSkf10cuTRUWTQESzxgl1WT8e2aCy3kfyZins,10829
+urllib3/filepost.py,sha256=U8eNZ-mpKKHhrlbHEEiTxxgK16IejhEa7uz42yqA_dI,2388
+urllib3/http2/__init__.py,sha256=xzrASH7R5ANRkPJOot5lGnATOq3KKuyXzI42rcnwmqs,1741
+urllib3/http2/__pycache__/__init__.cpython-310.pyc,,
+urllib3/http2/__pycache__/connection.cpython-310.pyc,,
+urllib3/http2/__pycache__/probe.cpython-310.pyc,,
+urllib3/http2/connection.py,sha256=bHMH6fNvatwXPrKqrcn74yA3pUWcqPDppnK1LcKCbP8,12578
+urllib3/http2/probe.py,sha256=nnAkqbhAakOiF75rz7W0udZ38Eeh_uD8fjV74N73FEI,3014
+urllib3/poolmanager.py,sha256=NYP5vkKfadGddaBacUk6z6u8rTP9wgCFGGjVtf1mkcc,23811
+urllib3/py.typed,sha256=UaCuPFa3H8UAakbt-5G8SPacldTOGvJv18pPjUJ5gDY,93
+urllib3/response.py,sha256=2VDtH9KrYNQLUbDYHZ3GgwzH3JZphkn_JoqtB7ozkt0,52931
+urllib3/util/__init__.py,sha256=-qeS0QceivazvBEKDNFCAI-6ACcdDOE4TMvo7SLNlAQ,1001
+urllib3/util/__pycache__/__init__.cpython-310.pyc,,
+urllib3/util/__pycache__/connection.cpython-310.pyc,,
+urllib3/util/__pycache__/proxy.cpython-310.pyc,,
+urllib3/util/__pycache__/request.cpython-310.pyc,,
+urllib3/util/__pycache__/response.cpython-310.pyc,,
+urllib3/util/__pycache__/retry.cpython-310.pyc,,
+urllib3/util/__pycache__/ssl_.cpython-310.pyc,,
+urllib3/util/__pycache__/ssl_match_hostname.cpython-310.pyc,,
+urllib3/util/__pycache__/ssltransport.cpython-310.pyc,,
+urllib3/util/__pycache__/timeout.cpython-310.pyc,,
+urllib3/util/__pycache__/url.cpython-310.pyc,,
+urllib3/util/__pycache__/util.cpython-310.pyc,,
+urllib3/util/__pycache__/wait.cpython-310.pyc,,
+urllib3/util/connection.py,sha256=JjO722lzHlzLXPTkr9ZWBdhseXnMVjMSb1DJLVrXSnQ,4444
+urllib3/util/proxy.py,sha256=seP8-Q5B6bB0dMtwPj-YcZZQ30vHuLqRu-tI0JZ2fzs,1148
+urllib3/util/request.py,sha256=itpnC8ug7D4nVfDmGUCRMlgkARUQ13r_XMxSnzTwmpE,8363
+urllib3/util/response.py,sha256=vQE639uoEhj1vpjEdxu5lNIhJCSUZkd7pqllUI0BZOA,3374
+urllib3/util/retry.py,sha256=WOcIHVaxKf-dVb89lUbpvcpeM7rNYF_vsKsCOKw10Z8,19235
+urllib3/util/ssl_.py,sha256=Y9RNkWCIehDxIRvyFnHUjiMlPolm368GYMya2YdDOag,19929
+urllib3/util/ssl_match_hostname.py,sha256=Di7DU7zokoltapT_F0Sj21ffYxwaS_cE5apOtwueeyA,5845
+urllib3/util/ssltransport.py,sha256=Ez4O8pR_vT8dan_FvqBYS6dgDfBXEMfVfrzcdUoWfi4,8847
+urllib3/util/timeout.py,sha256=4eT1FVeZZU7h7mYD1Jq2OXNe4fxekdNvhoWUkZusRpA,10346
+urllib3/util/url.py,sha256=WRh-TMYXosmgp8m8lT4H5spoHw5yUjlcMCfU53AkoAs,15205
+urllib3/util/util.py,sha256=j3lbZK1jPyiwD34T8IgJzdWEZVT-4E-0vYIJi9UjeNA,1146
+urllib3/util/wait.py,sha256=_ph8IrUR3sqPqi0OopQgJUlH4wzkGeM5CiyA7XGGtmI,4423
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3-2.6.3.dist-info/WHEEL b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3-2.6.3.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..ae8ec1bdaa94d726ceb907542d76cbd5d38cafcd
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3-2.6.3.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: hatchling 1.28.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3-2.6.3.dist-info/licenses/LICENSE.txt b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3-2.6.3.dist-info/licenses/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..e6183d0276b26c5b87aecccf8d0d5bcd7b1148d4
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3-2.6.3.dist-info/licenses/LICENSE.txt
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2008-2020 Andrey Petrov and contributors.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3fe782c8a45bbabcf240f3cac4303ac12b0ec274
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/__init__.py
@@ -0,0 +1,211 @@
+"""
+Python HTTP library with thread-safe connection pooling, file post support, user friendly, and more
+"""
+
+from __future__ import annotations
+
+# Set default logging handler to avoid "No handler found" warnings.
+import logging
+import sys
+import typing
+import warnings
+from logging import NullHandler
+
+from . import exceptions
+from ._base_connection import _TYPE_BODY
+from ._collections import HTTPHeaderDict
+from ._version import __version__
+from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url
+from .filepost import _TYPE_FIELDS, encode_multipart_formdata
+from .poolmanager import PoolManager, ProxyManager, proxy_from_url
+from .response import BaseHTTPResponse, HTTPResponse
+from .util.request import make_headers
+from .util.retry import Retry
+from .util.timeout import Timeout
+
+# Ensure that Python is compiled with OpenSSL 1.1.1+
+# If the 'ssl' module isn't available at all that's
+# fine, we only care if the module is available.
+try:
+ import ssl
+except ImportError:
+ pass
+else:
+ if not ssl.OPENSSL_VERSION.startswith("OpenSSL "): # Defensive:
+ warnings.warn(
+ "urllib3 v2 only supports OpenSSL 1.1.1+, currently "
+ f"the 'ssl' module is compiled with {ssl.OPENSSL_VERSION!r}. "
+ "See: https://github.com/urllib3/urllib3/issues/3020",
+ exceptions.NotOpenSSLWarning,
+ )
+ elif ssl.OPENSSL_VERSION_INFO < (1, 1, 1): # Defensive:
+ raise ImportError(
+ "urllib3 v2 only supports OpenSSL 1.1.1+, currently "
+ f"the 'ssl' module is compiled with {ssl.OPENSSL_VERSION!r}. "
+ "See: https://github.com/urllib3/urllib3/issues/2168"
+ )
+
+__author__ = "Andrey Petrov (andrey.petrov@shazow.net)"
+__license__ = "MIT"
+__version__ = __version__
+
+__all__ = (
+ "HTTPConnectionPool",
+ "HTTPHeaderDict",
+ "HTTPSConnectionPool",
+ "PoolManager",
+ "ProxyManager",
+ "HTTPResponse",
+ "Retry",
+ "Timeout",
+ "add_stderr_logger",
+ "connection_from_url",
+ "disable_warnings",
+ "encode_multipart_formdata",
+ "make_headers",
+ "proxy_from_url",
+ "request",
+ "BaseHTTPResponse",
+)
+
+logging.getLogger(__name__).addHandler(NullHandler())
+
+
+def add_stderr_logger(
+ level: int = logging.DEBUG,
+) -> logging.StreamHandler[typing.TextIO]:
+ """
+ Helper for quickly adding a StreamHandler to the logger. Useful for
+ debugging.
+
+ Returns the handler after adding it.
+ """
+ # This method needs to be in this __init__.py to get the __name__ correct
+ # even if urllib3 is vendored within another package.
+ logger = logging.getLogger(__name__)
+ handler = logging.StreamHandler()
+ handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
+ logger.addHandler(handler)
+ logger.setLevel(level)
+ logger.debug("Added a stderr logging handler to logger: %s", __name__)
+ return handler
+
+
+# ... Clean up.
+del NullHandler
+
+
+# All warning filters *must* be appended unless you're really certain that they
+# shouldn't be: otherwise, it's very hard for users to use most Python
+# mechanisms to silence them.
+# SecurityWarning's always go off by default.
+warnings.simplefilter("always", exceptions.SecurityWarning, append=True)
+# InsecurePlatformWarning's don't vary between requests, so we keep it default.
+warnings.simplefilter("default", exceptions.InsecurePlatformWarning, append=True)
+
+
+def disable_warnings(category: type[Warning] = exceptions.HTTPWarning) -> None:
+ """
+ Helper for quickly disabling all urllib3 warnings.
+ """
+ warnings.simplefilter("ignore", category)
+
+
+_DEFAULT_POOL = PoolManager()
+
+
+def request(
+ method: str,
+ url: str,
+ *,
+ body: _TYPE_BODY | None = None,
+ fields: _TYPE_FIELDS | None = None,
+ headers: typing.Mapping[str, str] | None = None,
+ preload_content: bool | None = True,
+ decode_content: bool | None = True,
+ redirect: bool | None = True,
+ retries: Retry | bool | int | None = None,
+ timeout: Timeout | float | int | None = 3,
+ json: typing.Any | None = None,
+) -> BaseHTTPResponse:
+ """
+ A convenience, top-level request method. It uses a module-global ``PoolManager`` instance.
+ Therefore, its side effects could be shared across dependencies relying on it.
+ To avoid side effects create a new ``PoolManager`` instance and use it instead.
+ The method does not accept low-level ``**urlopen_kw`` keyword arguments.
+
+ :param method:
+ HTTP request method (such as GET, POST, PUT, etc.)
+
+ :param url:
+ The URL to perform the request on.
+
+ :param body:
+ Data to send in the request body, either :class:`str`, :class:`bytes`,
+ an iterable of :class:`str`/:class:`bytes`, or a file-like object.
+
+ :param fields:
+ Data to encode and send in the request body.
+
+ :param headers:
+ Dictionary of custom headers to send, such as User-Agent,
+ If-None-Match, etc.
+
+ :param bool preload_content:
+ If True, the response's body will be preloaded into memory.
+
+ :param bool decode_content:
+ If True, will attempt to decode the body based on the
+ 'content-encoding' header.
+
+ :param redirect:
+ If True, automatically handle redirects (status codes 301, 302,
+ 303, 307, 308). Each redirect counts as a retry. Disabling retries
+ will disable redirect, too.
+
+ :param retries:
+ Configure the number of retries to allow before raising a
+ :class:`~urllib3.exceptions.MaxRetryError` exception.
+
+ If ``None`` (default) will retry 3 times, see ``Retry.DEFAULT``. Pass a
+ :class:`~urllib3.util.retry.Retry` object for fine-grained control
+ over different types of retries.
+ Pass an integer number to retry connection errors that many times,
+ but no other types of errors. Pass zero to never retry.
+
+ If ``False``, then retries are disabled and any exception is raised
+ immediately. Also, instead of raising a MaxRetryError on redirects,
+ the redirect response will be returned.
+
+ :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int.
+
+ :param timeout:
+ If specified, overrides the default timeout for this one
+ request. It may be a float (in seconds) or an instance of
+ :class:`urllib3.util.Timeout`.
+
+ :param json:
+ Data to encode and send as JSON with UTF-encoded in the request body.
+ The ``"Content-Type"`` header will be set to ``"application/json"``
+ unless specified otherwise.
+ """
+
+ return _DEFAULT_POOL.request(
+ method,
+ url,
+ body=body,
+ fields=fields,
+ headers=headers,
+ preload_content=preload_content,
+ decode_content=decode_content,
+ redirect=redirect,
+ retries=retries,
+ timeout=timeout,
+ json=json,
+ )
+
+
+if sys.platform == "emscripten":
+ from .contrib.emscripten import inject_into_urllib3 # noqa: 401
+
+ inject_into_urllib3()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/_base_connection.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/_base_connection.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc0f318c0b380926eed0f4209d395c79963eaf9e
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/_base_connection.py
@@ -0,0 +1,165 @@
+from __future__ import annotations
+
+import typing
+
+from .util.connection import _TYPE_SOCKET_OPTIONS
+from .util.timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT
+from .util.url import Url
+
+_TYPE_BODY = typing.Union[bytes, typing.IO[typing.Any], typing.Iterable[bytes], str]
+
+
+class ProxyConfig(typing.NamedTuple):
+ ssl_context: ssl.SSLContext | None
+ use_forwarding_for_https: bool
+ assert_hostname: None | str | typing.Literal[False]
+ assert_fingerprint: str | None
+
+
+class _ResponseOptions(typing.NamedTuple):
+ # TODO: Remove this in favor of a better
+ # HTTP request/response lifecycle tracking.
+ request_method: str
+ request_url: str
+ preload_content: bool
+ decode_content: bool
+ enforce_content_length: bool
+
+
+if typing.TYPE_CHECKING:
+ import ssl
+ from typing import Protocol
+
+ from .response import BaseHTTPResponse
+
+ class BaseHTTPConnection(Protocol):
+ default_port: typing.ClassVar[int]
+ default_socket_options: typing.ClassVar[_TYPE_SOCKET_OPTIONS]
+
+ host: str
+ port: int
+ timeout: None | (
+ float
+ ) # Instance doesn't store _DEFAULT_TIMEOUT, must be resolved.
+ blocksize: int
+ source_address: tuple[str, int] | None
+ socket_options: _TYPE_SOCKET_OPTIONS | None
+
+ proxy: Url | None
+ proxy_config: ProxyConfig | None
+
+ is_verified: bool
+ proxy_is_verified: bool | None
+
+ def __init__(
+ self,
+ host: str,
+ port: int | None = None,
+ *,
+ timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,
+ source_address: tuple[str, int] | None = None,
+ blocksize: int = 8192,
+ socket_options: _TYPE_SOCKET_OPTIONS | None = ...,
+ proxy: Url | None = None,
+ proxy_config: ProxyConfig | None = None,
+ ) -> None: ...
+
+ def set_tunnel(
+ self,
+ host: str,
+ port: int | None = None,
+ headers: typing.Mapping[str, str] | None = None,
+ scheme: str = "http",
+ ) -> None: ...
+
+ def connect(self) -> None: ...
+
+ def request(
+ self,
+ method: str,
+ url: str,
+ body: _TYPE_BODY | None = None,
+ headers: typing.Mapping[str, str] | None = None,
+ # We know *at least* botocore is depending on the order of the
+ # first 3 parameters so to be safe we only mark the later ones
+ # as keyword-only to ensure we have space to extend.
+ *,
+ chunked: bool = False,
+ preload_content: bool = True,
+ decode_content: bool = True,
+ enforce_content_length: bool = True,
+ ) -> None: ...
+
+ def getresponse(self) -> BaseHTTPResponse: ...
+
+ def close(self) -> None: ...
+
+ @property
+ def is_closed(self) -> bool:
+ """Whether the connection either is brand new or has been previously closed.
+ If this property is True then both ``is_connected`` and ``has_connected_to_proxy``
+ properties must be False.
+ """
+
+ @property
+ def is_connected(self) -> bool:
+ """Whether the connection is actively connected to any origin (proxy or target)"""
+
+ @property
+ def has_connected_to_proxy(self) -> bool:
+ """Whether the connection has successfully connected to its proxy.
+ This returns False if no proxy is in use. Used to determine whether
+ errors are coming from the proxy layer or from tunnelling to the target origin.
+ """
+
+ class BaseHTTPSConnection(BaseHTTPConnection, Protocol):
+ default_port: typing.ClassVar[int]
+ default_socket_options: typing.ClassVar[_TYPE_SOCKET_OPTIONS]
+
+ # Certificate verification methods
+ cert_reqs: int | str | None
+ assert_hostname: None | str | typing.Literal[False]
+ assert_fingerprint: str | None
+ ssl_context: ssl.SSLContext | None
+
+ # Trusted CAs
+ ca_certs: str | None
+ ca_cert_dir: str | None
+ ca_cert_data: None | str | bytes
+
+ # TLS version
+ ssl_minimum_version: int | None
+ ssl_maximum_version: int | None
+ ssl_version: int | str | None # Deprecated
+
+ # Client certificates
+ cert_file: str | None
+ key_file: str | None
+ key_password: str | None
+
+ def __init__(
+ self,
+ host: str,
+ port: int | None = None,
+ *,
+ timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,
+ source_address: tuple[str, int] | None = None,
+ blocksize: int = 16384,
+ socket_options: _TYPE_SOCKET_OPTIONS | None = ...,
+ proxy: Url | None = None,
+ proxy_config: ProxyConfig | None = None,
+ cert_reqs: int | str | None = None,
+ assert_hostname: None | str | typing.Literal[False] = None,
+ assert_fingerprint: str | None = None,
+ server_hostname: str | None = None,
+ ssl_context: ssl.SSLContext | None = None,
+ ca_certs: str | None = None,
+ ca_cert_dir: str | None = None,
+ ca_cert_data: None | str | bytes = None,
+ ssl_minimum_version: int | None = None,
+ ssl_maximum_version: int | None = None,
+ ssl_version: int | str | None = None, # Deprecated
+ cert_file: str | None = None,
+ key_file: str | None = None,
+ key_password: str | None = None,
+ ) -> None: ...
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/_collections.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/_collections.py
new file mode 100644
index 0000000000000000000000000000000000000000..0378aab1b1aba0b61cb2741156dea652591ca2bf
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/_collections.py
@@ -0,0 +1,487 @@
+from __future__ import annotations
+
+import typing
+from collections import OrderedDict
+from enum import Enum, auto
+from threading import RLock
+
+if typing.TYPE_CHECKING:
+ # We can only import Protocol if TYPE_CHECKING because it's a development
+ # dependency, and is not available at runtime.
+ from typing import Protocol
+
+ from typing_extensions import Self
+
+ class HasGettableStringKeys(Protocol):
+ def keys(self) -> typing.Iterator[str]: ...
+
+ def __getitem__(self, key: str) -> str: ...
+
+
+__all__ = ["RecentlyUsedContainer", "HTTPHeaderDict"]
+
+
+# Key type
+_KT = typing.TypeVar("_KT")
+# Value type
+_VT = typing.TypeVar("_VT")
+# Default type
+_DT = typing.TypeVar("_DT")
+
+ValidHTTPHeaderSource = typing.Union[
+ "HTTPHeaderDict",
+ typing.Mapping[str, str],
+ typing.Iterable[tuple[str, str]],
+ "HasGettableStringKeys",
+]
+
+
+class _Sentinel(Enum):
+ not_passed = auto()
+
+
+def ensure_can_construct_http_header_dict(
+ potential: object,
+) -> ValidHTTPHeaderSource | None:
+ if isinstance(potential, HTTPHeaderDict):
+ return potential
+ elif isinstance(potential, typing.Mapping):
+ # Full runtime checking of the contents of a Mapping is expensive, so for the
+ # purposes of typechecking, we assume that any Mapping is the right shape.
+ return typing.cast(typing.Mapping[str, str], potential)
+ elif isinstance(potential, typing.Iterable):
+ # Similarly to Mapping, full runtime checking of the contents of an Iterable is
+ # expensive, so for the purposes of typechecking, we assume that any Iterable
+ # is the right shape.
+ return typing.cast(typing.Iterable[tuple[str, str]], potential)
+ elif hasattr(potential, "keys") and hasattr(potential, "__getitem__"):
+ return typing.cast("HasGettableStringKeys", potential)
+ else:
+ return None
+
+
+class RecentlyUsedContainer(typing.Generic[_KT, _VT], typing.MutableMapping[_KT, _VT]):
+ """
+ Provides a thread-safe dict-like container which maintains up to
+ ``maxsize`` keys while throwing away the least-recently-used keys beyond
+ ``maxsize``.
+
+ :param maxsize:
+ Maximum number of recent elements to retain.
+
+ :param dispose_func:
+ Every time an item is evicted from the container,
+ ``dispose_func(value)`` is called. Callback which will get called
+ """
+
+ _container: typing.OrderedDict[_KT, _VT]
+ _maxsize: int
+ dispose_func: typing.Callable[[_VT], None] | None
+ lock: RLock
+
+ def __init__(
+ self,
+ maxsize: int = 10,
+ dispose_func: typing.Callable[[_VT], None] | None = None,
+ ) -> None:
+ super().__init__()
+ self._maxsize = maxsize
+ self.dispose_func = dispose_func
+ self._container = OrderedDict()
+ self.lock = RLock()
+
+ def __getitem__(self, key: _KT) -> _VT:
+ # Re-insert the item, moving it to the end of the eviction line.
+ with self.lock:
+ item = self._container.pop(key)
+ self._container[key] = item
+ return item
+
+ def __setitem__(self, key: _KT, value: _VT) -> None:
+ evicted_item = None
+ with self.lock:
+ # Possibly evict the existing value of 'key'
+ try:
+ # If the key exists, we'll overwrite it, which won't change the
+ # size of the pool. Because accessing a key should move it to
+ # the end of the eviction line, we pop it out first.
+ evicted_item = key, self._container.pop(key)
+ self._container[key] = value
+ except KeyError:
+ # When the key does not exist, we insert the value first so that
+ # evicting works in all cases, including when self._maxsize is 0
+ self._container[key] = value
+ if len(self._container) > self._maxsize:
+ # If we didn't evict an existing value, and we've hit our maximum
+ # size, then we have to evict the least recently used item from
+ # the beginning of the container.
+ evicted_item = self._container.popitem(last=False)
+
+ # After releasing the lock on the pool, dispose of any evicted value.
+ if evicted_item is not None and self.dispose_func:
+ _, evicted_value = evicted_item
+ self.dispose_func(evicted_value)
+
+ def __delitem__(self, key: _KT) -> None:
+ with self.lock:
+ value = self._container.pop(key)
+
+ if self.dispose_func:
+ self.dispose_func(value)
+
+ def __len__(self) -> int:
+ with self.lock:
+ return len(self._container)
+
+ def __iter__(self) -> typing.NoReturn:
+ raise NotImplementedError(
+ "Iteration over this class is unlikely to be threadsafe."
+ )
+
+ def clear(self) -> None:
+ with self.lock:
+ # Copy pointers to all values, then wipe the mapping
+ values = list(self._container.values())
+ self._container.clear()
+
+ if self.dispose_func:
+ for value in values:
+ self.dispose_func(value)
+
+ def keys(self) -> set[_KT]: # type: ignore[override]
+ with self.lock:
+ return set(self._container.keys())
+
+
+class HTTPHeaderDictItemView(set[tuple[str, str]]):
+ """
+ HTTPHeaderDict is unusual for a Mapping[str, str] in that it has two modes of
+ address.
+
+ If we directly try to get an item with a particular name, we will get a string
+ back that is the concatenated version of all the values:
+
+ >>> d['X-Header-Name']
+ 'Value1, Value2, Value3'
+
+ However, if we iterate over an HTTPHeaderDict's items, we will optionally combine
+ these values based on whether combine=True was called when building up the dictionary
+
+ >>> d = HTTPHeaderDict({"A": "1", "B": "foo"})
+ >>> d.add("A", "2", combine=True)
+ >>> d.add("B", "bar")
+ >>> list(d.items())
+ [
+ ('A', '1, 2'),
+ ('B', 'foo'),
+ ('B', 'bar'),
+ ]
+
+ This class conforms to the interface required by the MutableMapping ABC while
+ also giving us the nonstandard iteration behavior we want; items with duplicate
+ keys, ordered by time of first insertion.
+ """
+
+ _headers: HTTPHeaderDict
+
+ def __init__(self, headers: HTTPHeaderDict) -> None:
+ self._headers = headers
+
+ def __len__(self) -> int:
+ return len(list(self._headers.iteritems()))
+
+ def __iter__(self) -> typing.Iterator[tuple[str, str]]:
+ return self._headers.iteritems()
+
+ def __contains__(self, item: object) -> bool:
+ if isinstance(item, tuple) and len(item) == 2:
+ passed_key, passed_val = item
+ if isinstance(passed_key, str) and isinstance(passed_val, str):
+ return self._headers._has_value_for_header(passed_key, passed_val)
+ return False
+
+
+class HTTPHeaderDict(typing.MutableMapping[str, str]):
+ """
+ :param headers:
+ An iterable of field-value pairs. Must not contain multiple field names
+ when compared case-insensitively.
+
+ :param kwargs:
+ Additional field-value pairs to pass in to ``dict.update``.
+
+ A ``dict`` like container for storing HTTP Headers.
+
+ Field names are stored and compared case-insensitively in compliance with
+ RFC 7230. Iteration provides the first case-sensitive key seen for each
+ case-insensitive pair.
+
+ Using ``__setitem__`` syntax overwrites fields that compare equal
+ case-insensitively in order to maintain ``dict``'s api. For fields that
+ compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add``
+ in a loop.
+
+ If multiple fields that are equal case-insensitively are passed to the
+ constructor or ``.update``, the behavior is undefined and some will be
+ lost.
+
+ >>> headers = HTTPHeaderDict()
+ >>> headers.add('Set-Cookie', 'foo=bar')
+ >>> headers.add('set-cookie', 'baz=quxx')
+ >>> headers['content-length'] = '7'
+ >>> headers['SET-cookie']
+ 'foo=bar, baz=quxx'
+ >>> headers['Content-Length']
+ '7'
+ """
+
+ _container: typing.MutableMapping[str, list[str]]
+
+ def __init__(self, headers: ValidHTTPHeaderSource | None = None, **kwargs: str):
+ super().__init__()
+ self._container = {} # 'dict' is insert-ordered
+ if headers is not None:
+ if isinstance(headers, HTTPHeaderDict):
+ self._copy_from(headers)
+ else:
+ self.extend(headers)
+ if kwargs:
+ self.extend(kwargs)
+
+ def __setitem__(self, key: str, val: str) -> None:
+ # avoid a bytes/str comparison by decoding before httplib
+ if isinstance(key, bytes):
+ key = key.decode("latin-1")
+ self._container[key.lower()] = [key, val]
+
+ def __getitem__(self, key: str) -> str:
+ if isinstance(key, bytes):
+ key = key.decode("latin-1")
+ val = self._container[key.lower()]
+ return ", ".join(val[1:])
+
+ def __delitem__(self, key: str) -> None:
+ if isinstance(key, bytes):
+ key = key.decode("latin-1")
+ del self._container[key.lower()]
+
+ def __contains__(self, key: object) -> bool:
+ if isinstance(key, bytes):
+ key = key.decode("latin-1")
+ if isinstance(key, str):
+ return key.lower() in self._container
+ return False
+
+ def setdefault(self, key: str, default: str = "") -> str:
+ return super().setdefault(key, default)
+
+ def __eq__(self, other: object) -> bool:
+ maybe_constructable = ensure_can_construct_http_header_dict(other)
+ if maybe_constructable is None:
+ return False
+ else:
+ other_as_http_header_dict = type(self)(maybe_constructable)
+
+ return {k.lower(): v for k, v in self.itermerged()} == {
+ k.lower(): v for k, v in other_as_http_header_dict.itermerged()
+ }
+
+ def __ne__(self, other: object) -> bool:
+ return not self.__eq__(other)
+
+ def __len__(self) -> int:
+ return len(self._container)
+
+ def __iter__(self) -> typing.Iterator[str]:
+ # Only provide the originally cased names
+ for vals in self._container.values():
+ yield vals[0]
+
+ def discard(self, key: str) -> None:
+ try:
+ del self[key]
+ except KeyError:
+ pass
+
+ def add(self, key: str, val: str, *, combine: bool = False) -> None:
+ """Adds a (name, value) pair, doesn't overwrite the value if it already
+ exists.
+
+ If this is called with combine=True, instead of adding a new header value
+ as a distinct item during iteration, this will instead append the value to
+ any existing header value with a comma. If no existing header value exists
+ for the key, then the value will simply be added, ignoring the combine parameter.
+
+ >>> headers = HTTPHeaderDict(foo='bar')
+ >>> headers.add('Foo', 'baz')
+ >>> headers['foo']
+ 'bar, baz'
+ >>> list(headers.items())
+ [('foo', 'bar'), ('foo', 'baz')]
+ >>> headers.add('foo', 'quz', combine=True)
+ >>> list(headers.items())
+ [('foo', 'bar, baz, quz')]
+ """
+ # avoid a bytes/str comparison by decoding before httplib
+ if isinstance(key, bytes):
+ key = key.decode("latin-1")
+ key_lower = key.lower()
+ new_vals = [key, val]
+ # Keep the common case aka no item present as fast as possible
+ vals = self._container.setdefault(key_lower, new_vals)
+ if new_vals is not vals:
+ # if there are values here, then there is at least the initial
+ # key/value pair
+ assert len(vals) >= 2
+ if combine:
+ vals[-1] = vals[-1] + ", " + val
+ else:
+ vals.append(val)
+
+ def extend(self, *args: ValidHTTPHeaderSource, **kwargs: str) -> None:
+ """Generic import function for any type of header-like object.
+ Adapted version of MutableMapping.update in order to insert items
+ with self.add instead of self.__setitem__
+ """
+ if len(args) > 1:
+ raise TypeError(
+ f"extend() takes at most 1 positional arguments ({len(args)} given)"
+ )
+ other = args[0] if len(args) >= 1 else ()
+
+ if isinstance(other, HTTPHeaderDict):
+ for key, val in other.iteritems():
+ self.add(key, val)
+ elif isinstance(other, typing.Mapping):
+ for key, val in other.items():
+ self.add(key, val)
+ elif isinstance(other, typing.Iterable):
+ other = typing.cast(typing.Iterable[tuple[str, str]], other)
+ for key, value in other:
+ self.add(key, value)
+ elif hasattr(other, "keys") and hasattr(other, "__getitem__"):
+ # THIS IS NOT A TYPESAFE BRANCH
+ # In this branch, the object has a `keys` attr but is not a Mapping or any of
+ # the other types indicated in the method signature. We do some stuff with
+ # it as though it partially implements the Mapping interface, but we're not
+ # doing that stuff safely AT ALL.
+ for key in other.keys():
+ self.add(key, other[key])
+
+ for key, value in kwargs.items():
+ self.add(key, value)
+
+ @typing.overload
+ def getlist(self, key: str) -> list[str]: ...
+
+ @typing.overload
+ def getlist(self, key: str, default: _DT) -> list[str] | _DT: ...
+
+ def getlist(
+ self, key: str, default: _Sentinel | _DT = _Sentinel.not_passed
+ ) -> list[str] | _DT:
+ """Returns a list of all the values for the named field. Returns an
+ empty list if the key doesn't exist."""
+ if isinstance(key, bytes):
+ key = key.decode("latin-1")
+ try:
+ vals = self._container[key.lower()]
+ except KeyError:
+ if default is _Sentinel.not_passed:
+ # _DT is unbound; empty list is instance of List[str]
+ return []
+ # _DT is bound; default is instance of _DT
+ return default
+ else:
+ # _DT may or may not be bound; vals[1:] is instance of List[str], which
+ # meets our external interface requirement of `Union[List[str], _DT]`.
+ return vals[1:]
+
+ def _prepare_for_method_change(self) -> Self:
+ """
+ Remove content-specific header fields before changing the request
+ method to GET or HEAD according to RFC 9110, Section 15.4.
+ """
+ content_specific_headers = [
+ "Content-Encoding",
+ "Content-Language",
+ "Content-Location",
+ "Content-Type",
+ "Content-Length",
+ "Digest",
+ "Last-Modified",
+ ]
+ for header in content_specific_headers:
+ self.discard(header)
+ return self
+
+ # Backwards compatibility for httplib
+ getheaders = getlist
+ getallmatchingheaders = getlist
+ iget = getlist
+
+ # Backwards compatibility for http.cookiejar
+ get_all = getlist
+
+ def __repr__(self) -> str:
+ return f"{type(self).__name__}({dict(self.itermerged())})"
+
+ def _copy_from(self, other: HTTPHeaderDict) -> None:
+ for key in other:
+ val = other.getlist(key)
+ self._container[key.lower()] = [key, *val]
+
+ def copy(self) -> Self:
+ clone = type(self)()
+ clone._copy_from(self)
+ return clone
+
+ def iteritems(self) -> typing.Iterator[tuple[str, str]]:
+ """Iterate over all header lines, including duplicate ones."""
+ for key in self:
+ vals = self._container[key.lower()]
+ for val in vals[1:]:
+ yield vals[0], val
+
+ def itermerged(self) -> typing.Iterator[tuple[str, str]]:
+ """Iterate over all headers, merging duplicate ones together."""
+ for key in self:
+ val = self._container[key.lower()]
+ yield val[0], ", ".join(val[1:])
+
+ def items(self) -> HTTPHeaderDictItemView: # type: ignore[override]
+ return HTTPHeaderDictItemView(self)
+
+ def _has_value_for_header(self, header_name: str, potential_value: str) -> bool:
+ if header_name in self:
+ return potential_value in self._container[header_name.lower()][1:]
+ return False
+
+ def __ior__(self, other: object) -> HTTPHeaderDict:
+ # Supports extending a header dict in-place using operator |=
+ # combining items with add instead of __setitem__
+ maybe_constructable = ensure_can_construct_http_header_dict(other)
+ if maybe_constructable is None:
+ return NotImplemented
+ self.extend(maybe_constructable)
+ return self
+
+ def __or__(self, other: object) -> Self:
+ # Supports merging header dicts using operator |
+ # combining items with add instead of __setitem__
+ maybe_constructable = ensure_can_construct_http_header_dict(other)
+ if maybe_constructable is None:
+ return NotImplemented
+ result = self.copy()
+ result.extend(maybe_constructable)
+ return result
+
+ def __ror__(self, other: object) -> Self:
+ # Supports merging header dicts using operator | when other is on left side
+ # combining items with add instead of __setitem__
+ maybe_constructable = ensure_can_construct_http_header_dict(other)
+ if maybe_constructable is None:
+ return NotImplemented
+ result = type(self)(maybe_constructable)
+ result.extend(self)
+ return result
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/_request_methods.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/_request_methods.py
new file mode 100644
index 0000000000000000000000000000000000000000..297c271bf401c1cb48c6225f8822e78f58c3ca56
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/_request_methods.py
@@ -0,0 +1,278 @@
+from __future__ import annotations
+
+import json as _json
+import typing
+from urllib.parse import urlencode
+
+from ._base_connection import _TYPE_BODY
+from ._collections import HTTPHeaderDict
+from .filepost import _TYPE_FIELDS, encode_multipart_formdata
+from .response import BaseHTTPResponse
+
+__all__ = ["RequestMethods"]
+
+_TYPE_ENCODE_URL_FIELDS = typing.Union[
+ typing.Sequence[tuple[str, typing.Union[str, bytes]]],
+ typing.Mapping[str, typing.Union[str, bytes]],
+]
+
+
+class RequestMethods:
+ """
+ Convenience mixin for classes who implement a :meth:`urlopen` method, such
+ as :class:`urllib3.HTTPConnectionPool` and
+ :class:`urllib3.PoolManager`.
+
+ Provides behavior for making common types of HTTP request methods and
+ decides which type of request field encoding to use.
+
+ Specifically,
+
+ :meth:`.request_encode_url` is for sending requests whose fields are
+ encoded in the URL (such as GET, HEAD, DELETE).
+
+ :meth:`.request_encode_body` is for sending requests whose fields are
+ encoded in the *body* of the request using multipart or www-form-urlencoded
+ (such as for POST, PUT, PATCH).
+
+ :meth:`.request` is for making any kind of request, it will look up the
+ appropriate encoding format and use one of the above two methods to make
+ the request.
+
+ Initializer parameters:
+
+ :param headers:
+ Headers to include with all requests, unless other headers are given
+ explicitly.
+ """
+
+ _encode_url_methods = {"DELETE", "GET", "HEAD", "OPTIONS"}
+
+ def __init__(self, headers: typing.Mapping[str, str] | None = None) -> None:
+ self.headers = headers or {}
+
+ def urlopen(
+ self,
+ method: str,
+ url: str,
+ body: _TYPE_BODY | None = None,
+ headers: typing.Mapping[str, str] | None = None,
+ encode_multipart: bool = True,
+ multipart_boundary: str | None = None,
+ **kw: typing.Any,
+ ) -> BaseHTTPResponse: # Abstract
+ raise NotImplementedError(
+ "Classes extending RequestMethods must implement "
+ "their own ``urlopen`` method."
+ )
+
+ def request(
+ self,
+ method: str,
+ url: str,
+ body: _TYPE_BODY | None = None,
+ fields: _TYPE_FIELDS | None = None,
+ headers: typing.Mapping[str, str] | None = None,
+ json: typing.Any | None = None,
+ **urlopen_kw: typing.Any,
+ ) -> BaseHTTPResponse:
+ """
+ Make a request using :meth:`urlopen` with the appropriate encoding of
+ ``fields`` based on the ``method`` used.
+
+ This is a convenience method that requires the least amount of manual
+ effort. It can be used in most situations, while still having the
+ option to drop down to more specific methods when necessary, such as
+ :meth:`request_encode_url`, :meth:`request_encode_body`,
+ or even the lowest level :meth:`urlopen`.
+
+ :param method:
+ HTTP request method (such as GET, POST, PUT, etc.)
+
+ :param url:
+ The URL to perform the request on.
+
+ :param body:
+ Data to send in the request body, either :class:`str`, :class:`bytes`,
+ an iterable of :class:`str`/:class:`bytes`, or a file-like object.
+
+ :param fields:
+ Data to encode and send in the URL or request body, depending on ``method``.
+
+ :param headers:
+ Dictionary of custom headers to send, such as User-Agent,
+ If-None-Match, etc. If None, pool headers are used. If provided,
+ these headers completely replace any pool-specific headers.
+
+ :param json:
+ Data to encode and send as JSON with UTF-encoded in the request body.
+ The ``"Content-Type"`` header will be set to ``"application/json"``
+ unless specified otherwise.
+ """
+ method = method.upper()
+
+ if json is not None and body is not None:
+ raise TypeError(
+ "request got values for both 'body' and 'json' parameters which are mutually exclusive"
+ )
+
+ if json is not None:
+ if headers is None:
+ headers = self.headers
+
+ if not ("content-type" in map(str.lower, headers.keys())):
+ headers = HTTPHeaderDict(headers)
+ headers["Content-Type"] = "application/json"
+
+ body = _json.dumps(json, separators=(",", ":"), ensure_ascii=False).encode(
+ "utf-8"
+ )
+
+ if body is not None:
+ urlopen_kw["body"] = body
+
+ if method in self._encode_url_methods:
+ return self.request_encode_url(
+ method,
+ url,
+ fields=fields, # type: ignore[arg-type]
+ headers=headers,
+ **urlopen_kw,
+ )
+ else:
+ return self.request_encode_body(
+ method, url, fields=fields, headers=headers, **urlopen_kw
+ )
+
+ def request_encode_url(
+ self,
+ method: str,
+ url: str,
+ fields: _TYPE_ENCODE_URL_FIELDS | None = None,
+ headers: typing.Mapping[str, str] | None = None,
+ **urlopen_kw: str,
+ ) -> BaseHTTPResponse:
+ """
+ Make a request using :meth:`urlopen` with the ``fields`` encoded in
+ the url. This is useful for request methods like GET, HEAD, DELETE, etc.
+
+ :param method:
+ HTTP request method (such as GET, POST, PUT, etc.)
+
+ :param url:
+ The URL to perform the request on.
+
+ :param fields:
+ Data to encode and send in the URL.
+
+ :param headers:
+ Dictionary of custom headers to send, such as User-Agent,
+ If-None-Match, etc. If None, pool headers are used. If provided,
+ these headers completely replace any pool-specific headers.
+ """
+ if headers is None:
+ headers = self.headers
+
+ extra_kw: dict[str, typing.Any] = {"headers": headers}
+ extra_kw.update(urlopen_kw)
+
+ if fields:
+ url += "?" + urlencode(fields)
+
+ return self.urlopen(method, url, **extra_kw)
+
+ def request_encode_body(
+ self,
+ method: str,
+ url: str,
+ fields: _TYPE_FIELDS | None = None,
+ headers: typing.Mapping[str, str] | None = None,
+ encode_multipart: bool = True,
+ multipart_boundary: str | None = None,
+ **urlopen_kw: str,
+ ) -> BaseHTTPResponse:
+ """
+ Make a request using :meth:`urlopen` with the ``fields`` encoded in
+ the body. This is useful for request methods like POST, PUT, PATCH, etc.
+
+ When ``encode_multipart=True`` (default), then
+ :func:`urllib3.encode_multipart_formdata` is used to encode
+ the payload with the appropriate content type. Otherwise
+ :func:`urllib.parse.urlencode` is used with the
+ 'application/x-www-form-urlencoded' content type.
+
+ Multipart encoding must be used when posting files, and it's reasonably
+ safe to use it in other times too. However, it may break request
+ signing, such as with OAuth.
+
+ Supports an optional ``fields`` parameter of key/value strings AND
+ key/filetuple. A filetuple is a (filename, data, MIME type) tuple where
+ the MIME type is optional. For example::
+
+ fields = {
+ 'foo': 'bar',
+ 'fakefile': ('foofile.txt', 'contents of foofile'),
+ 'realfile': ('barfile.txt', open('realfile').read()),
+ 'typedfile': ('bazfile.bin', open('bazfile').read(),
+ 'image/jpeg'),
+ 'nonamefile': 'contents of nonamefile field',
+ }
+
+ When uploading a file, providing a filename (the first parameter of the
+ tuple) is optional but recommended to best mimic behavior of browsers.
+
+ Note that if ``headers`` are supplied, the 'Content-Type' header will
+ be overwritten because it depends on the dynamic random boundary string
+ which is used to compose the body of the request. The random boundary
+ string can be explicitly set with the ``multipart_boundary`` parameter.
+
+ :param method:
+ HTTP request method (such as GET, POST, PUT, etc.)
+
+ :param url:
+ The URL to perform the request on.
+
+ :param fields:
+ Data to encode and send in the request body.
+
+ :param headers:
+ Dictionary of custom headers to send, such as User-Agent,
+ If-None-Match, etc. If None, pool headers are used. If provided,
+ these headers completely replace any pool-specific headers.
+
+ :param encode_multipart:
+ If True, encode the ``fields`` using the multipart/form-data MIME
+ format.
+
+ :param multipart_boundary:
+ If not specified, then a random boundary will be generated using
+ :func:`urllib3.filepost.choose_boundary`.
+ """
+ if headers is None:
+ headers = self.headers
+
+ extra_kw: dict[str, typing.Any] = {"headers": HTTPHeaderDict(headers)}
+ body: bytes | str
+
+ if fields:
+ if "body" in urlopen_kw:
+ raise TypeError(
+ "request got values for both 'fields' and 'body', can only specify one."
+ )
+
+ if encode_multipart:
+ body, content_type = encode_multipart_formdata(
+ fields, boundary=multipart_boundary
+ )
+ else:
+ body, content_type = (
+ urlencode(fields), # type: ignore[arg-type]
+ "application/x-www-form-urlencoded",
+ )
+
+ extra_kw["body"] = body
+ extra_kw["headers"].setdefault("Content-Type", content_type)
+
+ extra_kw.update(urlopen_kw)
+
+ return self.urlopen(method, url, **extra_kw)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/_version.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..268d3b984dc3861ed90b8c6aa5b2763b5bcfd729
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/_version.py
@@ -0,0 +1,34 @@
+# file generated by setuptools-scm
+# don't change, don't track in version control
+
+__all__ = [
+ "__version__",
+ "__version_tuple__",
+ "version",
+ "version_tuple",
+ "__commit_id__",
+ "commit_id",
+]
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from typing import Tuple
+ from typing import Union
+
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
+ COMMIT_ID = Union[str, None]
+else:
+ VERSION_TUPLE = object
+ COMMIT_ID = object
+
+version: str
+__version__: str
+__version_tuple__: VERSION_TUPLE
+version_tuple: VERSION_TUPLE
+commit_id: COMMIT_ID
+__commit_id__: COMMIT_ID
+
+__version__ = version = '2.6.3'
+__version_tuple__ = version_tuple = (2, 6, 3)
+
+__commit_id__ = commit_id = None
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/connection.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/connection.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ceeb0a5483bef1927a57d03c3dd2cab0d8c9f8f
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/connection.py
@@ -0,0 +1,1099 @@
+from __future__ import annotations
+
+import datetime
+import http.client
+import logging
+import os
+import re
+import socket
+import sys
+import threading
+import typing
+import warnings
+from http.client import HTTPConnection as _HTTPConnection
+from http.client import HTTPException as HTTPException # noqa: F401
+from http.client import ResponseNotReady
+from socket import timeout as SocketTimeout
+
+if typing.TYPE_CHECKING:
+ from .response import HTTPResponse
+ from .util.ssl_ import _TYPE_PEER_CERT_RET_DICT
+ from .util.ssltransport import SSLTransport
+
+from ._collections import HTTPHeaderDict
+from .http2 import probe as http2_probe
+from .util.response import assert_header_parsing
+from .util.timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT, Timeout
+from .util.util import to_str
+from .util.wait import wait_for_read
+
+try: # Compiled with SSL?
+ import ssl
+
+ BaseSSLError = ssl.SSLError
+except (ImportError, AttributeError):
+ ssl = None # type: ignore[assignment]
+
+ class BaseSSLError(BaseException): # type: ignore[no-redef]
+ pass
+
+
+from ._base_connection import _TYPE_BODY
+from ._base_connection import ProxyConfig as ProxyConfig
+from ._base_connection import _ResponseOptions as _ResponseOptions
+from ._version import __version__
+from .exceptions import (
+ ConnectTimeoutError,
+ HeaderParsingError,
+ NameResolutionError,
+ NewConnectionError,
+ ProxyError,
+ SystemTimeWarning,
+)
+from .util import SKIP_HEADER, SKIPPABLE_HEADERS, connection, ssl_
+from .util.request import body_to_chunks
+from .util.ssl_ import assert_fingerprint as _assert_fingerprint
+from .util.ssl_ import (
+ create_urllib3_context,
+ is_ipaddress,
+ resolve_cert_reqs,
+ resolve_ssl_version,
+ ssl_wrap_socket,
+)
+from .util.ssl_match_hostname import CertificateError, match_hostname
+from .util.url import Url
+
+# Not a no-op, we're adding this to the namespace so it can be imported.
+ConnectionError = ConnectionError
+BrokenPipeError = BrokenPipeError
+
+
+log = logging.getLogger(__name__)
+
+port_by_scheme = {"http": 80, "https": 443}
+
+# When it comes time to update this value as a part of regular maintenance
+# (ie test_recent_date is failing) update it to ~6 months before the current date.
+RECENT_DATE = datetime.date(2025, 1, 1)
+
+_CONTAINS_CONTROL_CHAR_RE = re.compile(r"[^-!#$%&'*+.^_`|~0-9a-zA-Z]")
+
+
+class HTTPConnection(_HTTPConnection):
+ """
+ Based on :class:`http.client.HTTPConnection` but provides an extra constructor
+ backwards-compatibility layer between older and newer Pythons.
+
+ Additional keyword parameters are used to configure attributes of the connection.
+ Accepted parameters include:
+
+ - ``source_address``: Set the source address for the current connection.
+ - ``socket_options``: Set specific options on the underlying socket. If not specified, then
+ defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling
+ Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy.
+
+ For example, if you wish to enable TCP Keep Alive in addition to the defaults,
+ you might pass:
+
+ .. code-block:: python
+
+ HTTPConnection.default_socket_options + [
+ (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
+ ]
+
+ Or you may want to disable the defaults by passing an empty list (e.g., ``[]``).
+ """
+
+ default_port: typing.ClassVar[int] = port_by_scheme["http"] # type: ignore[misc]
+
+ #: Disable Nagle's algorithm by default.
+ #: ``[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]``
+ default_socket_options: typing.ClassVar[connection._TYPE_SOCKET_OPTIONS] = [
+ (socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
+ ]
+
+ #: Whether this connection verifies the host's certificate.
+ is_verified: bool = False
+
+ #: Whether this proxy connection verified the proxy host's certificate.
+ # If no proxy is currently connected to the value will be ``None``.
+ proxy_is_verified: bool | None = None
+
+ blocksize: int
+ source_address: tuple[str, int] | None
+ socket_options: connection._TYPE_SOCKET_OPTIONS | None
+
+ _has_connected_to_proxy: bool
+ _response_options: _ResponseOptions | None
+ _tunnel_host: str | None
+ _tunnel_port: int | None
+ _tunnel_scheme: str | None
+
+ def __init__(
+ self,
+ host: str,
+ port: int | None = None,
+ *,
+ timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,
+ source_address: tuple[str, int] | None = None,
+ blocksize: int = 16384,
+ socket_options: None | (
+ connection._TYPE_SOCKET_OPTIONS
+ ) = default_socket_options,
+ proxy: Url | None = None,
+ proxy_config: ProxyConfig | None = None,
+ ) -> None:
+ super().__init__(
+ host=host,
+ port=port,
+ timeout=Timeout.resolve_default_timeout(timeout),
+ source_address=source_address,
+ blocksize=blocksize,
+ )
+ self.socket_options = socket_options
+ self.proxy = proxy
+ self.proxy_config = proxy_config
+
+ self._has_connected_to_proxy = False
+ self._response_options = None
+ self._tunnel_host: str | None = None
+ self._tunnel_port: int | None = None
+ self._tunnel_scheme: str | None = None
+
+ def __str__(self) -> str:
+ return f"{type(self).__name__}(host={self.host!r}, port={self.port!r})"
+
+ def __repr__(self) -> str:
+ return f"<{self} at {id(self):#x}>"
+
+ @property
+ def host(self) -> str:
+ """
+ Getter method to remove any trailing dots that indicate the hostname is an FQDN.
+
+ In general, SSL certificates don't include the trailing dot indicating a
+ fully-qualified domain name, and thus, they don't validate properly when
+ checked against a domain name that includes the dot. In addition, some
+ servers may not expect to receive the trailing dot when provided.
+
+ However, the hostname with trailing dot is critical to DNS resolution; doing a
+ lookup with the trailing dot will properly only resolve the appropriate FQDN,
+ whereas a lookup without a trailing dot will search the system's search domain
+ list. Thus, it's important to keep the original host around for use only in
+ those cases where it's appropriate (i.e., when doing DNS lookup to establish the
+ actual TCP connection across which we're going to send HTTP requests).
+ """
+ return self._dns_host.rstrip(".")
+
+ @host.setter
+ def host(self, value: str) -> None:
+ """
+ Setter for the `host` property.
+
+ We assume that only urllib3 uses the _dns_host attribute; httplib itself
+ only uses `host`, and it seems reasonable that other libraries follow suit.
+ """
+ self._dns_host = value
+
+ def _new_conn(self) -> socket.socket:
+ """Establish a socket connection and set nodelay settings on it.
+
+ :return: New socket connection.
+ """
+ try:
+ sock = connection.create_connection(
+ (self._dns_host, self.port),
+ self.timeout,
+ source_address=self.source_address,
+ socket_options=self.socket_options,
+ )
+ except socket.gaierror as e:
+ raise NameResolutionError(self.host, self, e) from e
+ except SocketTimeout as e:
+ raise ConnectTimeoutError(
+ self,
+ f"Connection to {self.host} timed out. (connect timeout={self.timeout})",
+ ) from e
+
+ except OSError as e:
+ raise NewConnectionError(
+ self, f"Failed to establish a new connection: {e}"
+ ) from e
+
+ sys.audit("http.client.connect", self, self.host, self.port)
+
+ return sock
+
+ def set_tunnel(
+ self,
+ host: str,
+ port: int | None = None,
+ headers: typing.Mapping[str, str] | None = None,
+ scheme: str = "http",
+ ) -> None:
+ if scheme not in ("http", "https"):
+ raise ValueError(
+ f"Invalid proxy scheme for tunneling: {scheme!r}, must be either 'http' or 'https'"
+ )
+ super().set_tunnel(host, port=port, headers=headers)
+ self._tunnel_scheme = scheme
+
+ if sys.version_info < (3, 11, 9) or ((3, 12) <= sys.version_info < (3, 12, 3)):
+ # Taken from python/cpython#100986 which was backported in 3.11.9 and 3.12.3.
+ # When using connection_from_host, host will come without brackets.
+ def _wrap_ipv6(self, ip: bytes) -> bytes:
+ if b":" in ip and ip[0] != b"["[0]:
+ return b"[" + ip + b"]"
+ return ip
+
+ if sys.version_info < (3, 11, 9):
+ # `_tunnel` copied from 3.11.13 backporting
+ # https://github.com/python/cpython/commit/0d4026432591d43185568dd31cef6a034c4b9261
+ # and https://github.com/python/cpython/commit/6fbc61070fda2ffb8889e77e3b24bca4249ab4d1
+ def _tunnel(self) -> None:
+ _MAXLINE = http.client._MAXLINE # type: ignore[attr-defined]
+ connect = b"CONNECT %s:%d HTTP/1.0\r\n" % ( # type: ignore[str-format]
+ self._wrap_ipv6(self._tunnel_host.encode("ascii")), # type: ignore[union-attr]
+ self._tunnel_port,
+ )
+ headers = [connect]
+ for header, value in self._tunnel_headers.items(): # type: ignore[attr-defined]
+ headers.append(f"{header}: {value}\r\n".encode("latin-1"))
+ headers.append(b"\r\n")
+ # Making a single send() call instead of one per line encourages
+ # the host OS to use a more optimal packet size instead of
+ # potentially emitting a series of small packets.
+ self.send(b"".join(headers))
+ del headers
+
+ response = self.response_class(self.sock, method=self._method) # type: ignore[attr-defined]
+ try:
+ (version, code, message) = response._read_status() # type: ignore[attr-defined]
+
+ if code != http.HTTPStatus.OK:
+ self.close()
+ raise OSError(
+ f"Tunnel connection failed: {code} {message.strip()}"
+ )
+ while True:
+ line = response.fp.readline(_MAXLINE + 1)
+ if len(line) > _MAXLINE:
+ raise http.client.LineTooLong("header line")
+ if not line:
+ # for sites which EOF without sending a trailer
+ break
+ if line in (b"\r\n", b"\n", b""):
+ break
+
+ if self.debuglevel > 0:
+ print("header:", line.decode())
+ finally:
+ response.close()
+
+ elif (3, 12) <= sys.version_info < (3, 12, 3):
+ # `_tunnel` copied from 3.12.11 backporting
+ # https://github.com/python/cpython/commit/23aef575c7629abcd4aaf028ebd226fb41a4b3c8
+ def _tunnel(self) -> None: # noqa: F811
+ connect = b"CONNECT %s:%d HTTP/1.1\r\n" % ( # type: ignore[str-format]
+ self._wrap_ipv6(self._tunnel_host.encode("idna")), # type: ignore[union-attr]
+ self._tunnel_port,
+ )
+ headers = [connect]
+ for header, value in self._tunnel_headers.items(): # type: ignore[attr-defined]
+ headers.append(f"{header}: {value}\r\n".encode("latin-1"))
+ headers.append(b"\r\n")
+ # Making a single send() call instead of one per line encourages
+ # the host OS to use a more optimal packet size instead of
+ # potentially emitting a series of small packets.
+ self.send(b"".join(headers))
+ del headers
+
+ response = self.response_class(self.sock, method=self._method) # type: ignore[attr-defined]
+ try:
+ (version, code, message) = response._read_status() # type: ignore[attr-defined]
+
+ self._raw_proxy_headers = http.client._read_headers(response.fp) # type: ignore[attr-defined]
+
+ if self.debuglevel > 0:
+ for header in self._raw_proxy_headers:
+ print("header:", header.decode())
+
+ if code != http.HTTPStatus.OK:
+ self.close()
+ raise OSError(
+ f"Tunnel connection failed: {code} {message.strip()}"
+ )
+
+ finally:
+ response.close()
+
+ def connect(self) -> None:
+ self.sock = self._new_conn()
+ if self._tunnel_host:
+ # If we're tunneling it means we're connected to our proxy.
+ self._has_connected_to_proxy = True
+
+ # TODO: Fix tunnel so it doesn't depend on self.sock state.
+ self._tunnel()
+
+ # If there's a proxy to be connected to we are fully connected.
+ # This is set twice (once above and here) due to forwarding proxies
+ # not using tunnelling.
+ self._has_connected_to_proxy = bool(self.proxy)
+
+ if self._has_connected_to_proxy:
+ self.proxy_is_verified = False
+
+ @property
+ def is_closed(self) -> bool:
+ return self.sock is None
+
+ @property
+ def is_connected(self) -> bool:
+ if self.sock is None:
+ return False
+ return not wait_for_read(self.sock, timeout=0.0)
+
+ @property
+ def has_connected_to_proxy(self) -> bool:
+ return self._has_connected_to_proxy
+
+ @property
+ def proxy_is_forwarding(self) -> bool:
+ """
+ Return True if a forwarding proxy is configured, else return False
+ """
+ return bool(self.proxy) and self._tunnel_host is None
+
+ @property
+ def proxy_is_tunneling(self) -> bool:
+ """
+ Return True if a tunneling proxy is configured, else return False
+ """
+ return self._tunnel_host is not None
+
+ def close(self) -> None:
+ try:
+ super().close()
+ finally:
+ # Reset all stateful properties so connection
+ # can be re-used without leaking prior configs.
+ self.sock = None
+ self.is_verified = False
+ self.proxy_is_verified = None
+ self._has_connected_to_proxy = False
+ self._response_options = None
+ self._tunnel_host = None
+ self._tunnel_port = None
+ self._tunnel_scheme = None
+
+ def putrequest(
+ self,
+ method: str,
+ url: str,
+ skip_host: bool = False,
+ skip_accept_encoding: bool = False,
+ ) -> None:
+ """"""
+ # Empty docstring because the indentation of CPython's implementation
+ # is broken but we don't want this method in our documentation.
+ match = _CONTAINS_CONTROL_CHAR_RE.search(method)
+ if match:
+ raise ValueError(
+ f"Method cannot contain non-token characters {method!r} (found at least {match.group()!r})"
+ )
+
+ return super().putrequest(
+ method, url, skip_host=skip_host, skip_accept_encoding=skip_accept_encoding
+ )
+
+ def putheader(self, header: str, *values: str) -> None: # type: ignore[override]
+ """"""
+ if not any(isinstance(v, str) and v == SKIP_HEADER for v in values):
+ super().putheader(header, *values)
+ elif to_str(header.lower()) not in SKIPPABLE_HEADERS:
+ skippable_headers = "', '".join(
+ [str.title(header) for header in sorted(SKIPPABLE_HEADERS)]
+ )
+ raise ValueError(
+ f"urllib3.util.SKIP_HEADER only supports '{skippable_headers}'"
+ )
+
+ # `request` method's signature intentionally violates LSP.
+ # urllib3's API is different from `http.client.HTTPConnection` and the subclassing is only incidental.
+ def request( # type: ignore[override]
+ self,
+ method: str,
+ url: str,
+ body: _TYPE_BODY | None = None,
+ headers: typing.Mapping[str, str] | None = None,
+ *,
+ chunked: bool = False,
+ preload_content: bool = True,
+ decode_content: bool = True,
+ enforce_content_length: bool = True,
+ ) -> None:
+ # Update the inner socket's timeout value to send the request.
+ # This only triggers if the connection is re-used.
+ if self.sock is not None:
+ self.sock.settimeout(self.timeout)
+
+ # Store these values to be fed into the HTTPResponse
+ # object later. TODO: Remove this in favor of a real
+ # HTTP lifecycle mechanism.
+
+ # We have to store these before we call .request()
+ # because sometimes we can still salvage a response
+ # off the wire even if we aren't able to completely
+ # send the request body.
+ self._response_options = _ResponseOptions(
+ request_method=method,
+ request_url=url,
+ preload_content=preload_content,
+ decode_content=decode_content,
+ enforce_content_length=enforce_content_length,
+ )
+
+ if headers is None:
+ headers = {}
+ header_keys = frozenset(to_str(k.lower()) for k in headers)
+ skip_accept_encoding = "accept-encoding" in header_keys
+ skip_host = "host" in header_keys
+ self.putrequest(
+ method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host
+ )
+
+ # Transform the body into an iterable of sendall()-able chunks
+ # and detect if an explicit Content-Length is doable.
+ chunks_and_cl = body_to_chunks(body, method=method, blocksize=self.blocksize)
+ chunks = chunks_and_cl.chunks
+ content_length = chunks_and_cl.content_length
+
+ # When chunked is explicit set to 'True' we respect that.
+ if chunked:
+ if "transfer-encoding" not in header_keys:
+ self.putheader("Transfer-Encoding", "chunked")
+ else:
+ # Detect whether a framing mechanism is already in use. If so
+ # we respect that value, otherwise we pick chunked vs content-length
+ # depending on the type of 'body'.
+ if "content-length" in header_keys:
+ chunked = False
+ elif "transfer-encoding" in header_keys:
+ chunked = True
+
+ # Otherwise we go off the recommendation of 'body_to_chunks()'.
+ else:
+ chunked = False
+ if content_length is None:
+ if chunks is not None:
+ chunked = True
+ self.putheader("Transfer-Encoding", "chunked")
+ else:
+ self.putheader("Content-Length", str(content_length))
+
+ # Now that framing headers are out of the way we send all the other headers.
+ if "user-agent" not in header_keys:
+ self.putheader("User-Agent", _get_default_user_agent())
+ for header, value in headers.items():
+ self.putheader(header, value)
+ self.endheaders()
+
+ # If we're given a body we start sending that in chunks.
+ if chunks is not None:
+ for chunk in chunks:
+ # Sending empty chunks isn't allowed for TE: chunked
+ # as it indicates the end of the body.
+ if not chunk:
+ continue
+ if isinstance(chunk, str):
+ chunk = chunk.encode("utf-8")
+ if chunked:
+ self.send(b"%x\r\n%b\r\n" % (len(chunk), chunk))
+ else:
+ self.send(chunk)
+
+ # Regardless of whether we have a body or not, if we're in
+ # chunked mode we want to send an explicit empty chunk.
+ if chunked:
+ self.send(b"0\r\n\r\n")
+
+ def request_chunked(
+ self,
+ method: str,
+ url: str,
+ body: _TYPE_BODY | None = None,
+ headers: typing.Mapping[str, str] | None = None,
+ ) -> None:
+ """
+ Alternative to the common request method, which sends the
+ body with chunked encoding and not as one block
+ """
+ warnings.warn(
+ "HTTPConnection.request_chunked() is deprecated and will be removed "
+ "in urllib3 v2.1.0. Instead use HTTPConnection.request(..., chunked=True).",
+ category=DeprecationWarning,
+ stacklevel=2,
+ )
+ self.request(method, url, body=body, headers=headers, chunked=True)
+
+ def getresponse( # type: ignore[override]
+ self,
+ ) -> HTTPResponse:
+ """
+ Get the response from the server.
+
+ If the HTTPConnection is in the correct state, returns an instance of HTTPResponse or of whatever object is returned by the response_class variable.
+
+ If a request has not been sent or if a previous response has not be handled, ResponseNotReady is raised. If the HTTP response indicates that the connection should be closed, then it will be closed before the response is returned. When the connection is closed, the underlying socket is closed.
+ """
+ # Raise the same error as http.client.HTTPConnection
+ if self._response_options is None:
+ raise ResponseNotReady()
+
+ # Reset this attribute for being used again.
+ resp_options = self._response_options
+ self._response_options = None
+
+ # Since the connection's timeout value may have been updated
+ # we need to set the timeout on the socket.
+ self.sock.settimeout(self.timeout)
+
+ # This is needed here to avoid circular import errors
+ from .response import HTTPResponse
+
+ # Save a reference to the shutdown function before ownership is passed
+ # to httplib_response
+ # TODO should we implement it everywhere?
+ _shutdown = getattr(self.sock, "shutdown", None)
+
+ # Get the response from http.client.HTTPConnection
+ httplib_response = super().getresponse()
+
+ try:
+ assert_header_parsing(httplib_response.msg)
+ except (HeaderParsingError, TypeError) as hpe:
+ log.warning(
+ "Failed to parse headers (url=%s): %s",
+ _url_from_connection(self, resp_options.request_url),
+ hpe,
+ exc_info=True,
+ )
+
+ headers = HTTPHeaderDict(httplib_response.msg.items())
+
+ response = HTTPResponse(
+ body=httplib_response,
+ headers=headers,
+ status=httplib_response.status,
+ version=httplib_response.version,
+ version_string=getattr(self, "_http_vsn_str", "HTTP/?"),
+ reason=httplib_response.reason,
+ preload_content=resp_options.preload_content,
+ decode_content=resp_options.decode_content,
+ original_response=httplib_response,
+ enforce_content_length=resp_options.enforce_content_length,
+ request_method=resp_options.request_method,
+ request_url=resp_options.request_url,
+ sock_shutdown=_shutdown,
+ )
+ return response
+
+
+class HTTPSConnection(HTTPConnection):
+ """
+ Many of the parameters to this constructor are passed to the underlying SSL
+ socket by means of :py:func:`urllib3.util.ssl_wrap_socket`.
+ """
+
+ default_port = port_by_scheme["https"] # type: ignore[misc]
+
+ cert_reqs: int | str | None = None
+ ca_certs: str | None = None
+ ca_cert_dir: str | None = None
+ ca_cert_data: None | str | bytes = None
+ ssl_version: int | str | None = None
+ ssl_minimum_version: int | None = None
+ ssl_maximum_version: int | None = None
+ assert_fingerprint: str | None = None
+ _connect_callback: typing.Callable[..., None] | None = None
+
+ def __init__(
+ self,
+ host: str,
+ port: int | None = None,
+ *,
+ timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,
+ source_address: tuple[str, int] | None = None,
+ blocksize: int = 16384,
+ socket_options: None | (
+ connection._TYPE_SOCKET_OPTIONS
+ ) = HTTPConnection.default_socket_options,
+ proxy: Url | None = None,
+ proxy_config: ProxyConfig | None = None,
+ cert_reqs: int | str | None = None,
+ assert_hostname: None | str | typing.Literal[False] = None,
+ assert_fingerprint: str | None = None,
+ server_hostname: str | None = None,
+ ssl_context: ssl.SSLContext | None = None,
+ ca_certs: str | None = None,
+ ca_cert_dir: str | None = None,
+ ca_cert_data: None | str | bytes = None,
+ ssl_minimum_version: int | None = None,
+ ssl_maximum_version: int | None = None,
+ ssl_version: int | str | None = None, # Deprecated
+ cert_file: str | None = None,
+ key_file: str | None = None,
+ key_password: str | None = None,
+ ) -> None:
+ super().__init__(
+ host,
+ port=port,
+ timeout=timeout,
+ source_address=source_address,
+ blocksize=blocksize,
+ socket_options=socket_options,
+ proxy=proxy,
+ proxy_config=proxy_config,
+ )
+
+ self.key_file = key_file
+ self.cert_file = cert_file
+ self.key_password = key_password
+ self.ssl_context = ssl_context
+ self.server_hostname = server_hostname
+ self.assert_hostname = assert_hostname
+ self.assert_fingerprint = assert_fingerprint
+ self.ssl_version = ssl_version
+ self.ssl_minimum_version = ssl_minimum_version
+ self.ssl_maximum_version = ssl_maximum_version
+ self.ca_certs = ca_certs and os.path.expanduser(ca_certs)
+ self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)
+ self.ca_cert_data = ca_cert_data
+
+ # cert_reqs depends on ssl_context so calculate last.
+ if cert_reqs is None:
+ if self.ssl_context is not None:
+ cert_reqs = self.ssl_context.verify_mode
+ else:
+ cert_reqs = resolve_cert_reqs(None)
+ self.cert_reqs = cert_reqs
+ self._connect_callback = None
+
+ def set_cert(
+ self,
+ key_file: str | None = None,
+ cert_file: str | None = None,
+ cert_reqs: int | str | None = None,
+ key_password: str | None = None,
+ ca_certs: str | None = None,
+ assert_hostname: None | str | typing.Literal[False] = None,
+ assert_fingerprint: str | None = None,
+ ca_cert_dir: str | None = None,
+ ca_cert_data: None | str | bytes = None,
+ ) -> None:
+ """
+ This method should only be called once, before the connection is used.
+ """
+ warnings.warn(
+ "HTTPSConnection.set_cert() is deprecated and will be removed "
+ "in urllib3 v2.1.0. Instead provide the parameters to the "
+ "HTTPSConnection constructor.",
+ category=DeprecationWarning,
+ stacklevel=2,
+ )
+
+ # If cert_reqs is not provided we'll assume CERT_REQUIRED unless we also
+ # have an SSLContext object in which case we'll use its verify_mode.
+ if cert_reqs is None:
+ if self.ssl_context is not None:
+ cert_reqs = self.ssl_context.verify_mode
+ else:
+ cert_reqs = resolve_cert_reqs(None)
+
+ self.key_file = key_file
+ self.cert_file = cert_file
+ self.cert_reqs = cert_reqs
+ self.key_password = key_password
+ self.assert_hostname = assert_hostname
+ self.assert_fingerprint = assert_fingerprint
+ self.ca_certs = ca_certs and os.path.expanduser(ca_certs)
+ self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)
+ self.ca_cert_data = ca_cert_data
+
+ def connect(self) -> None:
+ # Today we don't need to be doing this step before the /actual/ socket
+ # connection, however in the future we'll need to decide whether to
+ # create a new socket or re-use an existing "shared" socket as a part
+ # of the HTTP/2 handshake dance.
+ if self._tunnel_host is not None and self._tunnel_port is not None:
+ probe_http2_host = self._tunnel_host
+ probe_http2_port = self._tunnel_port
+ else:
+ probe_http2_host = self.host
+ probe_http2_port = self.port
+
+ # Check if the target origin supports HTTP/2.
+ # If the value comes back as 'None' it means that the current thread
+ # is probing for HTTP/2 support. Otherwise, we're waiting for another
+ # probe to complete, or we get a value right away.
+ target_supports_http2: bool | None
+ if "h2" in ssl_.ALPN_PROTOCOLS:
+ target_supports_http2 = http2_probe.acquire_and_get(
+ host=probe_http2_host, port=probe_http2_port
+ )
+ else:
+ # If HTTP/2 isn't going to be offered it doesn't matter if
+ # the target supports HTTP/2. Don't want to make a probe.
+ target_supports_http2 = False
+
+ if self._connect_callback is not None:
+ self._connect_callback(
+ "before connect",
+ thread_id=threading.get_ident(),
+ target_supports_http2=target_supports_http2,
+ )
+
+ try:
+ sock: socket.socket | ssl.SSLSocket
+ self.sock = sock = self._new_conn()
+ server_hostname: str = self.host
+ tls_in_tls = False
+
+ # Do we need to establish a tunnel?
+ if self.proxy_is_tunneling:
+ # We're tunneling to an HTTPS origin so need to do TLS-in-TLS.
+ if self._tunnel_scheme == "https":
+ # _connect_tls_proxy will verify and assign proxy_is_verified
+ self.sock = sock = self._connect_tls_proxy(self.host, sock)
+ tls_in_tls = True
+ elif self._tunnel_scheme == "http":
+ self.proxy_is_verified = False
+
+ # If we're tunneling it means we're connected to our proxy.
+ self._has_connected_to_proxy = True
+
+ self._tunnel()
+ # Override the host with the one we're requesting data from.
+ server_hostname = typing.cast(str, self._tunnel_host)
+
+ if self.server_hostname is not None:
+ server_hostname = self.server_hostname
+
+ is_time_off = datetime.date.today() < RECENT_DATE
+ if is_time_off:
+ warnings.warn(
+ (
+ f"System time is way off (before {RECENT_DATE}). This will probably "
+ "lead to SSL verification errors"
+ ),
+ SystemTimeWarning,
+ )
+
+ # Remove trailing '.' from fqdn hostnames to allow certificate validation
+ server_hostname_rm_dot = server_hostname.rstrip(".")
+
+ sock_and_verified = _ssl_wrap_socket_and_match_hostname(
+ sock=sock,
+ cert_reqs=self.cert_reqs,
+ ssl_version=self.ssl_version,
+ ssl_minimum_version=self.ssl_minimum_version,
+ ssl_maximum_version=self.ssl_maximum_version,
+ ca_certs=self.ca_certs,
+ ca_cert_dir=self.ca_cert_dir,
+ ca_cert_data=self.ca_cert_data,
+ cert_file=self.cert_file,
+ key_file=self.key_file,
+ key_password=self.key_password,
+ server_hostname=server_hostname_rm_dot,
+ ssl_context=self.ssl_context,
+ tls_in_tls=tls_in_tls,
+ assert_hostname=self.assert_hostname,
+ assert_fingerprint=self.assert_fingerprint,
+ )
+ self.sock = sock_and_verified.socket
+
+ # If an error occurs during connection/handshake we may need to release
+ # our lock so another connection can probe the origin.
+ except BaseException:
+ if self._connect_callback is not None:
+ self._connect_callback(
+ "after connect failure",
+ thread_id=threading.get_ident(),
+ target_supports_http2=target_supports_http2,
+ )
+
+ if target_supports_http2 is None:
+ http2_probe.set_and_release(
+ host=probe_http2_host, port=probe_http2_port, supports_http2=None
+ )
+ raise
+
+ # If this connection doesn't know if the origin supports HTTP/2
+ # we report back to the HTTP/2 probe our result.
+ if target_supports_http2 is None:
+ supports_http2 = sock_and_verified.socket.selected_alpn_protocol() == "h2"
+ http2_probe.set_and_release(
+ host=probe_http2_host,
+ port=probe_http2_port,
+ supports_http2=supports_http2,
+ )
+
+ # Forwarding proxies can never have a verified target since
+ # the proxy is the one doing the verification. Should instead
+ # use a CONNECT tunnel in order to verify the target.
+ # See: https://github.com/urllib3/urllib3/issues/3267.
+ if self.proxy_is_forwarding:
+ self.is_verified = False
+ else:
+ self.is_verified = sock_and_verified.is_verified
+
+ # If there's a proxy to be connected to we are fully connected.
+ # This is set twice (once above and here) due to forwarding proxies
+ # not using tunnelling.
+ self._has_connected_to_proxy = bool(self.proxy)
+
+ # Set `self.proxy_is_verified` unless it's already set while
+ # establishing a tunnel.
+ if self._has_connected_to_proxy and self.proxy_is_verified is None:
+ self.proxy_is_verified = sock_and_verified.is_verified
+
+ def _connect_tls_proxy(self, hostname: str, sock: socket.socket) -> ssl.SSLSocket:
+ """
+ Establish a TLS connection to the proxy using the provided SSL context.
+ """
+ # `_connect_tls_proxy` is called when self._tunnel_host is truthy.
+ proxy_config = typing.cast(ProxyConfig, self.proxy_config)
+ ssl_context = proxy_config.ssl_context
+ sock_and_verified = _ssl_wrap_socket_and_match_hostname(
+ sock,
+ cert_reqs=self.cert_reqs,
+ ssl_version=self.ssl_version,
+ ssl_minimum_version=self.ssl_minimum_version,
+ ssl_maximum_version=self.ssl_maximum_version,
+ ca_certs=self.ca_certs,
+ ca_cert_dir=self.ca_cert_dir,
+ ca_cert_data=self.ca_cert_data,
+ server_hostname=hostname,
+ ssl_context=ssl_context,
+ assert_hostname=proxy_config.assert_hostname,
+ assert_fingerprint=proxy_config.assert_fingerprint,
+ # Features that aren't implemented for proxies yet:
+ cert_file=None,
+ key_file=None,
+ key_password=None,
+ tls_in_tls=False,
+ )
+ self.proxy_is_verified = sock_and_verified.is_verified
+ return sock_and_verified.socket # type: ignore[return-value]
+
+
+class _WrappedAndVerifiedSocket(typing.NamedTuple):
+ """
+ Wrapped socket and whether the connection is
+ verified after the TLS handshake
+ """
+
+ socket: ssl.SSLSocket | SSLTransport
+ is_verified: bool
+
+
+def _ssl_wrap_socket_and_match_hostname(
+ sock: socket.socket,
+ *,
+ cert_reqs: None | str | int,
+ ssl_version: None | str | int,
+ ssl_minimum_version: int | None,
+ ssl_maximum_version: int | None,
+ cert_file: str | None,
+ key_file: str | None,
+ key_password: str | None,
+ ca_certs: str | None,
+ ca_cert_dir: str | None,
+ ca_cert_data: None | str | bytes,
+ assert_hostname: None | str | typing.Literal[False],
+ assert_fingerprint: str | None,
+ server_hostname: str | None,
+ ssl_context: ssl.SSLContext | None,
+ tls_in_tls: bool = False,
+) -> _WrappedAndVerifiedSocket:
+ """Logic for constructing an SSLContext from all TLS parameters, passing
+ that down into ssl_wrap_socket, and then doing certificate verification
+ either via hostname or fingerprint. This function exists to guarantee
+ that both proxies and targets have the same behavior when connecting via TLS.
+ """
+ default_ssl_context = False
+ if ssl_context is None:
+ default_ssl_context = True
+ context = create_urllib3_context(
+ ssl_version=resolve_ssl_version(ssl_version),
+ ssl_minimum_version=ssl_minimum_version,
+ ssl_maximum_version=ssl_maximum_version,
+ cert_reqs=resolve_cert_reqs(cert_reqs),
+ )
+ else:
+ context = ssl_context
+
+ context.verify_mode = resolve_cert_reqs(cert_reqs)
+
+ # In some cases, we want to verify hostnames ourselves
+ if (
+ # `ssl` can't verify fingerprints or alternate hostnames
+ assert_fingerprint
+ or assert_hostname
+ # assert_hostname can be set to False to disable hostname checking
+ or assert_hostname is False
+ # We still support OpenSSL 1.0.2, which prevents us from verifying
+ # hostnames easily: https://github.com/pyca/pyopenssl/pull/933
+ or ssl_.IS_PYOPENSSL
+ or not ssl_.HAS_NEVER_CHECK_COMMON_NAME
+ ):
+ context.check_hostname = False
+
+ # Try to load OS default certs if none are given. We need to do the hasattr() check
+ # for custom pyOpenSSL SSLContext objects because they don't support
+ # load_default_certs().
+ if (
+ not ca_certs
+ and not ca_cert_dir
+ and not ca_cert_data
+ and default_ssl_context
+ and hasattr(context, "load_default_certs")
+ ):
+ context.load_default_certs()
+
+ # Ensure that IPv6 addresses are in the proper format and don't have a
+ # scope ID. Python's SSL module fails to recognize scoped IPv6 addresses
+ # and interprets them as DNS hostnames.
+ if server_hostname is not None:
+ normalized = server_hostname.strip("[]")
+ if "%" in normalized:
+ normalized = normalized[: normalized.rfind("%")]
+ if is_ipaddress(normalized):
+ server_hostname = normalized
+
+ ssl_sock = ssl_wrap_socket(
+ sock=sock,
+ keyfile=key_file,
+ certfile=cert_file,
+ key_password=key_password,
+ ca_certs=ca_certs,
+ ca_cert_dir=ca_cert_dir,
+ ca_cert_data=ca_cert_data,
+ server_hostname=server_hostname,
+ ssl_context=context,
+ tls_in_tls=tls_in_tls,
+ )
+
+ try:
+ if assert_fingerprint:
+ _assert_fingerprint(
+ ssl_sock.getpeercert(binary_form=True), assert_fingerprint
+ )
+ elif (
+ context.verify_mode != ssl.CERT_NONE
+ and not context.check_hostname
+ and assert_hostname is not False
+ ):
+ cert: _TYPE_PEER_CERT_RET_DICT = ssl_sock.getpeercert() # type: ignore[assignment]
+
+ # Need to signal to our match_hostname whether to use 'commonName' or not.
+ # If we're using our own constructed SSLContext we explicitly set 'False'
+ # because PyPy hard-codes 'True' from SSLContext.hostname_checks_common_name.
+ if default_ssl_context:
+ hostname_checks_common_name = False
+ else:
+ hostname_checks_common_name = (
+ getattr(context, "hostname_checks_common_name", False) or False
+ )
+
+ _match_hostname(
+ cert,
+ assert_hostname or server_hostname, # type: ignore[arg-type]
+ hostname_checks_common_name,
+ )
+
+ return _WrappedAndVerifiedSocket(
+ socket=ssl_sock,
+ is_verified=context.verify_mode == ssl.CERT_REQUIRED
+ or bool(assert_fingerprint),
+ )
+ except BaseException:
+ ssl_sock.close()
+ raise
+
+
+def _match_hostname(
+ cert: _TYPE_PEER_CERT_RET_DICT | None,
+ asserted_hostname: str,
+ hostname_checks_common_name: bool = False,
+) -> None:
+ # Our upstream implementation of ssl.match_hostname()
+ # only applies this normalization to IP addresses so it doesn't
+ # match DNS SANs so we do the same thing!
+ stripped_hostname = asserted_hostname.strip("[]")
+ if is_ipaddress(stripped_hostname):
+ asserted_hostname = stripped_hostname
+
+ try:
+ match_hostname(cert, asserted_hostname, hostname_checks_common_name)
+ except CertificateError as e:
+ log.warning(
+ "Certificate did not match expected hostname: %s. Certificate: %s",
+ asserted_hostname,
+ cert,
+ )
+ # Add cert to exception and reraise so client code can inspect
+ # the cert when catching the exception, if they want to
+ e._peer_cert = cert # type: ignore[attr-defined]
+ raise
+
+
+def _wrap_proxy_error(err: Exception, proxy_scheme: str | None) -> ProxyError:
+ # Look for the phrase 'wrong version number', if found
+ # then we should warn the user that we're very sure that
+ # this proxy is HTTP-only and they have a configuration issue.
+ error_normalized = " ".join(re.split("[^a-z]", str(err).lower()))
+ is_likely_http_proxy = (
+ "wrong version number" in error_normalized
+ or "unknown protocol" in error_normalized
+ or "record layer failure" in error_normalized
+ )
+ http_proxy_warning = (
+ ". Your proxy appears to only use HTTP and not HTTPS, "
+ "try changing your proxy URL to be HTTP. See: "
+ "https://urllib3.readthedocs.io/en/latest/advanced-usage.html"
+ "#https-proxy-error-http-proxy"
+ )
+ new_err = ProxyError(
+ f"Unable to connect to proxy"
+ f"{http_proxy_warning if is_likely_http_proxy and proxy_scheme == 'https' else ''}",
+ err,
+ )
+ new_err.__cause__ = err
+ return new_err
+
+
+def _get_default_user_agent() -> str:
+ return f"python-urllib3/{__version__}"
+
+
+class DummyConnection:
+ """Used to detect a failed ConnectionCls import."""
+
+
+if not ssl:
+ HTTPSConnection = DummyConnection # type: ignore[misc, assignment] # noqa: F811
+
+
+VerifiedHTTPSConnection = HTTPSConnection
+
+
+def _url_from_connection(
+ conn: HTTPConnection | HTTPSConnection, path: str | None = None
+) -> str:
+ """Returns the URL from a given connection. This is mainly used for testing and logging."""
+
+ scheme = "https" if isinstance(conn, HTTPSConnection) else "http"
+
+ return Url(scheme=scheme, host=conn.host, port=conn.port, path=path).url
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/connectionpool.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/connectionpool.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a0685b4cdd0562e508b9dd032765b5c759ea61e
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/connectionpool.py
@@ -0,0 +1,1178 @@
+from __future__ import annotations
+
+import errno
+import logging
+import queue
+import sys
+import typing
+import warnings
+import weakref
+from socket import timeout as SocketTimeout
+from types import TracebackType
+
+from ._base_connection import _TYPE_BODY
+from ._collections import HTTPHeaderDict
+from ._request_methods import RequestMethods
+from .connection import (
+ BaseSSLError,
+ BrokenPipeError,
+ DummyConnection,
+ HTTPConnection,
+ HTTPException,
+ HTTPSConnection,
+ ProxyConfig,
+ _wrap_proxy_error,
+)
+from .connection import port_by_scheme as port_by_scheme
+from .exceptions import (
+ ClosedPoolError,
+ EmptyPoolError,
+ FullPoolError,
+ HostChangedError,
+ InsecureRequestWarning,
+ LocationValueError,
+ MaxRetryError,
+ NewConnectionError,
+ ProtocolError,
+ ProxyError,
+ ReadTimeoutError,
+ SSLError,
+ TimeoutError,
+)
+from .response import BaseHTTPResponse
+from .util.connection import is_connection_dropped
+from .util.proxy import connection_requires_http_tunnel
+from .util.request import _TYPE_BODY_POSITION, set_file_position
+from .util.retry import Retry
+from .util.ssl_match_hostname import CertificateError
+from .util.timeout import _DEFAULT_TIMEOUT, _TYPE_DEFAULT, Timeout
+from .util.url import Url, _encode_target
+from .util.url import _normalize_host as normalize_host
+from .util.url import parse_url
+from .util.util import to_str
+
+if typing.TYPE_CHECKING:
+ import ssl
+
+ from typing_extensions import Self
+
+ from ._base_connection import BaseHTTPConnection, BaseHTTPSConnection
+
+log = logging.getLogger(__name__)
+
+_TYPE_TIMEOUT = typing.Union[Timeout, float, _TYPE_DEFAULT, None]
+
+
+# Pool objects
+class ConnectionPool:
+ """
+ Base class for all connection pools, such as
+ :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.
+
+ .. note::
+ ConnectionPool.urlopen() does not normalize or percent-encode target URIs
+ which is useful if your target server doesn't support percent-encoded
+ target URIs.
+ """
+
+ scheme: str | None = None
+ QueueCls = queue.LifoQueue
+
+ def __init__(self, host: str, port: int | None = None) -> None:
+ if not host:
+ raise LocationValueError("No host specified.")
+
+ self.host = _normalize_host(host, scheme=self.scheme)
+ self.port = port
+
+ # This property uses 'normalize_host()' (not '_normalize_host()')
+ # to avoid removing square braces around IPv6 addresses.
+ # This value is sent to `HTTPConnection.set_tunnel()` if called
+ # because square braces are required for HTTP CONNECT tunneling.
+ self._tunnel_host = normalize_host(host, scheme=self.scheme).lower()
+
+ def __str__(self) -> str:
+ return f"{type(self).__name__}(host={self.host!r}, port={self.port!r})"
+
+ def __enter__(self) -> Self:
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: TracebackType | None,
+ ) -> typing.Literal[False]:
+ self.close()
+ # Return False to re-raise any potential exceptions
+ return False
+
+ def close(self) -> None:
+ """
+ Close all pooled connections and disable the pool.
+ """
+
+
+# This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l252
+_blocking_errnos = {errno.EAGAIN, errno.EWOULDBLOCK}
+
+
+class HTTPConnectionPool(ConnectionPool, RequestMethods):
+ """
+ Thread-safe connection pool for one host.
+
+ :param host:
+ Host used for this HTTP Connection (e.g. "localhost"), passed into
+ :class:`http.client.HTTPConnection`.
+
+ :param port:
+ Port used for this HTTP Connection (None is equivalent to 80), passed
+ into :class:`http.client.HTTPConnection`.
+
+ :param timeout:
+ Socket timeout in seconds for each individual connection. This can
+ be a float or integer, which sets the timeout for the HTTP request,
+ or an instance of :class:`urllib3.util.Timeout` which gives you more
+ fine-grained control over request timeouts. After the constructor has
+ been parsed, this is always a `urllib3.util.Timeout` object.
+
+ :param maxsize:
+ Number of connections to save that can be reused. More than 1 is useful
+ in multithreaded situations. If ``block`` is set to False, more
+ connections will be created but they will not be saved once they've
+ been used.
+
+ :param block:
+ If set to True, no more than ``maxsize`` connections will be used at
+ a time. When no free connections are available, the call will block
+ until a connection has been released. This is a useful side effect for
+ particular multithreaded situations where one does not want to use more
+ than maxsize connections per host to prevent flooding.
+
+ :param headers:
+ Headers to include with all requests, unless other headers are given
+ explicitly.
+
+ :param retries:
+ Retry configuration to use by default with requests in this pool.
+
+ :param _proxy:
+ Parsed proxy URL, should not be used directly, instead, see
+ :class:`urllib3.ProxyManager`
+
+ :param _proxy_headers:
+ A dictionary with proxy headers, should not be used directly,
+ instead, see :class:`urllib3.ProxyManager`
+
+ :param \\**conn_kw:
+ Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`,
+ :class:`urllib3.connection.HTTPSConnection` instances.
+ """
+
+ scheme = "http"
+ ConnectionCls: type[BaseHTTPConnection] | type[BaseHTTPSConnection] = HTTPConnection
+
+ def __init__(
+ self,
+ host: str,
+ port: int | None = None,
+ timeout: _TYPE_TIMEOUT | None = _DEFAULT_TIMEOUT,
+ maxsize: int = 1,
+ block: bool = False,
+ headers: typing.Mapping[str, str] | None = None,
+ retries: Retry | bool | int | None = None,
+ _proxy: Url | None = None,
+ _proxy_headers: typing.Mapping[str, str] | None = None,
+ _proxy_config: ProxyConfig | None = None,
+ **conn_kw: typing.Any,
+ ):
+ ConnectionPool.__init__(self, host, port)
+ RequestMethods.__init__(self, headers)
+
+ if not isinstance(timeout, Timeout):
+ timeout = Timeout.from_float(timeout)
+
+ if retries is None:
+ retries = Retry.DEFAULT
+
+ self.timeout = timeout
+ self.retries = retries
+
+ self.pool: queue.LifoQueue[typing.Any] | None = self.QueueCls(maxsize)
+ self.block = block
+
+ self.proxy = _proxy
+ self.proxy_headers = _proxy_headers or {}
+ self.proxy_config = _proxy_config
+
+ # Fill the queue up so that doing get() on it will block properly
+ for _ in range(maxsize):
+ self.pool.put(None)
+
+ # These are mostly for testing and debugging purposes.
+ self.num_connections = 0
+ self.num_requests = 0
+ self.conn_kw = conn_kw
+
+ if self.proxy:
+ # Enable Nagle's algorithm for proxies, to avoid packet fragmentation.
+ # We cannot know if the user has added default socket options, so we cannot replace the
+ # list.
+ self.conn_kw.setdefault("socket_options", [])
+
+ self.conn_kw["proxy"] = self.proxy
+ self.conn_kw["proxy_config"] = self.proxy_config
+
+ # Do not pass 'self' as callback to 'finalize'.
+ # Then the 'finalize' would keep an endless living (leak) to self.
+ # By just passing a reference to the pool allows the garbage collector
+ # to free self if nobody else has a reference to it.
+ pool = self.pool
+
+ # Close all the HTTPConnections in the pool before the
+ # HTTPConnectionPool object is garbage collected.
+ weakref.finalize(self, _close_pool_connections, pool)
+
+ def _new_conn(self) -> BaseHTTPConnection:
+ """
+ Return a fresh :class:`HTTPConnection`.
+ """
+ self.num_connections += 1
+ log.debug(
+ "Starting new HTTP connection (%d): %s:%s",
+ self.num_connections,
+ self.host,
+ self.port or "80",
+ )
+
+ conn = self.ConnectionCls(
+ host=self.host,
+ port=self.port,
+ timeout=self.timeout.connect_timeout,
+ **self.conn_kw,
+ )
+ return conn
+
+ def _get_conn(self, timeout: float | None = None) -> BaseHTTPConnection:
+ """
+ Get a connection. Will return a pooled connection if one is available.
+
+ If no connections are available and :prop:`.block` is ``False``, then a
+ fresh connection is returned.
+
+ :param timeout:
+ Seconds to wait before giving up and raising
+ :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and
+ :prop:`.block` is ``True``.
+ """
+ conn = None
+
+ if self.pool is None:
+ raise ClosedPoolError(self, "Pool is closed.")
+
+ try:
+ conn = self.pool.get(block=self.block, timeout=timeout)
+
+ except AttributeError: # self.pool is None
+ raise ClosedPoolError(self, "Pool is closed.") from None # Defensive:
+
+ except queue.Empty:
+ if self.block:
+ raise EmptyPoolError(
+ self,
+ "Pool is empty and a new connection can't be opened due to blocking mode.",
+ ) from None
+ pass # Oh well, we'll create a new connection then
+
+ # If this is a persistent connection, check if it got disconnected
+ if conn and is_connection_dropped(conn):
+ log.debug("Resetting dropped connection: %s", self.host)
+ conn.close()
+
+ return conn or self._new_conn()
+
+ def _put_conn(self, conn: BaseHTTPConnection | None) -> None:
+ """
+ Put a connection back into the pool.
+
+ :param conn:
+ Connection object for the current host and port as returned by
+ :meth:`._new_conn` or :meth:`._get_conn`.
+
+ If the pool is already full, the connection is closed and discarded
+ because we exceeded maxsize. If connections are discarded frequently,
+ then maxsize should be increased.
+
+ If the pool is closed, then the connection will be closed and discarded.
+ """
+ if self.pool is not None:
+ try:
+ self.pool.put(conn, block=False)
+ return # Everything is dandy, done.
+ except AttributeError:
+ # self.pool is None.
+ pass
+ except queue.Full:
+ # Connection never got put back into the pool, close it.
+ if conn:
+ conn.close()
+
+ if self.block:
+ # This should never happen if you got the conn from self._get_conn
+ raise FullPoolError(
+ self,
+ "Pool reached maximum size and no more connections are allowed.",
+ ) from None
+
+ log.warning(
+ "Connection pool is full, discarding connection: %s. Connection pool size: %s",
+ self.host,
+ self.pool.qsize(),
+ )
+
+ # Connection never got put back into the pool, close it.
+ if conn:
+ conn.close()
+
+ def _validate_conn(self, conn: BaseHTTPConnection) -> None:
+ """
+ Called right before a request is made, after the socket is created.
+ """
+
+ def _prepare_proxy(self, conn: BaseHTTPConnection) -> None:
+ # Nothing to do for HTTP connections.
+ pass
+
+ def _get_timeout(self, timeout: _TYPE_TIMEOUT) -> Timeout:
+ """Helper that always returns a :class:`urllib3.util.Timeout`"""
+ if timeout is _DEFAULT_TIMEOUT:
+ return self.timeout.clone()
+
+ if isinstance(timeout, Timeout):
+ return timeout.clone()
+ else:
+ # User passed us an int/float. This is for backwards compatibility,
+ # can be removed later
+ return Timeout.from_float(timeout)
+
+ def _raise_timeout(
+ self,
+ err: BaseSSLError | OSError | SocketTimeout,
+ url: str,
+ timeout_value: _TYPE_TIMEOUT | None,
+ ) -> None:
+ """Is the error actually a timeout? Will raise a ReadTimeout or pass"""
+
+ if isinstance(err, SocketTimeout):
+ raise ReadTimeoutError(
+ self, url, f"Read timed out. (read timeout={timeout_value})"
+ ) from err
+
+ # See the above comment about EAGAIN in Python 3.
+ if hasattr(err, "errno") and err.errno in _blocking_errnos:
+ raise ReadTimeoutError(
+ self, url, f"Read timed out. (read timeout={timeout_value})"
+ ) from err
+
+ def _make_request(
+ self,
+ conn: BaseHTTPConnection,
+ method: str,
+ url: str,
+ body: _TYPE_BODY | None = None,
+ headers: typing.Mapping[str, str] | None = None,
+ retries: Retry | None = None,
+ timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,
+ chunked: bool = False,
+ response_conn: BaseHTTPConnection | None = None,
+ preload_content: bool = True,
+ decode_content: bool = True,
+ enforce_content_length: bool = True,
+ ) -> BaseHTTPResponse:
+ """
+ Perform a request on a given urllib connection object taken from our
+ pool.
+
+ :param conn:
+ a connection from one of our connection pools
+
+ :param method:
+ HTTP request method (such as GET, POST, PUT, etc.)
+
+ :param url:
+ The URL to perform the request on.
+
+ :param body:
+ Data to send in the request body, either :class:`str`, :class:`bytes`,
+ an iterable of :class:`str`/:class:`bytes`, or a file-like object.
+
+ :param headers:
+ Dictionary of custom headers to send, such as User-Agent,
+ If-None-Match, etc. If None, pool headers are used. If provided,
+ these headers completely replace any pool-specific headers.
+
+ :param retries:
+ Configure the number of retries to allow before raising a
+ :class:`~urllib3.exceptions.MaxRetryError` exception.
+
+ Pass ``None`` to retry until you receive a response. Pass a
+ :class:`~urllib3.util.retry.Retry` object for fine-grained control
+ over different types of retries.
+ Pass an integer number to retry connection errors that many times,
+ but no other types of errors. Pass zero to never retry.
+
+ If ``False``, then retries are disabled and any exception is raised
+ immediately. Also, instead of raising a MaxRetryError on redirects,
+ the redirect response will be returned.
+
+ :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int.
+
+ :param timeout:
+ If specified, overrides the default timeout for this one
+ request. It may be a float (in seconds) or an instance of
+ :class:`urllib3.util.Timeout`.
+
+ :param chunked:
+ If True, urllib3 will send the body using chunked transfer
+ encoding. Otherwise, urllib3 will send the body using the standard
+ content-length form. Defaults to False.
+
+ :param response_conn:
+ Set this to ``None`` if you will handle releasing the connection or
+ set the connection to have the response release it.
+
+ :param preload_content:
+ If True, the response's body will be preloaded during construction.
+
+ :param decode_content:
+ If True, will attempt to decode the body based on the
+ 'content-encoding' header.
+
+ :param enforce_content_length:
+ Enforce content length checking. Body returned by server must match
+ value of Content-Length header, if present. Otherwise, raise error.
+ """
+ self.num_requests += 1
+
+ timeout_obj = self._get_timeout(timeout)
+ timeout_obj.start_connect()
+ conn.timeout = Timeout.resolve_default_timeout(timeout_obj.connect_timeout)
+
+ try:
+ # Trigger any extra validation we need to do.
+ try:
+ self._validate_conn(conn)
+ except (SocketTimeout, BaseSSLError) as e:
+ self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
+ raise
+
+ # _validate_conn() starts the connection to an HTTPS proxy
+ # so we need to wrap errors with 'ProxyError' here too.
+ except (
+ OSError,
+ NewConnectionError,
+ TimeoutError,
+ BaseSSLError,
+ CertificateError,
+ SSLError,
+ ) as e:
+ new_e: Exception = e
+ if isinstance(e, (BaseSSLError, CertificateError)):
+ new_e = SSLError(e)
+ # If the connection didn't successfully connect to it's proxy
+ # then there
+ if isinstance(
+ new_e, (OSError, NewConnectionError, TimeoutError, SSLError)
+ ) and (conn and conn.proxy and not conn.has_connected_to_proxy):
+ new_e = _wrap_proxy_error(new_e, conn.proxy.scheme)
+ raise new_e
+
+ # conn.request() calls http.client.*.request, not the method in
+ # urllib3.request. It also calls makefile (recv) on the socket.
+ try:
+ conn.request(
+ method,
+ url,
+ body=body,
+ headers=headers,
+ chunked=chunked,
+ preload_content=preload_content,
+ decode_content=decode_content,
+ enforce_content_length=enforce_content_length,
+ )
+
+ # We are swallowing BrokenPipeError (errno.EPIPE) since the server is
+ # legitimately able to close the connection after sending a valid response.
+ # With this behaviour, the received response is still readable.
+ except BrokenPipeError:
+ pass
+ except OSError as e:
+ # MacOS/Linux
+ # EPROTOTYPE and ECONNRESET are needed on macOS
+ # https://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/
+ # Condition changed later to emit ECONNRESET instead of only EPROTOTYPE.
+ if e.errno != errno.EPROTOTYPE and e.errno != errno.ECONNRESET:
+ raise
+
+ # Reset the timeout for the recv() on the socket
+ read_timeout = timeout_obj.read_timeout
+
+ if not conn.is_closed:
+ # In Python 3 socket.py will catch EAGAIN and return None when you
+ # try and read into the file pointer created by http.client, which
+ # instead raises a BadStatusLine exception. Instead of catching
+ # the exception and assuming all BadStatusLine exceptions are read
+ # timeouts, check for a zero timeout before making the request.
+ if read_timeout == 0:
+ raise ReadTimeoutError(
+ self, url, f"Read timed out. (read timeout={read_timeout})"
+ )
+ conn.timeout = read_timeout
+
+ # Receive the response from the server
+ try:
+ response = conn.getresponse()
+ except (BaseSSLError, OSError) as e:
+ self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
+ raise
+
+ # Set properties that are used by the pooling layer.
+ response.retries = retries
+ response._connection = response_conn # type: ignore[attr-defined]
+ response._pool = self # type: ignore[attr-defined]
+
+ log.debug(
+ '%s://%s:%s "%s %s %s" %s %s',
+ self.scheme,
+ self.host,
+ self.port,
+ method,
+ url,
+ response.version_string,
+ response.status,
+ response.length_remaining,
+ )
+
+ return response
+
+ def close(self) -> None:
+ """
+ Close all pooled connections and disable the pool.
+ """
+ if self.pool is None:
+ return
+ # Disable access to the pool
+ old_pool, self.pool = self.pool, None
+
+ # Close all the HTTPConnections in the pool.
+ _close_pool_connections(old_pool)
+
+ def is_same_host(self, url: str) -> bool:
+ """
+ Check if the given ``url`` is a member of the same host as this
+ connection pool.
+ """
+ if url.startswith("/"):
+ return True
+
+ # TODO: Add optional support for socket.gethostbyname checking.
+ scheme, _, host, port, *_ = parse_url(url)
+ scheme = scheme or "http"
+ if host is not None:
+ host = _normalize_host(host, scheme=scheme)
+
+ # Use explicit default port for comparison when none is given
+ if self.port and not port:
+ port = port_by_scheme.get(scheme)
+ elif not self.port and port == port_by_scheme.get(scheme):
+ port = None
+
+ return (scheme, host, port) == (self.scheme, self.host, self.port)
+
+ def urlopen( # type: ignore[override]
+ self,
+ method: str,
+ url: str,
+ body: _TYPE_BODY | None = None,
+ headers: typing.Mapping[str, str] | None = None,
+ retries: Retry | bool | int | None = None,
+ redirect: bool = True,
+ assert_same_host: bool = True,
+ timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,
+ pool_timeout: int | None = None,
+ release_conn: bool | None = None,
+ chunked: bool = False,
+ body_pos: _TYPE_BODY_POSITION | None = None,
+ preload_content: bool = True,
+ decode_content: bool = True,
+ **response_kw: typing.Any,
+ ) -> BaseHTTPResponse:
+ """
+ Get a connection from the pool and perform an HTTP request. This is the
+ lowest level call for making a request, so you'll need to specify all
+ the raw details.
+
+ .. note::
+
+ More commonly, it's appropriate to use a convenience method
+ such as :meth:`request`.
+
+ .. note::
+
+ `release_conn` will only behave as expected if
+ `preload_content=False` because we want to make
+ `preload_content=False` the default behaviour someday soon without
+ breaking backwards compatibility.
+
+ :param method:
+ HTTP request method (such as GET, POST, PUT, etc.)
+
+ :param url:
+ The URL to perform the request on.
+
+ :param body:
+ Data to send in the request body, either :class:`str`, :class:`bytes`,
+ an iterable of :class:`str`/:class:`bytes`, or a file-like object.
+
+ :param headers:
+ Dictionary of custom headers to send, such as User-Agent,
+ If-None-Match, etc. If None, pool headers are used. If provided,
+ these headers completely replace any pool-specific headers.
+
+ :param retries:
+ Configure the number of retries to allow before raising a
+ :class:`~urllib3.exceptions.MaxRetryError` exception.
+
+ If ``None`` (default) will retry 3 times, see ``Retry.DEFAULT``. Pass a
+ :class:`~urllib3.util.retry.Retry` object for fine-grained control
+ over different types of retries.
+ Pass an integer number to retry connection errors that many times,
+ but no other types of errors. Pass zero to never retry.
+
+ If ``False``, then retries are disabled and any exception is raised
+ immediately. Also, instead of raising a MaxRetryError on redirects,
+ the redirect response will be returned.
+
+ :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int.
+
+ :param redirect:
+ If True, automatically handle redirects (status codes 301, 302,
+ 303, 307, 308). Each redirect counts as a retry. Disabling retries
+ will disable redirect, too.
+
+ :param assert_same_host:
+ If ``True``, will make sure that the host of the pool requests is
+ consistent else will raise HostChangedError. When ``False``, you can
+ use the pool on an HTTP proxy and request foreign hosts.
+
+ :param timeout:
+ If specified, overrides the default timeout for this one
+ request. It may be a float (in seconds) or an instance of
+ :class:`urllib3.util.Timeout`.
+
+ :param pool_timeout:
+ If set and the pool is set to block=True, then this method will
+ block for ``pool_timeout`` seconds and raise EmptyPoolError if no
+ connection is available within the time period.
+
+ :param bool preload_content:
+ If True, the response's body will be preloaded into memory.
+
+ :param bool decode_content:
+ If True, will attempt to decode the body based on the
+ 'content-encoding' header.
+
+ :param release_conn:
+ If False, then the urlopen call will not release the connection
+ back into the pool once a response is received (but will release if
+ you read the entire contents of the response such as when
+ `preload_content=True`). This is useful if you're not preloading
+ the response's content immediately. You will need to call
+ ``r.release_conn()`` on the response ``r`` to return the connection
+ back into the pool. If None, it takes the value of ``preload_content``
+ which defaults to ``True``.
+
+ :param bool chunked:
+ If True, urllib3 will send the body using chunked transfer
+ encoding. Otherwise, urllib3 will send the body using the standard
+ content-length form. Defaults to False.
+
+ :param int body_pos:
+ Position to seek to in file-like body in the event of a retry or
+ redirect. Typically this won't need to be set because urllib3 will
+ auto-populate the value when needed.
+ """
+ parsed_url = parse_url(url)
+ destination_scheme = parsed_url.scheme
+
+ if headers is None:
+ headers = self.headers
+
+ if not isinstance(retries, Retry):
+ retries = Retry.from_int(retries, redirect=redirect, default=self.retries)
+
+ if release_conn is None:
+ release_conn = preload_content
+
+ # Check host
+ if assert_same_host and not self.is_same_host(url):
+ raise HostChangedError(self, url, retries)
+
+ # Ensure that the URL we're connecting to is properly encoded
+ if url.startswith("/"):
+ url = to_str(_encode_target(url))
+ else:
+ url = to_str(parsed_url.url)
+
+ conn = None
+
+ # Track whether `conn` needs to be released before
+ # returning/raising/recursing. Update this variable if necessary, and
+ # leave `release_conn` constant throughout the function. That way, if
+ # the function recurses, the original value of `release_conn` will be
+ # passed down into the recursive call, and its value will be respected.
+ #
+ # See issue #651 [1] for details.
+ #
+ # [1]
+ release_this_conn = release_conn
+
+ http_tunnel_required = connection_requires_http_tunnel(
+ self.proxy, self.proxy_config, destination_scheme
+ )
+
+ # Merge the proxy headers. Only done when not using HTTP CONNECT. We
+ # have to copy the headers dict so we can safely change it without those
+ # changes being reflected in anyone else's copy.
+ if not http_tunnel_required:
+ headers = headers.copy() # type: ignore[attr-defined]
+ headers.update(self.proxy_headers) # type: ignore[union-attr]
+
+ # Must keep the exception bound to a separate variable or else Python 3
+ # complains about UnboundLocalError.
+ err = None
+
+ # Keep track of whether we cleanly exited the except block. This
+ # ensures we do proper cleanup in finally.
+ clean_exit = False
+
+ # Rewind body position, if needed. Record current position
+ # for future rewinds in the event of a redirect/retry.
+ body_pos = set_file_position(body, body_pos)
+
+ try:
+ # Request a connection from the queue.
+ timeout_obj = self._get_timeout(timeout)
+ conn = self._get_conn(timeout=pool_timeout)
+
+ conn.timeout = timeout_obj.connect_timeout # type: ignore[assignment]
+
+ # Is this a closed/new connection that requires CONNECT tunnelling?
+ if self.proxy is not None and http_tunnel_required and conn.is_closed:
+ try:
+ self._prepare_proxy(conn)
+ except (BaseSSLError, OSError, SocketTimeout) as e:
+ self._raise_timeout(
+ err=e, url=self.proxy.url, timeout_value=conn.timeout
+ )
+ raise
+
+ # If we're going to release the connection in ``finally:``, then
+ # the response doesn't need to know about the connection. Otherwise
+ # it will also try to release it and we'll have a double-release
+ # mess.
+ response_conn = conn if not release_conn else None
+
+ # Make the request on the HTTPConnection object
+ response = self._make_request(
+ conn,
+ method,
+ url,
+ timeout=timeout_obj,
+ body=body,
+ headers=headers,
+ chunked=chunked,
+ retries=retries,
+ response_conn=response_conn,
+ preload_content=preload_content,
+ decode_content=decode_content,
+ **response_kw,
+ )
+
+ # Everything went great!
+ clean_exit = True
+
+ except EmptyPoolError:
+ # Didn't get a connection from the pool, no need to clean up
+ clean_exit = True
+ release_this_conn = False
+ raise
+
+ except (
+ TimeoutError,
+ HTTPException,
+ OSError,
+ ProtocolError,
+ BaseSSLError,
+ SSLError,
+ CertificateError,
+ ProxyError,
+ ) as e:
+ # Discard the connection for these exceptions. It will be
+ # replaced during the next _get_conn() call.
+ clean_exit = False
+ new_e: Exception = e
+ if isinstance(e, (BaseSSLError, CertificateError)):
+ new_e = SSLError(e)
+ if isinstance(
+ new_e,
+ (
+ OSError,
+ NewConnectionError,
+ TimeoutError,
+ SSLError,
+ HTTPException,
+ ),
+ ) and (conn and conn.proxy and not conn.has_connected_to_proxy):
+ new_e = _wrap_proxy_error(new_e, conn.proxy.scheme)
+ elif isinstance(new_e, (OSError, HTTPException)):
+ new_e = ProtocolError("Connection aborted.", new_e)
+
+ retries = retries.increment(
+ method, url, error=new_e, _pool=self, _stacktrace=sys.exc_info()[2]
+ )
+ retries.sleep()
+
+ # Keep track of the error for the retry warning.
+ err = e
+
+ finally:
+ if not clean_exit:
+ # We hit some kind of exception, handled or otherwise. We need
+ # to throw the connection away unless explicitly told not to.
+ # Close the connection, set the variable to None, and make sure
+ # we put the None back in the pool to avoid leaking it.
+ if conn:
+ conn.close()
+ conn = None
+ release_this_conn = True
+
+ if release_this_conn:
+ # Put the connection back to be reused. If the connection is
+ # expired then it will be None, which will get replaced with a
+ # fresh connection during _get_conn.
+ self._put_conn(conn)
+
+ if not conn:
+ # Try again
+ log.warning(
+ "Retrying (%r) after connection broken by '%r': %s", retries, err, url
+ )
+ return self.urlopen(
+ method,
+ url,
+ body,
+ headers,
+ retries,
+ redirect,
+ assert_same_host,
+ timeout=timeout,
+ pool_timeout=pool_timeout,
+ release_conn=release_conn,
+ chunked=chunked,
+ body_pos=body_pos,
+ preload_content=preload_content,
+ decode_content=decode_content,
+ **response_kw,
+ )
+
+ # Handle redirect?
+ redirect_location = redirect and response.get_redirect_location()
+ if redirect_location:
+ if response.status == 303:
+ # Change the method according to RFC 9110, Section 15.4.4.
+ method = "GET"
+ # And lose the body not to transfer anything sensitive.
+ body = None
+ headers = HTTPHeaderDict(headers)._prepare_for_method_change()
+
+ try:
+ retries = retries.increment(method, url, response=response, _pool=self)
+ except MaxRetryError:
+ if retries.raise_on_redirect:
+ response.drain_conn()
+ raise
+ return response
+
+ response.drain_conn()
+ retries.sleep_for_retry(response)
+ log.debug("Redirecting %s -> %s", url, redirect_location)
+ return self.urlopen(
+ method,
+ redirect_location,
+ body,
+ headers,
+ retries=retries,
+ redirect=redirect,
+ assert_same_host=assert_same_host,
+ timeout=timeout,
+ pool_timeout=pool_timeout,
+ release_conn=release_conn,
+ chunked=chunked,
+ body_pos=body_pos,
+ preload_content=preload_content,
+ decode_content=decode_content,
+ **response_kw,
+ )
+
+ # Check if we should retry the HTTP response.
+ has_retry_after = bool(response.headers.get("Retry-After"))
+ if retries.is_retry(method, response.status, has_retry_after):
+ try:
+ retries = retries.increment(method, url, response=response, _pool=self)
+ except MaxRetryError:
+ if retries.raise_on_status:
+ response.drain_conn()
+ raise
+ return response
+
+ response.drain_conn()
+ retries.sleep(response)
+ log.debug("Retry: %s", url)
+ return self.urlopen(
+ method,
+ url,
+ body,
+ headers,
+ retries=retries,
+ redirect=redirect,
+ assert_same_host=assert_same_host,
+ timeout=timeout,
+ pool_timeout=pool_timeout,
+ release_conn=release_conn,
+ chunked=chunked,
+ body_pos=body_pos,
+ preload_content=preload_content,
+ decode_content=decode_content,
+ **response_kw,
+ )
+
+ return response
+
+
+class HTTPSConnectionPool(HTTPConnectionPool):
+ """
+ Same as :class:`.HTTPConnectionPool`, but HTTPS.
+
+ :class:`.HTTPSConnection` uses one of ``assert_fingerprint``,
+ ``assert_hostname`` and ``host`` in this order to verify connections.
+ If ``assert_hostname`` is False, no verification is done.
+
+ The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs``,
+ ``ca_cert_dir``, ``ssl_version``, ``key_password`` are only used if :mod:`ssl`
+ is available and are fed into :meth:`urllib3.util.ssl_wrap_socket` to upgrade
+ the connection socket into an SSL socket.
+ """
+
+ scheme = "https"
+ ConnectionCls: type[BaseHTTPSConnection] = HTTPSConnection
+
+ def __init__(
+ self,
+ host: str,
+ port: int | None = None,
+ timeout: _TYPE_TIMEOUT | None = _DEFAULT_TIMEOUT,
+ maxsize: int = 1,
+ block: bool = False,
+ headers: typing.Mapping[str, str] | None = None,
+ retries: Retry | bool | int | None = None,
+ _proxy: Url | None = None,
+ _proxy_headers: typing.Mapping[str, str] | None = None,
+ key_file: str | None = None,
+ cert_file: str | None = None,
+ cert_reqs: int | str | None = None,
+ key_password: str | None = None,
+ ca_certs: str | None = None,
+ ssl_version: int | str | None = None,
+ ssl_minimum_version: ssl.TLSVersion | None = None,
+ ssl_maximum_version: ssl.TLSVersion | None = None,
+ assert_hostname: str | typing.Literal[False] | None = None,
+ assert_fingerprint: str | None = None,
+ ca_cert_dir: str | None = None,
+ **conn_kw: typing.Any,
+ ) -> None:
+ super().__init__(
+ host,
+ port,
+ timeout,
+ maxsize,
+ block,
+ headers,
+ retries,
+ _proxy,
+ _proxy_headers,
+ **conn_kw,
+ )
+
+ self.key_file = key_file
+ self.cert_file = cert_file
+ self.cert_reqs = cert_reqs
+ self.key_password = key_password
+ self.ca_certs = ca_certs
+ self.ca_cert_dir = ca_cert_dir
+ self.ssl_version = ssl_version
+ self.ssl_minimum_version = ssl_minimum_version
+ self.ssl_maximum_version = ssl_maximum_version
+ self.assert_hostname = assert_hostname
+ self.assert_fingerprint = assert_fingerprint
+
+ def _prepare_proxy(self, conn: HTTPSConnection) -> None: # type: ignore[override]
+ """Establishes a tunnel connection through HTTP CONNECT."""
+ if self.proxy and self.proxy.scheme == "https":
+ tunnel_scheme = "https"
+ else:
+ tunnel_scheme = "http"
+
+ conn.set_tunnel(
+ scheme=tunnel_scheme,
+ host=self._tunnel_host,
+ port=self.port,
+ headers=self.proxy_headers,
+ )
+ conn.connect()
+
+ def _new_conn(self) -> BaseHTTPSConnection:
+ """
+ Return a fresh :class:`urllib3.connection.HTTPConnection`.
+ """
+ self.num_connections += 1
+ log.debug(
+ "Starting new HTTPS connection (%d): %s:%s",
+ self.num_connections,
+ self.host,
+ self.port or "443",
+ )
+
+ if not self.ConnectionCls or self.ConnectionCls is DummyConnection: # type: ignore[comparison-overlap]
+ raise ImportError(
+ "Can't connect to HTTPS URL because the SSL module is not available."
+ )
+
+ actual_host: str = self.host
+ actual_port = self.port
+ if self.proxy is not None and self.proxy.host is not None:
+ actual_host = self.proxy.host
+ actual_port = self.proxy.port
+
+ return self.ConnectionCls(
+ host=actual_host,
+ port=actual_port,
+ timeout=self.timeout.connect_timeout,
+ cert_file=self.cert_file,
+ key_file=self.key_file,
+ key_password=self.key_password,
+ cert_reqs=self.cert_reqs,
+ ca_certs=self.ca_certs,
+ ca_cert_dir=self.ca_cert_dir,
+ assert_hostname=self.assert_hostname,
+ assert_fingerprint=self.assert_fingerprint,
+ ssl_version=self.ssl_version,
+ ssl_minimum_version=self.ssl_minimum_version,
+ ssl_maximum_version=self.ssl_maximum_version,
+ **self.conn_kw,
+ )
+
+ def _validate_conn(self, conn: BaseHTTPConnection) -> None:
+ """
+ Called right before a request is made, after the socket is created.
+ """
+ super()._validate_conn(conn)
+
+ # Force connect early to allow us to validate the connection.
+ if conn.is_closed:
+ conn.connect()
+
+ # TODO revise this, see https://github.com/urllib3/urllib3/issues/2791
+ if not conn.is_verified and not conn.proxy_is_verified:
+ warnings.warn(
+ (
+ f"Unverified HTTPS request is being made to host '{conn.host}'. "
+ "Adding certificate verification is strongly advised. See: "
+ "https://urllib3.readthedocs.io/en/latest/advanced-usage.html"
+ "#tls-warnings"
+ ),
+ InsecureRequestWarning,
+ )
+
+
+def connection_from_url(url: str, **kw: typing.Any) -> HTTPConnectionPool:
+ """
+ Given a url, return an :class:`.ConnectionPool` instance of its host.
+
+ This is a shortcut for not having to parse out the scheme, host, and port
+ of the url before creating an :class:`.ConnectionPool` instance.
+
+ :param url:
+ Absolute URL string that must include the scheme. Port is optional.
+
+ :param \\**kw:
+ Passes additional parameters to the constructor of the appropriate
+ :class:`.ConnectionPool`. Useful for specifying things like
+ timeout, maxsize, headers, etc.
+
+ Example::
+
+ >>> conn = connection_from_url('http://google.com/')
+ >>> r = conn.request('GET', '/')
+ """
+ scheme, _, host, port, *_ = parse_url(url)
+ scheme = scheme or "http"
+ port = port or port_by_scheme.get(scheme, 80)
+ if scheme == "https":
+ return HTTPSConnectionPool(host, port=port, **kw) # type: ignore[arg-type]
+ else:
+ return HTTPConnectionPool(host, port=port, **kw) # type: ignore[arg-type]
+
+
+@typing.overload
+def _normalize_host(host: None, scheme: str | None) -> None: ...
+
+
+@typing.overload
+def _normalize_host(host: str, scheme: str | None) -> str: ...
+
+
+def _normalize_host(host: str | None, scheme: str | None) -> str | None:
+ """
+ Normalize hosts for comparisons and use with sockets.
+ """
+
+ host = normalize_host(host, scheme)
+
+ # httplib doesn't like it when we include brackets in IPv6 addresses
+ # Specifically, if we include brackets but also pass the port then
+ # httplib crazily doubles up the square brackets on the Host header.
+ # Instead, we need to make sure we never pass ``None`` as the port.
+ # However, for backward compatibility reasons we can't actually
+ # *assert* that. See http://bugs.python.org/issue28539
+ if host and host.startswith("[") and host.endswith("]"):
+ host = host[1:-1]
+ return host
+
+
+def _url_from_pool(
+ pool: HTTPConnectionPool | HTTPSConnectionPool, path: str | None = None
+) -> str:
+ """Returns the URL from a given connection pool. This is mainly used for testing and logging."""
+ return Url(scheme=pool.scheme, host=pool.host, port=pool.port, path=path).url
+
+
+def _close_pool_connections(pool: queue.LifoQueue[typing.Any]) -> None:
+ """Drains a queue of connections and closes each one."""
+ try:
+ while True:
+ conn = pool.get(block=False)
+ if conn:
+ conn.close()
+ except queue.Empty:
+ pass # Done.
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/emscripten/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/emscripten/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5b62b25e932566f7ae7599c1cedec2b8f30d95b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/emscripten/__init__.py
@@ -0,0 +1,17 @@
+from __future__ import annotations
+
+import urllib3.connection
+
+from ...connectionpool import HTTPConnectionPool, HTTPSConnectionPool
+from .connection import EmscriptenHTTPConnection, EmscriptenHTTPSConnection
+
+
+def inject_into_urllib3() -> None:
+ # override connection classes to use emscripten specific classes
+ # n.b. mypy complains about the overriding of classes below
+ # if it isn't ignored
+ HTTPConnectionPool.ConnectionCls = EmscriptenHTTPConnection
+ HTTPSConnectionPool.ConnectionCls = EmscriptenHTTPSConnection
+ urllib3.connection.HTTPConnection = EmscriptenHTTPConnection # type: ignore[misc,assignment]
+ urllib3.connection.HTTPSConnection = EmscriptenHTTPSConnection # type: ignore[misc,assignment]
+ urllib3.connection.VerifiedHTTPSConnection = EmscriptenHTTPSConnection # type: ignore[assignment]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/emscripten/connection.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/emscripten/connection.py
new file mode 100644
index 0000000000000000000000000000000000000000..63f79dd3be803db09671c909f79316c3f65d6916
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/emscripten/connection.py
@@ -0,0 +1,260 @@
+from __future__ import annotations
+
+import os
+import typing
+
+# use http.client.HTTPException for consistency with non-emscripten
+from http.client import HTTPException as HTTPException # noqa: F401
+from http.client import ResponseNotReady
+
+from ..._base_connection import _TYPE_BODY
+from ...connection import HTTPConnection, ProxyConfig, port_by_scheme
+from ...exceptions import TimeoutError
+from ...response import BaseHTTPResponse
+from ...util.connection import _TYPE_SOCKET_OPTIONS
+from ...util.timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT
+from ...util.url import Url
+from .fetch import _RequestError, _TimeoutError, send_request, send_streaming_request
+from .request import EmscriptenRequest
+from .response import EmscriptenHttpResponseWrapper, EmscriptenResponse
+
+if typing.TYPE_CHECKING:
+ from ..._base_connection import BaseHTTPConnection, BaseHTTPSConnection
+
+
+class EmscriptenHTTPConnection:
+ default_port: typing.ClassVar[int] = port_by_scheme["http"]
+ default_socket_options: typing.ClassVar[_TYPE_SOCKET_OPTIONS]
+
+ timeout: None | (float)
+
+ host: str
+ port: int
+ blocksize: int
+ source_address: tuple[str, int] | None
+ socket_options: _TYPE_SOCKET_OPTIONS | None
+
+ proxy: Url | None
+ proxy_config: ProxyConfig | None
+
+ is_verified: bool = False
+ proxy_is_verified: bool | None = None
+
+ response_class: type[BaseHTTPResponse] = EmscriptenHttpResponseWrapper
+ _response: EmscriptenResponse | None
+
+ def __init__(
+ self,
+ host: str,
+ port: int = 0,
+ *,
+ timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,
+ source_address: tuple[str, int] | None = None,
+ blocksize: int = 8192,
+ socket_options: _TYPE_SOCKET_OPTIONS | None = None,
+ proxy: Url | None = None,
+ proxy_config: ProxyConfig | None = None,
+ ) -> None:
+ self.host = host
+ self.port = port
+ self.timeout = timeout if isinstance(timeout, float) else 0.0
+ self.scheme = "http"
+ self._closed = True
+ self._response = None
+ # ignore these things because we don't
+ # have control over that stuff
+ self.proxy = None
+ self.proxy_config = None
+ self.blocksize = blocksize
+ self.source_address = None
+ self.socket_options = None
+ self.is_verified = False
+
+ def set_tunnel(
+ self,
+ host: str,
+ port: int | None = 0,
+ headers: typing.Mapping[str, str] | None = None,
+ scheme: str = "http",
+ ) -> None:
+ pass
+
+ def connect(self) -> None:
+ pass
+
+ def request(
+ self,
+ method: str,
+ url: str,
+ body: _TYPE_BODY | None = None,
+ headers: typing.Mapping[str, str] | None = None,
+ # We know *at least* botocore is depending on the order of the
+ # first 3 parameters so to be safe we only mark the later ones
+ # as keyword-only to ensure we have space to extend.
+ *,
+ chunked: bool = False,
+ preload_content: bool = True,
+ decode_content: bool = True,
+ enforce_content_length: bool = True,
+ ) -> None:
+ self._closed = False
+ if url.startswith("/"):
+ if self.port is not None:
+ port = f":{self.port}"
+ else:
+ port = ""
+ # no scheme / host / port included, make a full url
+ url = f"{self.scheme}://{self.host}{port}{url}"
+ request = EmscriptenRequest(
+ url=url,
+ method=method,
+ timeout=self.timeout if self.timeout else 0,
+ decode_content=decode_content,
+ )
+ request.set_body(body)
+ if headers:
+ for k, v in headers.items():
+ request.set_header(k, v)
+ self._response = None
+ try:
+ if not preload_content:
+ self._response = send_streaming_request(request)
+ if self._response is None:
+ self._response = send_request(request)
+ except _TimeoutError as e:
+ raise TimeoutError(e.message) from e
+ except _RequestError as e:
+ raise HTTPException(e.message) from e
+
+ def getresponse(self) -> BaseHTTPResponse:
+ if self._response is not None:
+ return EmscriptenHttpResponseWrapper(
+ internal_response=self._response,
+ url=self._response.request.url,
+ connection=self,
+ )
+ else:
+ raise ResponseNotReady()
+
+ def close(self) -> None:
+ self._closed = True
+ self._response = None
+
+ @property
+ def is_closed(self) -> bool:
+ """Whether the connection either is brand new or has been previously closed.
+ If this property is True then both ``is_connected`` and ``has_connected_to_proxy``
+ properties must be False.
+ """
+ return self._closed
+
+ @property
+ def is_connected(self) -> bool:
+ """Whether the connection is actively connected to any origin (proxy or target)"""
+ return True
+
+ @property
+ def has_connected_to_proxy(self) -> bool:
+ """Whether the connection has successfully connected to its proxy.
+ This returns False if no proxy is in use. Used to determine whether
+ errors are coming from the proxy layer or from tunnelling to the target origin.
+ """
+ return False
+
+
+class EmscriptenHTTPSConnection(EmscriptenHTTPConnection):
+ default_port = port_by_scheme["https"]
+ # all this is basically ignored, as browser handles https
+ cert_reqs: int | str | None = None
+ ca_certs: str | None = None
+ ca_cert_dir: str | None = None
+ ca_cert_data: None | str | bytes = None
+ cert_file: str | None
+ key_file: str | None
+ key_password: str | None
+ ssl_context: typing.Any | None
+ ssl_version: int | str | None = None
+ ssl_minimum_version: int | None = None
+ ssl_maximum_version: int | None = None
+ assert_hostname: None | str | typing.Literal[False]
+ assert_fingerprint: str | None = None
+
+ def __init__(
+ self,
+ host: str,
+ port: int = 0,
+ *,
+ timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,
+ source_address: tuple[str, int] | None = None,
+ blocksize: int = 16384,
+ socket_options: (
+ None | _TYPE_SOCKET_OPTIONS
+ ) = HTTPConnection.default_socket_options,
+ proxy: Url | None = None,
+ proxy_config: ProxyConfig | None = None,
+ cert_reqs: int | str | None = None,
+ assert_hostname: None | str | typing.Literal[False] = None,
+ assert_fingerprint: str | None = None,
+ server_hostname: str | None = None,
+ ssl_context: typing.Any | None = None,
+ ca_certs: str | None = None,
+ ca_cert_dir: str | None = None,
+ ca_cert_data: None | str | bytes = None,
+ ssl_minimum_version: int | None = None,
+ ssl_maximum_version: int | None = None,
+ ssl_version: int | str | None = None, # Deprecated
+ cert_file: str | None = None,
+ key_file: str | None = None,
+ key_password: str | None = None,
+ ) -> None:
+ super().__init__(
+ host,
+ port=port,
+ timeout=timeout,
+ source_address=source_address,
+ blocksize=blocksize,
+ socket_options=socket_options,
+ proxy=proxy,
+ proxy_config=proxy_config,
+ )
+ self.scheme = "https"
+
+ self.key_file = key_file
+ self.cert_file = cert_file
+ self.key_password = key_password
+ self.ssl_context = ssl_context
+ self.server_hostname = server_hostname
+ self.assert_hostname = assert_hostname
+ self.assert_fingerprint = assert_fingerprint
+ self.ssl_version = ssl_version
+ self.ssl_minimum_version = ssl_minimum_version
+ self.ssl_maximum_version = ssl_maximum_version
+ self.ca_certs = ca_certs and os.path.expanduser(ca_certs)
+ self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)
+ self.ca_cert_data = ca_cert_data
+
+ self.cert_reqs = None
+
+ # The browser will automatically verify all requests.
+ # We have no control over that setting.
+ self.is_verified = True
+
+ def set_cert(
+ self,
+ key_file: str | None = None,
+ cert_file: str | None = None,
+ cert_reqs: int | str | None = None,
+ key_password: str | None = None,
+ ca_certs: str | None = None,
+ assert_hostname: None | str | typing.Literal[False] = None,
+ assert_fingerprint: str | None = None,
+ ca_cert_dir: str | None = None,
+ ca_cert_data: None | str | bytes = None,
+ ) -> None:
+ pass
+
+
+# verify that this class implements BaseHTTP(s) connection correctly
+if typing.TYPE_CHECKING:
+ _supports_http_protocol: BaseHTTPConnection = EmscriptenHTTPConnection("", 0)
+ _supports_https_protocol: BaseHTTPSConnection = EmscriptenHTTPSConnection("", 0)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/emscripten/emscripten_fetch_worker.js b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/emscripten/emscripten_fetch_worker.js
new file mode 100644
index 0000000000000000000000000000000000000000..faf141e1fa4113a0c14480d1681ddecb9678ced4
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/emscripten/emscripten_fetch_worker.js
@@ -0,0 +1,110 @@
+let Status = {
+ SUCCESS_HEADER: -1,
+ SUCCESS_EOF: -2,
+ ERROR_TIMEOUT: -3,
+ ERROR_EXCEPTION: -4,
+};
+
+let connections = new Map();
+let nextConnectionID = 1;
+const encoder = new TextEncoder();
+
+self.addEventListener("message", async function (event) {
+ if (event.data.close) {
+ let connectionID = event.data.close;
+ connections.delete(connectionID);
+ return;
+ } else if (event.data.getMore) {
+ let connectionID = event.data.getMore;
+ let { curOffset, value, reader, intBuffer, byteBuffer } =
+ connections.get(connectionID);
+ // if we still have some in buffer, then just send it back straight away
+ if (!value || curOffset >= value.length) {
+ // read another buffer if required
+ try {
+ let readResponse = await reader.read();
+
+ if (readResponse.done) {
+ // read everything - clear connection and return
+ connections.delete(connectionID);
+ Atomics.store(intBuffer, 0, Status.SUCCESS_EOF);
+ Atomics.notify(intBuffer, 0);
+ // finished reading successfully
+ // return from event handler
+ return;
+ }
+ curOffset = 0;
+ connections.get(connectionID).value = readResponse.value;
+ value = readResponse.value;
+ } catch (error) {
+ console.log("Request exception:", error);
+ let errorBytes = encoder.encode(error.message);
+ let written = errorBytes.length;
+ byteBuffer.set(errorBytes);
+ intBuffer[1] = written;
+ Atomics.store(intBuffer, 0, Status.ERROR_EXCEPTION);
+ Atomics.notify(intBuffer, 0);
+ }
+ }
+
+ // send as much buffer as we can
+ let curLen = value.length - curOffset;
+ if (curLen > byteBuffer.length) {
+ curLen = byteBuffer.length;
+ }
+ byteBuffer.set(value.subarray(curOffset, curOffset + curLen), 0);
+
+ Atomics.store(intBuffer, 0, curLen); // store current length in bytes
+ Atomics.notify(intBuffer, 0);
+ curOffset += curLen;
+ connections.get(connectionID).curOffset = curOffset;
+
+ return;
+ } else {
+ // start fetch
+ let connectionID = nextConnectionID;
+ nextConnectionID += 1;
+ const intBuffer = new Int32Array(event.data.buffer);
+ const byteBuffer = new Uint8Array(event.data.buffer, 8);
+ try {
+ const response = await fetch(event.data.url, event.data.fetchParams);
+ // return the headers first via textencoder
+ var headers = [];
+ for (const pair of response.headers.entries()) {
+ headers.push([pair[0], pair[1]]);
+ }
+ let headerObj = {
+ headers: headers,
+ status: response.status,
+ connectionID,
+ };
+ const headerText = JSON.stringify(headerObj);
+ let headerBytes = encoder.encode(headerText);
+ let written = headerBytes.length;
+ byteBuffer.set(headerBytes);
+ intBuffer[1] = written;
+ // make a connection
+ connections.set(connectionID, {
+ reader: response.body.getReader(),
+ intBuffer: intBuffer,
+ byteBuffer: byteBuffer,
+ value: undefined,
+ curOffset: 0,
+ });
+ // set header ready
+ Atomics.store(intBuffer, 0, Status.SUCCESS_HEADER);
+ Atomics.notify(intBuffer, 0);
+ // all fetching after this goes through a new postmessage call with getMore
+ // this allows for parallel requests
+ } catch (error) {
+ console.log("Request exception:", error);
+ let errorBytes = encoder.encode(error.message);
+ let written = errorBytes.length;
+ byteBuffer.set(errorBytes);
+ intBuffer[1] = written;
+ Atomics.store(intBuffer, 0, Status.ERROR_EXCEPTION);
+ Atomics.notify(intBuffer, 0);
+ }
+ }
+});
+self.postMessage({ inited: true });
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/emscripten/fetch.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/emscripten/fetch.py
new file mode 100644
index 0000000000000000000000000000000000000000..612cfddc4c28d2f0edf47522278fa6d9b7906623
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/emscripten/fetch.py
@@ -0,0 +1,726 @@
+"""
+Support for streaming http requests in emscripten.
+
+A few caveats -
+
+If your browser (or Node.js) has WebAssembly JavaScript Promise Integration enabled
+https://github.com/WebAssembly/js-promise-integration/blob/main/proposals/js-promise-integration/Overview.md
+*and* you launch pyodide using `pyodide.runPythonAsync`, this will fetch data using the
+JavaScript asynchronous fetch api (wrapped via `pyodide.ffi.call_sync`). In this case
+timeouts and streaming should just work.
+
+Otherwise, it uses a combination of XMLHttpRequest and a web-worker for streaming.
+
+This approach has several caveats:
+
+Firstly, you can't do streaming http in the main UI thread, because atomics.wait isn't allowed.
+Streaming only works if you're running pyodide in a web worker.
+
+Secondly, this uses an extra web worker and SharedArrayBuffer to do the asynchronous fetch
+operation, so it requires that you have crossOriginIsolation enabled, by serving over https
+(or from localhost) with the two headers below set:
+
+ Cross-Origin-Opener-Policy: same-origin
+ Cross-Origin-Embedder-Policy: require-corp
+
+You can tell if cross origin isolation is successfully enabled by looking at the global crossOriginIsolated variable in
+JavaScript console. If it isn't, streaming requests will fallback to XMLHttpRequest, i.e. getting the whole
+request into a buffer and then returning it. it shows a warning in the JavaScript console in this case.
+
+Finally, the webworker which does the streaming fetch is created on initial import, but will only be started once
+control is returned to javascript. Call `await wait_for_streaming_ready()` to wait for streaming fetch.
+
+NB: in this code, there are a lot of JavaScript objects. They are named js_*
+to make it clear what type of object they are.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+from email.parser import Parser
+from importlib.resources import files
+from typing import TYPE_CHECKING, Any
+
+import js # type: ignore[import-not-found]
+from pyodide.ffi import ( # type: ignore[import-not-found]
+ JsArray,
+ JsException,
+ JsProxy,
+ to_js,
+)
+
+if TYPE_CHECKING:
+ from typing_extensions import Buffer
+
+from .request import EmscriptenRequest
+from .response import EmscriptenResponse
+
+"""
+There are some headers that trigger unintended CORS preflight requests.
+See also https://github.com/koenvo/pyodide-http/issues/22
+"""
+HEADERS_TO_IGNORE = ("user-agent",)
+
+SUCCESS_HEADER = -1
+SUCCESS_EOF = -2
+ERROR_TIMEOUT = -3
+ERROR_EXCEPTION = -4
+
+
+class _RequestError(Exception):
+ def __init__(
+ self,
+ message: str | None = None,
+ *,
+ request: EmscriptenRequest | None = None,
+ response: EmscriptenResponse | None = None,
+ ):
+ self.request = request
+ self.response = response
+ self.message = message
+ super().__init__(self.message)
+
+
+class _StreamingError(_RequestError):
+ pass
+
+
+class _TimeoutError(_RequestError):
+ pass
+
+
+def _obj_from_dict(dict_val: dict[str, Any]) -> JsProxy:
+ return to_js(dict_val, dict_converter=js.Object.fromEntries)
+
+
+class _ReadStream(io.RawIOBase):
+ def __init__(
+ self,
+ int_buffer: JsArray,
+ byte_buffer: JsArray,
+ timeout: float,
+ worker: JsProxy,
+ connection_id: int,
+ request: EmscriptenRequest,
+ ):
+ self.int_buffer = int_buffer
+ self.byte_buffer = byte_buffer
+ self.read_pos = 0
+ self.read_len = 0
+ self.connection_id = connection_id
+ self.worker = worker
+ self.timeout = int(1000 * timeout) if timeout > 0 else None
+ self.is_live = True
+ self._is_closed = False
+ self.request: EmscriptenRequest | None = request
+
+ def __del__(self) -> None:
+ self.close()
+
+ # this is compatible with _base_connection
+ def is_closed(self) -> bool:
+ return self._is_closed
+
+ # for compatibility with RawIOBase
+ @property
+ def closed(self) -> bool:
+ return self.is_closed()
+
+ def close(self) -> None:
+ if self.is_closed():
+ return
+ self.read_len = 0
+ self.read_pos = 0
+ self.int_buffer = None
+ self.byte_buffer = None
+ self._is_closed = True
+ self.request = None
+ if self.is_live:
+ self.worker.postMessage(_obj_from_dict({"close": self.connection_id}))
+ self.is_live = False
+ super().close()
+
+ def readable(self) -> bool:
+ return True
+
+ def writable(self) -> bool:
+ return False
+
+ def seekable(self) -> bool:
+ return False
+
+ def readinto(self, byte_obj: Buffer) -> int:
+ if not self.int_buffer:
+ raise _StreamingError(
+ "No buffer for stream in _ReadStream.readinto",
+ request=self.request,
+ response=None,
+ )
+ if self.read_len == 0:
+ # wait for the worker to send something
+ js.Atomics.store(self.int_buffer, 0, ERROR_TIMEOUT)
+ self.worker.postMessage(_obj_from_dict({"getMore": self.connection_id}))
+ if (
+ js.Atomics.wait(self.int_buffer, 0, ERROR_TIMEOUT, self.timeout)
+ == "timed-out"
+ ):
+ raise _TimeoutError
+ data_len = self.int_buffer[0]
+ if data_len > 0:
+ self.read_len = data_len
+ self.read_pos = 0
+ elif data_len == ERROR_EXCEPTION:
+ string_len = self.int_buffer[1]
+ # decode the error string
+ js_decoder = js.TextDecoder.new()
+ json_str = js_decoder.decode(self.byte_buffer.slice(0, string_len))
+ raise _StreamingError(
+ f"Exception thrown in fetch: {json_str}",
+ request=self.request,
+ response=None,
+ )
+ else:
+ # EOF, free the buffers and return zero
+ # and free the request
+ self.is_live = False
+ self.close()
+ return 0
+ # copy from int32array to python bytes
+ ret_length = min(self.read_len, len(memoryview(byte_obj)))
+ subarray = self.byte_buffer.subarray(
+ self.read_pos, self.read_pos + ret_length
+ ).to_py()
+ memoryview(byte_obj)[0:ret_length] = subarray
+ self.read_len -= ret_length
+ self.read_pos += ret_length
+ return ret_length
+
+
+class _StreamingFetcher:
+ def __init__(self) -> None:
+ # make web-worker and data buffer on startup
+ self.streaming_ready = False
+ streaming_worker_code = (
+ files(__package__)
+ .joinpath("emscripten_fetch_worker.js")
+ .read_text(encoding="utf-8")
+ )
+ js_data_blob = js.Blob.new(
+ to_js([streaming_worker_code], create_pyproxies=False),
+ _obj_from_dict({"type": "application/javascript"}),
+ )
+
+ def promise_resolver(js_resolve_fn: JsProxy, js_reject_fn: JsProxy) -> None:
+ def onMsg(e: JsProxy) -> None:
+ self.streaming_ready = True
+ js_resolve_fn(e)
+
+ def onErr(e: JsProxy) -> None:
+ js_reject_fn(e) # Defensive: never happens in ci
+
+ self.js_worker.onmessage = onMsg
+ self.js_worker.onerror = onErr
+
+ js_data_url = js.URL.createObjectURL(js_data_blob)
+ self.js_worker = js.globalThis.Worker.new(js_data_url)
+ self.js_worker_ready_promise = js.globalThis.Promise.new(promise_resolver)
+
+ def send(self, request: EmscriptenRequest) -> EmscriptenResponse:
+ headers = {
+ k: v for k, v in request.headers.items() if k not in HEADERS_TO_IGNORE
+ }
+
+ body = request.body
+ fetch_data = {"headers": headers, "body": to_js(body), "method": request.method}
+ # start the request off in the worker
+ timeout = int(1000 * request.timeout) if request.timeout > 0 else None
+ js_shared_buffer = js.SharedArrayBuffer.new(1048576)
+ js_int_buffer = js.Int32Array.new(js_shared_buffer)
+ js_byte_buffer = js.Uint8Array.new(js_shared_buffer, 8)
+
+ js.Atomics.store(js_int_buffer, 0, ERROR_TIMEOUT)
+ js.Atomics.notify(js_int_buffer, 0)
+ js_absolute_url = js.URL.new(request.url, js.location).href
+ self.js_worker.postMessage(
+ _obj_from_dict(
+ {
+ "buffer": js_shared_buffer,
+ "url": js_absolute_url,
+ "fetchParams": fetch_data,
+ }
+ )
+ )
+ # wait for the worker to send something
+ js.Atomics.wait(js_int_buffer, 0, ERROR_TIMEOUT, timeout)
+ if js_int_buffer[0] == ERROR_TIMEOUT:
+ raise _TimeoutError(
+ "Timeout connecting to streaming request",
+ request=request,
+ response=None,
+ )
+ elif js_int_buffer[0] == SUCCESS_HEADER:
+ # got response
+ # header length is in second int of intBuffer
+ string_len = js_int_buffer[1]
+ # decode the rest to a JSON string
+ js_decoder = js.TextDecoder.new()
+ # this does a copy (the slice) because decode can't work on shared array
+ # for some silly reason
+ json_str = js_decoder.decode(js_byte_buffer.slice(0, string_len))
+ # get it as an object
+ response_obj = json.loads(json_str)
+ return EmscriptenResponse(
+ request=request,
+ status_code=response_obj["status"],
+ headers=response_obj["headers"],
+ body=_ReadStream(
+ js_int_buffer,
+ js_byte_buffer,
+ request.timeout,
+ self.js_worker,
+ response_obj["connectionID"],
+ request,
+ ),
+ )
+ elif js_int_buffer[0] == ERROR_EXCEPTION:
+ string_len = js_int_buffer[1]
+ # decode the error string
+ js_decoder = js.TextDecoder.new()
+ json_str = js_decoder.decode(js_byte_buffer.slice(0, string_len))
+ raise _StreamingError(
+ f"Exception thrown in fetch: {json_str}", request=request, response=None
+ )
+ else:
+ raise _StreamingError(
+ f"Unknown status from worker in fetch: {js_int_buffer[0]}",
+ request=request,
+ response=None,
+ )
+
+
+class _JSPIReadStream(io.RawIOBase):
+ """
+ A read stream that uses pyodide.ffi.run_sync to read from a JavaScript fetch
+ response. This requires support for WebAssembly JavaScript Promise Integration
+ in the containing browser, and for pyodide to be launched via runPythonAsync.
+
+ :param js_read_stream:
+ The JavaScript stream reader
+
+ :param timeout:
+ Timeout in seconds
+
+ :param request:
+ The request we're handling
+
+ :param response:
+ The response this stream relates to
+
+ :param js_abort_controller:
+ A JavaScript AbortController object, used for timeouts
+ """
+
+ def __init__(
+ self,
+ js_read_stream: Any,
+ timeout: float,
+ request: EmscriptenRequest,
+ response: EmscriptenResponse,
+ js_abort_controller: Any, # JavaScript AbortController for timeouts
+ ):
+ self.js_read_stream = js_read_stream
+ self.timeout = timeout
+ self._is_closed = False
+ self._is_done = False
+ self.request: EmscriptenRequest | None = request
+ self.response: EmscriptenResponse | None = response
+ self.current_buffer = None
+ self.current_buffer_pos = 0
+ self.js_abort_controller = js_abort_controller
+
+ def __del__(self) -> None:
+ self.close()
+
+ # this is compatible with _base_connection
+ def is_closed(self) -> bool:
+ return self._is_closed
+
+ # for compatibility with RawIOBase
+ @property
+ def closed(self) -> bool:
+ return self.is_closed()
+
+ def close(self) -> None:
+ if self.is_closed():
+ return
+ self.read_len = 0
+ self.read_pos = 0
+ self.js_read_stream.cancel()
+ self.js_read_stream = None
+ self._is_closed = True
+ self._is_done = True
+ self.request = None
+ self.response = None
+ super().close()
+
+ def readable(self) -> bool:
+ return True
+
+ def writable(self) -> bool:
+ return False
+
+ def seekable(self) -> bool:
+ return False
+
+ def _get_next_buffer(self) -> bool:
+ result_js = _run_sync_with_timeout(
+ self.js_read_stream.read(),
+ self.timeout,
+ self.js_abort_controller,
+ request=self.request,
+ response=self.response,
+ )
+ if result_js.done:
+ self._is_done = True
+ return False
+ else:
+ self.current_buffer = result_js.value.to_py()
+ self.current_buffer_pos = 0
+ return True
+
+ def readinto(self, byte_obj: Buffer) -> int:
+ if self.current_buffer is None:
+ if not self._get_next_buffer() or self.current_buffer is None:
+ self.close()
+ return 0
+ ret_length = min(
+ len(byte_obj), len(self.current_buffer) - self.current_buffer_pos
+ )
+ byte_obj[0:ret_length] = self.current_buffer[
+ self.current_buffer_pos : self.current_buffer_pos + ret_length
+ ]
+ self.current_buffer_pos += ret_length
+ if self.current_buffer_pos == len(self.current_buffer):
+ self.current_buffer = None
+ return ret_length
+
+
+# check if we are in a worker or not
+def is_in_browser_main_thread() -> bool:
+ return hasattr(js, "window") and hasattr(js, "self") and js.self == js.window
+
+
+def is_cross_origin_isolated() -> bool:
+ return hasattr(js, "crossOriginIsolated") and js.crossOriginIsolated
+
+
+def is_in_node() -> bool:
+ return (
+ hasattr(js, "process")
+ and hasattr(js.process, "release")
+ and hasattr(js.process.release, "name")
+ and js.process.release.name == "node"
+ )
+
+
+def is_worker_available() -> bool:
+ return hasattr(js, "Worker") and hasattr(js, "Blob")
+
+
+_fetcher: _StreamingFetcher | None = None
+
+if is_worker_available() and (
+ (is_cross_origin_isolated() and not is_in_browser_main_thread())
+ and (not is_in_node())
+):
+ _fetcher = _StreamingFetcher()
+else:
+ _fetcher = None
+
+
+NODE_JSPI_ERROR = (
+ "urllib3 only works in Node.js with pyodide.runPythonAsync"
+ " and requires the flag --experimental-wasm-stack-switching in "
+ " versions of node <24."
+)
+
+
+def send_streaming_request(request: EmscriptenRequest) -> EmscriptenResponse | None:
+ if has_jspi():
+ return send_jspi_request(request, True)
+ elif is_in_node():
+ raise _RequestError(
+ message=NODE_JSPI_ERROR,
+ request=request,
+ response=None,
+ )
+
+ if _fetcher and streaming_ready():
+ return _fetcher.send(request)
+ else:
+ _show_streaming_warning()
+ return None
+
+
+_SHOWN_TIMEOUT_WARNING = False
+
+
+def _show_timeout_warning() -> None:
+ global _SHOWN_TIMEOUT_WARNING
+ if not _SHOWN_TIMEOUT_WARNING:
+ _SHOWN_TIMEOUT_WARNING = True
+ message = "Warning: Timeout is not available on main browser thread"
+ js.console.warn(message)
+
+
+_SHOWN_STREAMING_WARNING = False
+
+
+def _show_streaming_warning() -> None:
+ global _SHOWN_STREAMING_WARNING
+ if not _SHOWN_STREAMING_WARNING:
+ _SHOWN_STREAMING_WARNING = True
+ message = "Can't stream HTTP requests because: \n"
+ if not is_cross_origin_isolated():
+ message += " Page is not cross-origin isolated\n"
+ if is_in_browser_main_thread():
+ message += " Python is running in main browser thread\n"
+ if not is_worker_available():
+ message += " Worker or Blob classes are not available in this environment." # Defensive: this is always False in browsers that we test in
+ if streaming_ready() is False:
+ message += """ Streaming fetch worker isn't ready. If you want to be sure that streaming fetch
+is working, you need to call: 'await urllib3.contrib.emscripten.fetch.wait_for_streaming_ready()`"""
+ from js import console
+
+ console.warn(message)
+
+
+def send_request(request: EmscriptenRequest) -> EmscriptenResponse:
+ if has_jspi():
+ return send_jspi_request(request, False)
+ elif is_in_node():
+ raise _RequestError(
+ message=NODE_JSPI_ERROR,
+ request=request,
+ response=None,
+ )
+ try:
+ js_xhr = js.XMLHttpRequest.new()
+
+ if not is_in_browser_main_thread():
+ js_xhr.responseType = "arraybuffer"
+ if request.timeout:
+ js_xhr.timeout = int(request.timeout * 1000)
+ else:
+ js_xhr.overrideMimeType("text/plain; charset=ISO-8859-15")
+ if request.timeout:
+ # timeout isn't available on the main thread - show a warning in console
+ # if it is set
+ _show_timeout_warning()
+
+ js_xhr.open(request.method, request.url, False)
+ for name, value in request.headers.items():
+ if name.lower() not in HEADERS_TO_IGNORE:
+ js_xhr.setRequestHeader(name, value)
+
+ js_xhr.send(to_js(request.body))
+
+ headers = dict(Parser().parsestr(js_xhr.getAllResponseHeaders()))
+
+ if not is_in_browser_main_thread():
+ body = js_xhr.response.to_py().tobytes()
+ else:
+ body = js_xhr.response.encode("ISO-8859-15")
+ return EmscriptenResponse(
+ status_code=js_xhr.status, headers=headers, body=body, request=request
+ )
+ except JsException as err:
+ if err.name == "TimeoutError":
+ raise _TimeoutError(err.message, request=request)
+ elif err.name == "NetworkError":
+ raise _RequestError(err.message, request=request)
+ else:
+ # general http error
+ raise _RequestError(err.message, request=request)
+
+
+def send_jspi_request(
+ request: EmscriptenRequest, streaming: bool
+) -> EmscriptenResponse:
+ """
+ Send a request using WebAssembly JavaScript Promise Integration
+ to wrap the asynchronous JavaScript fetch api (experimental).
+
+ :param request:
+ Request to send
+
+ :param streaming:
+ Whether to stream the response
+
+ :return: The response object
+ :rtype: EmscriptenResponse
+ """
+ timeout = request.timeout
+ js_abort_controller = js.AbortController.new()
+ headers = {k: v for k, v in request.headers.items() if k not in HEADERS_TO_IGNORE}
+ req_body = request.body
+ fetch_data = {
+ "headers": headers,
+ "body": to_js(req_body),
+ "method": request.method,
+ "signal": js_abort_controller.signal,
+ }
+ # Node.js returns the whole response (unlike opaqueredirect in browsers),
+ # so urllib3 can set `redirect: manual` to control redirects itself.
+ # https://stackoverflow.com/a/78524615
+ if _is_node_js():
+ fetch_data["redirect"] = "manual"
+ # Call JavaScript fetch (async api, returns a promise)
+ fetcher_promise_js = js.fetch(request.url, _obj_from_dict(fetch_data))
+ # Now suspend WebAssembly until we resolve that promise
+ # or time out.
+ response_js = _run_sync_with_timeout(
+ fetcher_promise_js,
+ timeout,
+ js_abort_controller,
+ request=request,
+ response=None,
+ )
+ headers = {}
+ header_iter = response_js.headers.entries()
+ while True:
+ iter_value_js = header_iter.next()
+ if getattr(iter_value_js, "done", False):
+ break
+ else:
+ headers[str(iter_value_js.value[0])] = str(iter_value_js.value[1])
+ status_code = response_js.status
+ body: bytes | io.RawIOBase = b""
+
+ response = EmscriptenResponse(
+ status_code=status_code, headers=headers, body=b"", request=request
+ )
+ if streaming:
+ # get via inputstream
+ if response_js.body is not None:
+ # get a reader from the fetch response
+ body_stream_js = response_js.body.getReader()
+ body = _JSPIReadStream(
+ body_stream_js, timeout, request, response, js_abort_controller
+ )
+ else:
+ # get directly via arraybuffer
+ # n.b. this is another async JavaScript call.
+ body = _run_sync_with_timeout(
+ response_js.arrayBuffer(),
+ timeout,
+ js_abort_controller,
+ request=request,
+ response=response,
+ ).to_py()
+ response.body = body
+ return response
+
+
+def _run_sync_with_timeout(
+ promise: Any,
+ timeout: float,
+ js_abort_controller: Any,
+ request: EmscriptenRequest | None,
+ response: EmscriptenResponse | None,
+) -> Any:
+ """
+ Await a JavaScript promise synchronously with a timeout which is implemented
+ via the AbortController
+
+ :param promise:
+ Javascript promise to await
+
+ :param timeout:
+ Timeout in seconds
+
+ :param js_abort_controller:
+ A JavaScript AbortController object, used on timeout
+
+ :param request:
+ The request being handled
+
+ :param response:
+ The response being handled (if it exists yet)
+
+ :raises _TimeoutError: If the request times out
+ :raises _RequestError: If the request raises a JavaScript exception
+
+ :return: The result of awaiting the promise.
+ """
+ timer_id = None
+ if timeout > 0:
+ timer_id = js.setTimeout(
+ js_abort_controller.abort.bind(js_abort_controller), int(timeout * 1000)
+ )
+ try:
+ from pyodide.ffi import run_sync
+
+ # run_sync here uses WebAssembly JavaScript Promise Integration to
+ # suspend python until the JavaScript promise resolves.
+ return run_sync(promise)
+ except JsException as err:
+ if err.name == "AbortError":
+ raise _TimeoutError(
+ message="Request timed out", request=request, response=response
+ )
+ else:
+ raise _RequestError(message=err.message, request=request, response=response)
+ finally:
+ if timer_id is not None:
+ js.clearTimeout(timer_id)
+
+
+def has_jspi() -> bool:
+ """
+ Return true if jspi can be used.
+
+ This requires both browser support and also WebAssembly
+ to be in the correct state - i.e. that the javascript
+ call into python was async not sync.
+
+ :return: True if jspi can be used.
+ :rtype: bool
+ """
+ try:
+ from pyodide.ffi import can_run_sync, run_sync # noqa: F401
+
+ return bool(can_run_sync())
+ except ImportError:
+ return False
+
+
+def _is_node_js() -> bool:
+ """
+ Check if we are in Node.js.
+
+ :return: True if we are in Node.js.
+ :rtype: bool
+ """
+ return (
+ hasattr(js, "process")
+ and hasattr(js.process, "release")
+ # According to the Node.js documentation, the release name is always "node".
+ and js.process.release.name == "node"
+ )
+
+
+def streaming_ready() -> bool | None:
+ if _fetcher:
+ return _fetcher.streaming_ready
+ else:
+ return None # no fetcher, return None to signify that
+
+
+async def wait_for_streaming_ready() -> bool:
+ if _fetcher:
+ await _fetcher.js_worker_ready_promise
+ return True
+ else:
+ return False
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/emscripten/request.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/emscripten/request.py
new file mode 100644
index 0000000000000000000000000000000000000000..e692e692bd0d38f6a0677992a6993fc68050dff3
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/emscripten/request.py
@@ -0,0 +1,22 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+from ..._base_connection import _TYPE_BODY
+
+
+@dataclass
+class EmscriptenRequest:
+ method: str
+ url: str
+ params: dict[str, str] | None = None
+ body: _TYPE_BODY | None = None
+ headers: dict[str, str] = field(default_factory=dict)
+ timeout: float = 0
+ decode_content: bool = True
+
+ def set_header(self, name: str, value: str) -> None:
+ self.headers[name.capitalize()] = value
+
+ def set_body(self, body: _TYPE_BODY | None) -> None:
+ self.body = body
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/emscripten/response.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/emscripten/response.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb1088a1826d089e1b603c51e85560b8583a3e3d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/emscripten/response.py
@@ -0,0 +1,277 @@
+from __future__ import annotations
+
+import json as _json
+import logging
+import typing
+from contextlib import contextmanager
+from dataclasses import dataclass
+from http.client import HTTPException as HTTPException
+from io import BytesIO, IOBase
+
+from ...exceptions import InvalidHeader, TimeoutError
+from ...response import BaseHTTPResponse
+from ...util.retry import Retry
+from .request import EmscriptenRequest
+
+if typing.TYPE_CHECKING:
+ from ..._base_connection import BaseHTTPConnection, BaseHTTPSConnection
+
+log = logging.getLogger(__name__)
+
+
+@dataclass
+class EmscriptenResponse:
+ status_code: int
+ headers: dict[str, str]
+ body: IOBase | bytes
+ request: EmscriptenRequest
+
+
+class EmscriptenHttpResponseWrapper(BaseHTTPResponse):
+ def __init__(
+ self,
+ internal_response: EmscriptenResponse,
+ url: str | None = None,
+ connection: BaseHTTPConnection | BaseHTTPSConnection | None = None,
+ ):
+ self._pool = None # set by pool class
+ self._body = None
+ self._response = internal_response
+ self._url = url
+ self._connection = connection
+ self._closed = False
+ super().__init__(
+ headers=internal_response.headers,
+ status=internal_response.status_code,
+ request_url=url,
+ version=0,
+ version_string="HTTP/?",
+ reason="",
+ decode_content=True,
+ )
+ self.length_remaining = self._init_length(self._response.request.method)
+ self.length_is_certain = False
+
+ @property
+ def url(self) -> str | None:
+ return self._url
+
+ @url.setter
+ def url(self, url: str | None) -> None:
+ self._url = url
+
+ @property
+ def connection(self) -> BaseHTTPConnection | BaseHTTPSConnection | None:
+ return self._connection
+
+ @property
+ def retries(self) -> Retry | None:
+ return self._retries
+
+ @retries.setter
+ def retries(self, retries: Retry | None) -> None:
+ # Override the request_url if retries has a redirect location.
+ self._retries = retries
+
+ def stream(
+ self, amt: int | None = 2**16, decode_content: bool | None = None
+ ) -> typing.Generator[bytes]:
+ """
+ A generator wrapper for the read() method. A call will block until
+ ``amt`` bytes have been read from the connection or until the
+ connection is closed.
+
+ :param amt:
+ How much of the content to read. The generator will return up to
+ much data per iteration, but may return less. This is particularly
+ likely when using compressed data. However, the empty string will
+ never be returned.
+
+ :param decode_content:
+ If True, will attempt to decode the body based on the
+ 'content-encoding' header.
+ """
+ while True:
+ data = self.read(amt=amt, decode_content=decode_content)
+
+ if data:
+ yield data
+ else:
+ break
+
+ def _init_length(self, request_method: str | None) -> int | None:
+ length: int | None
+ content_length: str | None = self.headers.get("content-length")
+
+ if content_length is not None:
+ try:
+ # RFC 7230 section 3.3.2 specifies multiple content lengths can
+ # be sent in a single Content-Length header
+ # (e.g. Content-Length: 42, 42). This line ensures the values
+ # are all valid ints and that as long as the `set` length is 1,
+ # all values are the same. Otherwise, the header is invalid.
+ lengths = {int(val) for val in content_length.split(",")}
+ if len(lengths) > 1:
+ raise InvalidHeader(
+ "Content-Length contained multiple "
+ "unmatching values (%s)" % content_length
+ )
+ length = lengths.pop()
+ except ValueError:
+ length = None
+ else:
+ if length < 0:
+ length = None
+
+ else: # if content_length is None
+ length = None
+
+ # Check for responses that shouldn't include a body
+ if (
+ self.status in (204, 304)
+ or 100 <= self.status < 200
+ or request_method == "HEAD"
+ ):
+ length = 0
+
+ return length
+
+ def read(
+ self,
+ amt: int | None = None,
+ decode_content: bool | None = None, # ignored because browser decodes always
+ cache_content: bool = False,
+ ) -> bytes:
+ if (
+ self._closed
+ or self._response is None
+ or (isinstance(self._response.body, IOBase) and self._response.body.closed)
+ ):
+ return b""
+
+ with self._error_catcher():
+ # body has been preloaded as a string by XmlHttpRequest
+ if not isinstance(self._response.body, IOBase):
+ self.length_remaining = len(self._response.body)
+ self.length_is_certain = True
+ # wrap body in IOStream
+ self._response.body = BytesIO(self._response.body)
+ if amt is not None and amt >= 0:
+ # don't cache partial content
+ cache_content = False
+ data = self._response.body.read(amt)
+ else: # read all we can (and cache it)
+ data = self._response.body.read()
+ if cache_content:
+ self._body = data
+ if self.length_remaining is not None:
+ self.length_remaining = max(self.length_remaining - len(data), 0)
+ if len(data) == 0 or (
+ self.length_is_certain and self.length_remaining == 0
+ ):
+ # definitely finished reading, close response stream
+ self._response.body.close()
+ return typing.cast(bytes, data)
+
+ def read_chunked(
+ self,
+ amt: int | None = None,
+ decode_content: bool | None = None,
+ ) -> typing.Generator[bytes]:
+ # chunked is handled by browser
+ while True:
+ bytes = self.read(amt, decode_content)
+ if not bytes:
+ break
+ yield bytes
+
+ def release_conn(self) -> None:
+ if not self._pool or not self._connection:
+ return None
+
+ self._pool._put_conn(self._connection)
+ self._connection = None
+
+ def drain_conn(self) -> None:
+ self.close()
+
+ @property
+ def data(self) -> bytes:
+ if self._body:
+ return self._body
+ else:
+ return self.read(cache_content=True)
+
+ def json(self) -> typing.Any:
+ """
+ Deserializes the body of the HTTP response as a Python object.
+
+ The body of the HTTP response must be encoded using UTF-8, as per
+ `RFC 8529 Section 8.1 `_.
+
+ To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to
+ your custom decoder instead.
+
+ If the body of the HTTP response is not decodable to UTF-8, a
+ `UnicodeDecodeError` will be raised. If the body of the HTTP response is not a
+ valid JSON document, a `json.JSONDecodeError` will be raised.
+
+ Read more :ref:`here `.
+
+ :returns: The body of the HTTP response as a Python object.
+ """
+ data = self.data.decode("utf-8")
+ return _json.loads(data)
+
+ def close(self) -> None:
+ if not self._closed:
+ if isinstance(self._response.body, IOBase):
+ self._response.body.close()
+ if self._connection:
+ self._connection.close()
+ self._connection = None
+ self._closed = True
+
+ @contextmanager
+ def _error_catcher(self) -> typing.Generator[None]:
+ """
+ Catch Emscripten specific exceptions thrown by fetch.py,
+ instead re-raising urllib3 variants, so that low-level exceptions
+ are not leaked in the high-level api.
+
+ On exit, release the connection back to the pool.
+ """
+ from .fetch import _RequestError, _TimeoutError # avoid circular import
+
+ clean_exit = False
+
+ try:
+ yield
+ # If no exception is thrown, we should avoid cleaning up
+ # unnecessarily.
+ clean_exit = True
+ except _TimeoutError as e:
+ raise TimeoutError(str(e))
+ except _RequestError as e:
+ raise HTTPException(str(e))
+ finally:
+ # If we didn't terminate cleanly, we need to throw away our
+ # connection.
+ if not clean_exit:
+ # The response may not be closed but we're not going to use it
+ # anymore so close it now
+ if (
+ isinstance(self._response.body, IOBase)
+ and not self._response.body.closed
+ ):
+ self._response.body.close()
+ # release the connection back to the pool
+ self.release_conn()
+ else:
+ # If we have read everything from the response stream,
+ # return the connection back to the pool.
+ if (
+ isinstance(self._response.body, IOBase)
+ and self._response.body.closed
+ ):
+ self.release_conn()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/pyopenssl.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/pyopenssl.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e05d3d785d53021a97a713cbdbb1f43708c9150
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/pyopenssl.py
@@ -0,0 +1,564 @@
+"""
+Module for using pyOpenSSL as a TLS backend. This module was relevant before
+the standard library ``ssl`` module supported SNI, but now that we've dropped
+support for Python 2.7 all relevant Python versions support SNI so
+**this module is no longer recommended**.
+
+This needs the following packages installed:
+
+* `pyOpenSSL`_ (tested with 16.0.0)
+* `cryptography`_ (minimum 1.3.4, from pyopenssl)
+* `idna`_ (minimum 2.0)
+
+However, pyOpenSSL depends on cryptography, so while we use all three directly here we
+end up having relatively few packages required.
+
+You can install them with the following command:
+
+.. code-block:: bash
+
+ $ python -m pip install pyopenssl cryptography idna
+
+To activate certificate checking, call
+:func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code
+before you begin making HTTP requests. This can be done in a ``sitecustomize``
+module, or at any other time before your application begins using ``urllib3``,
+like this:
+
+.. code-block:: python
+
+ try:
+ import urllib3.contrib.pyopenssl
+ urllib3.contrib.pyopenssl.inject_into_urllib3()
+ except ImportError:
+ pass
+
+.. _pyopenssl: https://www.pyopenssl.org
+.. _cryptography: https://cryptography.io
+.. _idna: https://github.com/kjd/idna
+"""
+
+from __future__ import annotations
+
+import OpenSSL.SSL # type: ignore[import-not-found]
+from cryptography import x509
+
+try:
+ from cryptography.x509 import UnsupportedExtension # type: ignore[attr-defined]
+except ImportError:
+ # UnsupportedExtension is gone in cryptography >= 2.1.0
+ class UnsupportedExtension(Exception): # type: ignore[no-redef]
+ pass
+
+
+import logging
+import ssl
+import typing
+from io import BytesIO
+from socket import socket as socket_cls
+from socket import timeout
+
+from .. import util
+
+if typing.TYPE_CHECKING:
+ from OpenSSL.crypto import X509 # type: ignore[import-not-found]
+
+
+__all__ = ["inject_into_urllib3", "extract_from_urllib3"]
+
+# Map from urllib3 to PyOpenSSL compatible parameter-values.
+_openssl_versions: dict[int, int] = {
+ util.ssl_.PROTOCOL_TLS: OpenSSL.SSL.SSLv23_METHOD, # type: ignore[attr-defined]
+ util.ssl_.PROTOCOL_TLS_CLIENT: OpenSSL.SSL.SSLv23_METHOD, # type: ignore[attr-defined]
+ ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD,
+}
+
+if hasattr(ssl, "PROTOCOL_TLSv1_1") and hasattr(OpenSSL.SSL, "TLSv1_1_METHOD"):
+ _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD
+
+if hasattr(ssl, "PROTOCOL_TLSv1_2") and hasattr(OpenSSL.SSL, "TLSv1_2_METHOD"):
+ _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD
+
+
+_stdlib_to_openssl_verify = {
+ ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,
+ ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,
+ ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER
+ + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
+}
+_openssl_to_stdlib_verify = {v: k for k, v in _stdlib_to_openssl_verify.items()}
+
+# The SSLvX values are the most likely to be missing in the future
+# but we check them all just to be sure.
+_OP_NO_SSLv2_OR_SSLv3: int = getattr(OpenSSL.SSL, "OP_NO_SSLv2", 0) | getattr(
+ OpenSSL.SSL, "OP_NO_SSLv3", 0
+)
+_OP_NO_TLSv1: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1", 0)
+_OP_NO_TLSv1_1: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_1", 0)
+_OP_NO_TLSv1_2: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_2", 0)
+_OP_NO_TLSv1_3: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_3", 0)
+
+_openssl_to_ssl_minimum_version: dict[int, int] = {
+ ssl.TLSVersion.MINIMUM_SUPPORTED: _OP_NO_SSLv2_OR_SSLv3,
+ ssl.TLSVersion.TLSv1: _OP_NO_SSLv2_OR_SSLv3,
+ ssl.TLSVersion.TLSv1_1: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1,
+ ssl.TLSVersion.TLSv1_2: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1,
+ ssl.TLSVersion.TLSv1_3: (
+ _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2
+ ),
+ ssl.TLSVersion.MAXIMUM_SUPPORTED: (
+ _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2
+ ),
+}
+_openssl_to_ssl_maximum_version: dict[int, int] = {
+ ssl.TLSVersion.MINIMUM_SUPPORTED: (
+ _OP_NO_SSLv2_OR_SSLv3
+ | _OP_NO_TLSv1
+ | _OP_NO_TLSv1_1
+ | _OP_NO_TLSv1_2
+ | _OP_NO_TLSv1_3
+ ),
+ ssl.TLSVersion.TLSv1: (
+ _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2 | _OP_NO_TLSv1_3
+ ),
+ ssl.TLSVersion.TLSv1_1: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_2 | _OP_NO_TLSv1_3,
+ ssl.TLSVersion.TLSv1_2: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_3,
+ ssl.TLSVersion.TLSv1_3: _OP_NO_SSLv2_OR_SSLv3,
+ ssl.TLSVersion.MAXIMUM_SUPPORTED: _OP_NO_SSLv2_OR_SSLv3,
+}
+
+# OpenSSL will only write 16K at a time
+SSL_WRITE_BLOCKSIZE = 16384
+
+orig_util_SSLContext = util.ssl_.SSLContext
+
+
+log = logging.getLogger(__name__)
+
+
+def inject_into_urllib3() -> None:
+ "Monkey-patch urllib3 with PyOpenSSL-backed SSL-support."
+
+ _validate_dependencies_met()
+
+ util.SSLContext = PyOpenSSLContext # type: ignore[assignment]
+ util.ssl_.SSLContext = PyOpenSSLContext # type: ignore[assignment]
+ util.IS_PYOPENSSL = True
+ util.ssl_.IS_PYOPENSSL = True
+
+
+def extract_from_urllib3() -> None:
+ "Undo monkey-patching by :func:`inject_into_urllib3`."
+
+ util.SSLContext = orig_util_SSLContext
+ util.ssl_.SSLContext = orig_util_SSLContext
+ util.IS_PYOPENSSL = False
+ util.ssl_.IS_PYOPENSSL = False
+
+
+def _validate_dependencies_met() -> None:
+ """
+ Verifies that PyOpenSSL's package-level dependencies have been met.
+ Throws `ImportError` if they are not met.
+ """
+ # Method added in `cryptography==1.1`; not available in older versions
+ from cryptography.x509.extensions import Extensions
+
+ if getattr(Extensions, "get_extension_for_class", None) is None:
+ raise ImportError(
+ "'cryptography' module missing required functionality. "
+ "Try upgrading to v1.3.4 or newer."
+ )
+
+ # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509
+ # attribute is only present on those versions.
+ from OpenSSL.crypto import X509
+
+ x509 = X509()
+ if getattr(x509, "_x509", None) is None:
+ raise ImportError(
+ "'pyOpenSSL' module missing required functionality. "
+ "Try upgrading to v0.14 or newer."
+ )
+
+
+def _dnsname_to_stdlib(name: str) -> str | None:
+ """
+ Converts a dNSName SubjectAlternativeName field to the form used by the
+ standard library on the given Python version.
+
+ Cryptography produces a dNSName as a unicode string that was idna-decoded
+ from ASCII bytes. We need to idna-encode that string to get it back, and
+ then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib
+ uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8).
+
+ If the name cannot be idna-encoded then we return None signalling that
+ the name given should be skipped.
+ """
+
+ def idna_encode(name: str) -> bytes | None:
+ """
+ Borrowed wholesale from the Python Cryptography Project. It turns out
+ that we can't just safely call `idna.encode`: it can explode for
+ wildcard names. This avoids that problem.
+ """
+ import idna
+
+ try:
+ for prefix in ["*.", "."]:
+ if name.startswith(prefix):
+ name = name[len(prefix) :]
+ return prefix.encode("ascii") + idna.encode(name)
+ return idna.encode(name)
+ except idna.core.IDNAError:
+ return None
+
+ # Don't send IPv6 addresses through the IDNA encoder.
+ if ":" in name:
+ return name
+
+ encoded_name = idna_encode(name)
+ if encoded_name is None:
+ return None
+ return encoded_name.decode("utf-8")
+
+
+def get_subj_alt_name(peer_cert: X509) -> list[tuple[str, str]]:
+ """
+ Given an PyOpenSSL certificate, provides all the subject alternative names.
+ """
+ cert = peer_cert.to_cryptography()
+
+ # We want to find the SAN extension. Ask Cryptography to locate it (it's
+ # faster than looping in Python)
+ try:
+ ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value
+ except x509.ExtensionNotFound:
+ # No such extension, return the empty list.
+ return []
+ except (
+ x509.DuplicateExtension,
+ UnsupportedExtension,
+ x509.UnsupportedGeneralNameType,
+ UnicodeError,
+ ) as e:
+ # A problem has been found with the quality of the certificate. Assume
+ # no SAN field is present.
+ log.warning(
+ "A problem was encountered with the certificate that prevented "
+ "urllib3 from finding the SubjectAlternativeName field. This can "
+ "affect certificate validation. The error was %s",
+ e,
+ )
+ return []
+
+ # We want to return dNSName and iPAddress fields. We need to cast the IPs
+ # back to strings because the match_hostname function wants them as
+ # strings.
+ # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8
+ # decoded. This is pretty frustrating, but that's what the standard library
+ # does with certificates, and so we need to attempt to do the same.
+ # We also want to skip over names which cannot be idna encoded.
+ names = [
+ ("DNS", name)
+ for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName))
+ if name is not None
+ ]
+ names.extend(
+ ("IP Address", str(name)) for name in ext.get_values_for_type(x509.IPAddress)
+ )
+
+ return names
+
+
+class WrappedSocket:
+ """API-compatibility wrapper for Python OpenSSL's Connection-class."""
+
+ def __init__(
+ self,
+ connection: OpenSSL.SSL.Connection,
+ socket: socket_cls,
+ suppress_ragged_eofs: bool = True,
+ ) -> None:
+ self.connection = connection
+ self.socket = socket
+ self.suppress_ragged_eofs = suppress_ragged_eofs
+ self._io_refs = 0
+ self._closed = False
+
+ def fileno(self) -> int:
+ return self.socket.fileno()
+
+ # Copy-pasted from Python 3.5 source code
+ def _decref_socketios(self) -> None:
+ if self._io_refs > 0:
+ self._io_refs -= 1
+ if self._closed:
+ self.close()
+
+ def recv(self, *args: typing.Any, **kwargs: typing.Any) -> bytes:
+ try:
+ data = self.connection.recv(*args, **kwargs)
+ except OpenSSL.SSL.SysCallError as e:
+ if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"):
+ return b""
+ else:
+ raise OSError(e.args[0], str(e)) from e
+ except OpenSSL.SSL.ZeroReturnError:
+ if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
+ return b""
+ else:
+ raise
+ except OpenSSL.SSL.WantReadError as e:
+ if not util.wait_for_read(self.socket, self.socket.gettimeout()):
+ raise timeout("The read operation timed out") from e
+ else:
+ return self.recv(*args, **kwargs)
+
+ # TLS 1.3 post-handshake authentication
+ except OpenSSL.SSL.Error as e:
+ raise ssl.SSLError(f"read error: {e!r}") from e
+ else:
+ return data # type: ignore[no-any-return]
+
+ def recv_into(self, *args: typing.Any, **kwargs: typing.Any) -> int:
+ try:
+ return self.connection.recv_into(*args, **kwargs) # type: ignore[no-any-return]
+ except OpenSSL.SSL.SysCallError as e:
+ if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"):
+ return 0
+ else:
+ raise OSError(e.args[0], str(e)) from e
+ except OpenSSL.SSL.ZeroReturnError:
+ if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
+ return 0
+ else:
+ raise
+ except OpenSSL.SSL.WantReadError as e:
+ if not util.wait_for_read(self.socket, self.socket.gettimeout()):
+ raise timeout("The read operation timed out") from e
+ else:
+ return self.recv_into(*args, **kwargs)
+
+ # TLS 1.3 post-handshake authentication
+ except OpenSSL.SSL.Error as e:
+ raise ssl.SSLError(f"read error: {e!r}") from e
+
+ def settimeout(self, timeout: float) -> None:
+ return self.socket.settimeout(timeout)
+
+ def _send_until_done(self, data: bytes) -> int:
+ while True:
+ try:
+ return self.connection.send(data) # type: ignore[no-any-return]
+ except OpenSSL.SSL.WantWriteError as e:
+ if not util.wait_for_write(self.socket, self.socket.gettimeout()):
+ raise timeout() from e
+ continue
+ except OpenSSL.SSL.SysCallError as e:
+ raise OSError(e.args[0], str(e)) from e
+
+ def sendall(self, data: bytes) -> None:
+ total_sent = 0
+ while total_sent < len(data):
+ sent = self._send_until_done(
+ data[total_sent : total_sent + SSL_WRITE_BLOCKSIZE]
+ )
+ total_sent += sent
+
+ def shutdown(self, how: int) -> None:
+ try:
+ self.connection.shutdown()
+ except OpenSSL.SSL.Error as e:
+ raise ssl.SSLError(f"shutdown error: {e!r}") from e
+
+ def close(self) -> None:
+ self._closed = True
+ if self._io_refs <= 0:
+ self._real_close()
+
+ def _real_close(self) -> None:
+ try:
+ return self.connection.close() # type: ignore[no-any-return]
+ except OpenSSL.SSL.Error:
+ return
+
+ def getpeercert(
+ self, binary_form: bool = False
+ ) -> dict[str, list[typing.Any]] | None:
+ x509 = self.connection.get_peer_certificate()
+
+ if not x509:
+ return x509 # type: ignore[no-any-return]
+
+ if binary_form:
+ return OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509) # type: ignore[no-any-return]
+
+ return {
+ "subject": ((("commonName", x509.get_subject().CN),),), # type: ignore[dict-item]
+ "subjectAltName": get_subj_alt_name(x509),
+ }
+
+ def version(self) -> str:
+ return self.connection.get_protocol_version_name() # type: ignore[no-any-return]
+
+ def selected_alpn_protocol(self) -> str | None:
+ alpn_proto = self.connection.get_alpn_proto_negotiated()
+ return alpn_proto.decode() if alpn_proto else None
+
+
+WrappedSocket.makefile = socket_cls.makefile # type: ignore[attr-defined]
+
+
+class PyOpenSSLContext:
+ """
+ I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible
+ for translating the interface of the standard library ``SSLContext`` object
+ to calls into PyOpenSSL.
+ """
+
+ def __init__(self, protocol: int) -> None:
+ self.protocol = _openssl_versions[protocol]
+ self._ctx = OpenSSL.SSL.Context(self.protocol)
+ self._options = 0
+ self.check_hostname = False
+ self._minimum_version: int = ssl.TLSVersion.MINIMUM_SUPPORTED
+ self._maximum_version: int = ssl.TLSVersion.MAXIMUM_SUPPORTED
+ self._verify_flags: int = ssl.VERIFY_X509_TRUSTED_FIRST
+
+ @property
+ def options(self) -> int:
+ return self._options
+
+ @options.setter
+ def options(self, value: int) -> None:
+ self._options = value
+ self._set_ctx_options()
+
+ @property
+ def verify_flags(self) -> int:
+ return self._verify_flags
+
+ @verify_flags.setter
+ def verify_flags(self, value: int) -> None:
+ self._verify_flags = value
+ self._ctx.get_cert_store().set_flags(self._verify_flags)
+
+ @property
+ def verify_mode(self) -> int:
+ return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()]
+
+ @verify_mode.setter
+ def verify_mode(self, value: ssl.VerifyMode) -> None:
+ self._ctx.set_verify(_stdlib_to_openssl_verify[value], _verify_callback)
+
+ def set_default_verify_paths(self) -> None:
+ self._ctx.set_default_verify_paths()
+
+ def set_ciphers(self, ciphers: bytes | str) -> None:
+ if isinstance(ciphers, str):
+ ciphers = ciphers.encode("utf-8")
+ self._ctx.set_cipher_list(ciphers)
+
+ def load_verify_locations(
+ self,
+ cafile: str | None = None,
+ capath: str | None = None,
+ cadata: bytes | None = None,
+ ) -> None:
+ if cafile is not None:
+ cafile = cafile.encode("utf-8") # type: ignore[assignment]
+ if capath is not None:
+ capath = capath.encode("utf-8") # type: ignore[assignment]
+ try:
+ self._ctx.load_verify_locations(cafile, capath)
+ if cadata is not None:
+ self._ctx.load_verify_locations(BytesIO(cadata))
+ except OpenSSL.SSL.Error as e:
+ raise ssl.SSLError(f"unable to load trusted certificates: {e!r}") from e
+
+ def load_cert_chain(
+ self,
+ certfile: str,
+ keyfile: str | None = None,
+ password: str | None = None,
+ ) -> None:
+ try:
+ self._ctx.use_certificate_chain_file(certfile)
+ if password is not None:
+ if not isinstance(password, bytes):
+ password = password.encode("utf-8") # type: ignore[assignment]
+ self._ctx.set_passwd_cb(lambda *_: password)
+ self._ctx.use_privatekey_file(keyfile or certfile)
+ except OpenSSL.SSL.Error as e:
+ raise ssl.SSLError(f"Unable to load certificate chain: {e!r}") from e
+
+ def set_alpn_protocols(self, protocols: list[bytes | str]) -> None:
+ protocols = [util.util.to_bytes(p, "ascii") for p in protocols]
+ return self._ctx.set_alpn_protos(protocols) # type: ignore[no-any-return]
+
+ def wrap_socket(
+ self,
+ sock: socket_cls,
+ server_side: bool = False,
+ do_handshake_on_connect: bool = True,
+ suppress_ragged_eofs: bool = True,
+ server_hostname: bytes | str | None = None,
+ ) -> WrappedSocket:
+ cnx = OpenSSL.SSL.Connection(self._ctx, sock)
+
+ # If server_hostname is an IP, don't use it for SNI, per RFC6066 Section 3
+ if server_hostname and not util.ssl_.is_ipaddress(server_hostname):
+ if isinstance(server_hostname, str):
+ server_hostname = server_hostname.encode("utf-8")
+ cnx.set_tlsext_host_name(server_hostname)
+
+ cnx.set_connect_state()
+
+ while True:
+ try:
+ cnx.do_handshake()
+ except OpenSSL.SSL.WantReadError as e:
+ if not util.wait_for_read(sock, sock.gettimeout()):
+ raise timeout("select timed out") from e
+ continue
+ except OpenSSL.SSL.Error as e:
+ raise ssl.SSLError(f"bad handshake: {e!r}") from e
+ break
+
+ return WrappedSocket(cnx, sock)
+
+ def _set_ctx_options(self) -> None:
+ self._ctx.set_options(
+ self._options
+ | _openssl_to_ssl_minimum_version[self._minimum_version]
+ | _openssl_to_ssl_maximum_version[self._maximum_version]
+ )
+
+ @property
+ def minimum_version(self) -> int:
+ return self._minimum_version
+
+ @minimum_version.setter
+ def minimum_version(self, minimum_version: int) -> None:
+ self._minimum_version = minimum_version
+ self._set_ctx_options()
+
+ @property
+ def maximum_version(self) -> int:
+ return self._maximum_version
+
+ @maximum_version.setter
+ def maximum_version(self, maximum_version: int) -> None:
+ self._maximum_version = maximum_version
+ self._set_ctx_options()
+
+
+def _verify_callback(
+ cnx: OpenSSL.SSL.Connection,
+ x509: X509,
+ err_no: int,
+ err_depth: int,
+ return_code: int,
+) -> bool:
+ return err_no == 0
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/socks.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/socks.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3239b569d93c6139f9c6a86118a5884daf1dabd
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/contrib/socks.py
@@ -0,0 +1,228 @@
+"""
+This module contains provisional support for SOCKS proxies from within
+urllib3. This module supports SOCKS4, SOCKS4A (an extension of SOCKS4), and
+SOCKS5. To enable its functionality, either install PySocks or install this
+module with the ``socks`` extra.
+
+The SOCKS implementation supports the full range of urllib3 features. It also
+supports the following SOCKS features:
+
+- SOCKS4A (``proxy_url='socks4a://...``)
+- SOCKS4 (``proxy_url='socks4://...``)
+- SOCKS5 with remote DNS (``proxy_url='socks5h://...``)
+- SOCKS5 with local DNS (``proxy_url='socks5://...``)
+- Usernames and passwords for the SOCKS proxy
+
+.. note::
+ It is recommended to use ``socks5h://`` or ``socks4a://`` schemes in
+ your ``proxy_url`` to ensure that DNS resolution is done from the remote
+ server instead of client-side when connecting to a domain name.
+
+SOCKS4 supports IPv4 and domain names with the SOCKS4A extension. SOCKS5
+supports IPv4, IPv6, and domain names.
+
+When connecting to a SOCKS4 proxy the ``username`` portion of the ``proxy_url``
+will be sent as the ``userid`` section of the SOCKS request:
+
+.. code-block:: python
+
+ proxy_url="socks4a://@proxy-host"
+
+When connecting to a SOCKS5 proxy the ``username`` and ``password`` portion
+of the ``proxy_url`` will be sent as the username/password to authenticate
+with the proxy:
+
+.. code-block:: python
+
+ proxy_url="socks5h://:@proxy-host"
+
+"""
+
+from __future__ import annotations
+
+try:
+ import socks # type: ignore[import-untyped]
+except ImportError:
+ import warnings
+
+ from ..exceptions import DependencyWarning
+
+ warnings.warn(
+ (
+ "SOCKS support in urllib3 requires the installation of optional "
+ "dependencies: specifically, PySocks. For more information, see "
+ "https://urllib3.readthedocs.io/en/latest/advanced-usage.html#socks-proxies"
+ ),
+ DependencyWarning,
+ )
+ raise
+
+import typing
+from socket import timeout as SocketTimeout
+
+from ..connection import HTTPConnection, HTTPSConnection
+from ..connectionpool import HTTPConnectionPool, HTTPSConnectionPool
+from ..exceptions import ConnectTimeoutError, NewConnectionError
+from ..poolmanager import PoolManager
+from ..util.url import parse_url
+
+try:
+ import ssl
+except ImportError:
+ ssl = None # type: ignore[assignment]
+
+
+class _TYPE_SOCKS_OPTIONS(typing.TypedDict):
+ socks_version: int
+ proxy_host: str | None
+ proxy_port: str | None
+ username: str | None
+ password: str | None
+ rdns: bool
+
+
+class SOCKSConnection(HTTPConnection):
+ """
+ A plain-text HTTP connection that connects via a SOCKS proxy.
+ """
+
+ def __init__(
+ self,
+ _socks_options: _TYPE_SOCKS_OPTIONS,
+ *args: typing.Any,
+ **kwargs: typing.Any,
+ ) -> None:
+ self._socks_options = _socks_options
+ super().__init__(*args, **kwargs)
+
+ def _new_conn(self) -> socks.socksocket:
+ """
+ Establish a new connection via the SOCKS proxy.
+ """
+ extra_kw: dict[str, typing.Any] = {}
+ if self.source_address:
+ extra_kw["source_address"] = self.source_address
+
+ if self.socket_options:
+ extra_kw["socket_options"] = self.socket_options
+
+ try:
+ conn = socks.create_connection(
+ (self.host, self.port),
+ proxy_type=self._socks_options["socks_version"],
+ proxy_addr=self._socks_options["proxy_host"],
+ proxy_port=self._socks_options["proxy_port"],
+ proxy_username=self._socks_options["username"],
+ proxy_password=self._socks_options["password"],
+ proxy_rdns=self._socks_options["rdns"],
+ timeout=self.timeout,
+ **extra_kw,
+ )
+
+ except SocketTimeout as e:
+ raise ConnectTimeoutError(
+ self,
+ f"Connection to {self.host} timed out. (connect timeout={self.timeout})",
+ ) from e
+
+ except socks.ProxyError as e:
+ # This is fragile as hell, but it seems to be the only way to raise
+ # useful errors here.
+ if e.socket_err:
+ error = e.socket_err
+ if isinstance(error, SocketTimeout):
+ raise ConnectTimeoutError(
+ self,
+ f"Connection to {self.host} timed out. (connect timeout={self.timeout})",
+ ) from e
+ else:
+ # Adding `from e` messes with coverage somehow, so it's omitted.
+ # See #2386.
+ raise NewConnectionError(
+ self, f"Failed to establish a new connection: {error}"
+ )
+ else:
+ raise NewConnectionError(
+ self, f"Failed to establish a new connection: {e}"
+ ) from e
+
+ except OSError as e: # Defensive: PySocks should catch all these.
+ raise NewConnectionError(
+ self, f"Failed to establish a new connection: {e}"
+ ) from e
+
+ return conn
+
+
+# We don't need to duplicate the Verified/Unverified distinction from
+# urllib3/connection.py here because the HTTPSConnection will already have been
+# correctly set to either the Verified or Unverified form by that module. This
+# means the SOCKSHTTPSConnection will automatically be the correct type.
+class SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection):
+ pass
+
+
+class SOCKSHTTPConnectionPool(HTTPConnectionPool):
+ ConnectionCls = SOCKSConnection
+
+
+class SOCKSHTTPSConnectionPool(HTTPSConnectionPool):
+ ConnectionCls = SOCKSHTTPSConnection
+
+
+class SOCKSProxyManager(PoolManager):
+ """
+ A version of the urllib3 ProxyManager that routes connections via the
+ defined SOCKS proxy.
+ """
+
+ pool_classes_by_scheme = {
+ "http": SOCKSHTTPConnectionPool,
+ "https": SOCKSHTTPSConnectionPool,
+ }
+
+ def __init__(
+ self,
+ proxy_url: str,
+ username: str | None = None,
+ password: str | None = None,
+ num_pools: int = 10,
+ headers: typing.Mapping[str, str] | None = None,
+ **connection_pool_kw: typing.Any,
+ ):
+ parsed = parse_url(proxy_url)
+
+ if username is None and password is None and parsed.auth is not None:
+ split = parsed.auth.split(":")
+ if len(split) == 2:
+ username, password = split
+ if parsed.scheme == "socks5":
+ socks_version = socks.PROXY_TYPE_SOCKS5
+ rdns = False
+ elif parsed.scheme == "socks5h":
+ socks_version = socks.PROXY_TYPE_SOCKS5
+ rdns = True
+ elif parsed.scheme == "socks4":
+ socks_version = socks.PROXY_TYPE_SOCKS4
+ rdns = False
+ elif parsed.scheme == "socks4a":
+ socks_version = socks.PROXY_TYPE_SOCKS4
+ rdns = True
+ else:
+ raise ValueError(f"Unable to determine SOCKS version from {proxy_url}")
+
+ self.proxy_url = proxy_url
+
+ socks_options = {
+ "socks_version": socks_version,
+ "proxy_host": parsed.host,
+ "proxy_port": parsed.port,
+ "username": username,
+ "password": password,
+ "rdns": rdns,
+ }
+ connection_pool_kw["_socks_options"] = socks_options
+
+ super().__init__(num_pools, headers, **connection_pool_kw)
+
+ self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/exceptions.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..58723faeb0ca7e5d8e3ba319f8d5acc79c91409c
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/exceptions.py
@@ -0,0 +1,335 @@
+from __future__ import annotations
+
+import socket
+import typing
+import warnings
+from email.errors import MessageDefect
+from http.client import IncompleteRead as httplib_IncompleteRead
+
+if typing.TYPE_CHECKING:
+ from .connection import HTTPConnection
+ from .connectionpool import ConnectionPool
+ from .response import HTTPResponse
+ from .util.retry import Retry
+
+# Base Exceptions
+
+
+class HTTPError(Exception):
+ """Base exception used by this module."""
+
+
+class HTTPWarning(Warning):
+ """Base warning used by this module."""
+
+
+_TYPE_REDUCE_RESULT = tuple[typing.Callable[..., object], tuple[object, ...]]
+
+
+class PoolError(HTTPError):
+ """Base exception for errors caused within a pool."""
+
+ def __init__(self, pool: ConnectionPool, message: str) -> None:
+ self.pool = pool
+ self._message = message
+ super().__init__(f"{pool}: {message}")
+
+ def __reduce__(self) -> _TYPE_REDUCE_RESULT:
+ # For pickling purposes.
+ return self.__class__, (None, self._message)
+
+
+class RequestError(PoolError):
+ """Base exception for PoolErrors that have associated URLs."""
+
+ def __init__(self, pool: ConnectionPool, url: str | None, message: str) -> None:
+ self.url = url
+ super().__init__(pool, message)
+
+ def __reduce__(self) -> _TYPE_REDUCE_RESULT:
+ # For pickling purposes.
+ return self.__class__, (None, self.url, self._message)
+
+
+class SSLError(HTTPError):
+ """Raised when SSL certificate fails in an HTTPS connection."""
+
+
+class ProxyError(HTTPError):
+ """Raised when the connection to a proxy fails."""
+
+ # The original error is also available as __cause__.
+ original_error: Exception
+
+ def __init__(self, message: str, error: Exception) -> None:
+ super().__init__(message, error)
+ self.original_error = error
+
+
+class DecodeError(HTTPError):
+ """Raised when automatic decoding based on Content-Type fails."""
+
+
+class ProtocolError(HTTPError):
+ """Raised when something unexpected happens mid-request/response."""
+
+
+#: Renamed to ProtocolError but aliased for backwards compatibility.
+ConnectionError = ProtocolError
+
+
+# Leaf Exceptions
+
+
+class MaxRetryError(RequestError):
+ """Raised when the maximum number of retries is exceeded.
+
+ :param pool: The connection pool
+ :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool`
+ :param str url: The requested Url
+ :param reason: The underlying error
+ :type reason: :class:`Exception`
+
+ """
+
+ def __init__(
+ self, pool: ConnectionPool, url: str | None, reason: Exception | None = None
+ ) -> None:
+ self.reason = reason
+
+ message = f"Max retries exceeded with url: {url} (Caused by {reason!r})"
+
+ super().__init__(pool, url, message)
+
+ def __reduce__(self) -> _TYPE_REDUCE_RESULT:
+ # For pickling purposes.
+ return self.__class__, (None, self.url, self.reason)
+
+
+class HostChangedError(RequestError):
+ """Raised when an existing pool gets a request for a foreign host."""
+
+ def __init__(
+ self, pool: ConnectionPool, url: str, retries: Retry | int = 3
+ ) -> None:
+ message = f"Tried to open a foreign host with url: {url}"
+ super().__init__(pool, url, message)
+ self.retries = retries
+
+
+class TimeoutStateError(HTTPError):
+ """Raised when passing an invalid state to a timeout"""
+
+
+class TimeoutError(HTTPError):
+ """Raised when a socket timeout error occurs.
+
+ Catching this error will catch both :exc:`ReadTimeoutErrors
+ ` and :exc:`ConnectTimeoutErrors `.
+ """
+
+
+class ReadTimeoutError(TimeoutError, RequestError):
+ """Raised when a socket timeout occurs while receiving data from a server"""
+
+
+# This timeout error does not have a URL attached and needs to inherit from the
+# base HTTPError
+class ConnectTimeoutError(TimeoutError):
+ """Raised when a socket timeout occurs while connecting to a server"""
+
+
+class NewConnectionError(ConnectTimeoutError, HTTPError):
+ """Raised when we fail to establish a new connection. Usually ECONNREFUSED."""
+
+ def __init__(self, conn: HTTPConnection, message: str) -> None:
+ self.conn = conn
+ self._message = message
+ super().__init__(f"{conn}: {message}")
+
+ def __reduce__(self) -> _TYPE_REDUCE_RESULT:
+ # For pickling purposes.
+ return self.__class__, (None, self._message)
+
+ @property
+ def pool(self) -> HTTPConnection:
+ warnings.warn(
+ "The 'pool' property is deprecated and will be removed "
+ "in urllib3 v2.1.0. Use 'conn' instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+ return self.conn
+
+
+class NameResolutionError(NewConnectionError):
+ """Raised when host name resolution fails."""
+
+ def __init__(self, host: str, conn: HTTPConnection, reason: socket.gaierror):
+ message = f"Failed to resolve '{host}' ({reason})"
+ self._host = host
+ self._reason = reason
+ super().__init__(conn, message)
+
+ def __reduce__(self) -> _TYPE_REDUCE_RESULT:
+ # For pickling purposes.
+ return self.__class__, (self._host, None, self._reason)
+
+
+class EmptyPoolError(PoolError):
+ """Raised when a pool runs out of connections and no more are allowed."""
+
+
+class FullPoolError(PoolError):
+ """Raised when we try to add a connection to a full pool in blocking mode."""
+
+
+class ClosedPoolError(PoolError):
+ """Raised when a request enters a pool after the pool has been closed."""
+
+
+class LocationValueError(ValueError, HTTPError):
+ """Raised when there is something wrong with a given URL input."""
+
+
+class LocationParseError(LocationValueError):
+ """Raised when get_host or similar fails to parse the URL input."""
+
+ def __init__(self, location: str) -> None:
+ message = f"Failed to parse: {location}"
+ super().__init__(message)
+
+ self.location = location
+
+
+class URLSchemeUnknown(LocationValueError):
+ """Raised when a URL input has an unsupported scheme."""
+
+ def __init__(self, scheme: str):
+ message = f"Not supported URL scheme {scheme}"
+ super().__init__(message)
+
+ self.scheme = scheme
+
+
+class ResponseError(HTTPError):
+ """Used as a container for an error reason supplied in a MaxRetryError."""
+
+ GENERIC_ERROR = "too many error responses"
+ SPECIFIC_ERROR = "too many {status_code} error responses"
+
+
+class SecurityWarning(HTTPWarning):
+ """Warned when performing security reducing actions"""
+
+
+class InsecureRequestWarning(SecurityWarning):
+ """Warned when making an unverified HTTPS request."""
+
+
+class NotOpenSSLWarning(SecurityWarning):
+ """Warned when using unsupported SSL library"""
+
+
+class SystemTimeWarning(SecurityWarning):
+ """Warned when system time is suspected to be wrong"""
+
+
+class InsecurePlatformWarning(SecurityWarning):
+ """Warned when certain TLS/SSL configuration is not available on a platform."""
+
+
+class DependencyWarning(HTTPWarning):
+ """
+ Warned when an attempt is made to import a module with missing optional
+ dependencies.
+ """
+
+
+class ResponseNotChunked(ProtocolError, ValueError):
+ """Response needs to be chunked in order to read it as chunks."""
+
+
+class BodyNotHttplibCompatible(HTTPError):
+ """
+ Body should be :class:`http.client.HTTPResponse` like
+ (have an fp attribute which returns raw chunks) for read_chunked().
+ """
+
+
+class IncompleteRead(HTTPError, httplib_IncompleteRead):
+ """
+ Response length doesn't match expected Content-Length
+
+ Subclass of :class:`http.client.IncompleteRead` to allow int value
+ for ``partial`` to avoid creating large objects on streamed reads.
+ """
+
+ partial: int # type: ignore[assignment]
+ expected: int
+
+ def __init__(self, partial: int, expected: int) -> None:
+ self.partial = partial
+ self.expected = expected
+
+ def __repr__(self) -> str:
+ return "IncompleteRead(%i bytes read, %i more expected)" % (
+ self.partial,
+ self.expected,
+ )
+
+
+class InvalidChunkLength(HTTPError, httplib_IncompleteRead):
+ """Invalid chunk length in a chunked response."""
+
+ def __init__(self, response: HTTPResponse, length: bytes) -> None:
+ self.partial: int = response.tell() # type: ignore[assignment]
+ self.expected: int | None = response.length_remaining
+ self.response = response
+ self.length = length
+
+ def __repr__(self) -> str:
+ return "InvalidChunkLength(got length %r, %i bytes read)" % (
+ self.length,
+ self.partial,
+ )
+
+
+class InvalidHeader(HTTPError):
+ """The header provided was somehow invalid."""
+
+
+class ProxySchemeUnknown(AssertionError, URLSchemeUnknown):
+ """ProxyManager does not support the supplied scheme"""
+
+ # TODO(t-8ch): Stop inheriting from AssertionError in v2.0.
+
+ def __init__(self, scheme: str | None) -> None:
+ # 'localhost' is here because our URL parser parses
+ # localhost:8080 -> scheme=localhost, remove if we fix this.
+ if scheme == "localhost":
+ scheme = None
+ if scheme is None:
+ message = "Proxy URL had no scheme, should start with http:// or https://"
+ else:
+ message = f"Proxy URL had unsupported scheme {scheme}, should use http:// or https://"
+ super().__init__(message)
+
+
+class ProxySchemeUnsupported(ValueError):
+ """Fetching HTTPS resources through HTTPS proxies is unsupported"""
+
+
+class HeaderParsingError(HTTPError):
+ """Raised by assert_header_parsing, but we convert it to a log.warning statement."""
+
+ def __init__(
+ self, defects: list[MessageDefect], unparsed_data: bytes | str | None
+ ) -> None:
+ message = f"{defects or 'Unknown'}, unparsed data: {unparsed_data!r}"
+ super().__init__(message)
+
+
+class UnrewindableBodyError(HTTPError):
+ """urllib3 encountered an error when trying to rewind a body"""
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/fields.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/fields.py
new file mode 100644
index 0000000000000000000000000000000000000000..97c4730cff0df570e1ab47f77e6aa879ec3c36e7
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/fields.py
@@ -0,0 +1,341 @@
+from __future__ import annotations
+
+import email.utils
+import mimetypes
+import typing
+
+_TYPE_FIELD_VALUE = typing.Union[str, bytes]
+_TYPE_FIELD_VALUE_TUPLE = typing.Union[
+ _TYPE_FIELD_VALUE,
+ tuple[str, _TYPE_FIELD_VALUE],
+ tuple[str, _TYPE_FIELD_VALUE, str],
+]
+
+
+def guess_content_type(
+ filename: str | None, default: str = "application/octet-stream"
+) -> str:
+ """
+ Guess the "Content-Type" of a file.
+
+ :param filename:
+ The filename to guess the "Content-Type" of using :mod:`mimetypes`.
+ :param default:
+ If no "Content-Type" can be guessed, default to `default`.
+ """
+ if filename:
+ return mimetypes.guess_type(filename)[0] or default
+ return default
+
+
+def format_header_param_rfc2231(name: str, value: _TYPE_FIELD_VALUE) -> str:
+ """
+ Helper function to format and quote a single header parameter using the
+ strategy defined in RFC 2231.
+
+ Particularly useful for header parameters which might contain
+ non-ASCII values, like file names. This follows
+ `RFC 2388 Section 4.4 `_.
+
+ :param name:
+ The name of the parameter, a string expected to be ASCII only.
+ :param value:
+ The value of the parameter, provided as ``bytes`` or `str``.
+ :returns:
+ An RFC-2231-formatted unicode string.
+
+ .. deprecated:: 2.0.0
+ Will be removed in urllib3 v2.1.0. This is not valid for
+ ``multipart/form-data`` header parameters.
+ """
+ import warnings
+
+ warnings.warn(
+ "'format_header_param_rfc2231' is deprecated and will be "
+ "removed in urllib3 v2.1.0. This is not valid for "
+ "multipart/form-data header parameters.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+ if isinstance(value, bytes):
+ value = value.decode("utf-8")
+
+ if not any(ch in value for ch in '"\\\r\n'):
+ result = f'{name}="{value}"'
+ try:
+ result.encode("ascii")
+ except (UnicodeEncodeError, UnicodeDecodeError):
+ pass
+ else:
+ return result
+
+ value = email.utils.encode_rfc2231(value, "utf-8")
+ value = f"{name}*={value}"
+
+ return value
+
+
+def format_multipart_header_param(name: str, value: _TYPE_FIELD_VALUE) -> str:
+ """
+ Format and quote a single multipart header parameter.
+
+ This follows the `WHATWG HTML Standard`_ as of 2021/06/10, matching
+ the behavior of current browser and curl versions. Values are
+ assumed to be UTF-8. The ``\\n``, ``\\r``, and ``"`` characters are
+ percent encoded.
+
+ .. _WHATWG HTML Standard:
+ https://html.spec.whatwg.org/multipage/
+ form-control-infrastructure.html#multipart-form-data
+
+ :param name:
+ The name of the parameter, an ASCII-only ``str``.
+ :param value:
+ The value of the parameter, a ``str`` or UTF-8 encoded
+ ``bytes``.
+ :returns:
+ A string ``name="value"`` with the escaped value.
+
+ .. versionchanged:: 2.0.0
+ Matches the WHATWG HTML Standard as of 2021/06/10. Control
+ characters are no longer percent encoded.
+
+ .. versionchanged:: 2.0.0
+ Renamed from ``format_header_param_html5`` and
+ ``format_header_param``. The old names will be removed in
+ urllib3 v2.1.0.
+ """
+ if isinstance(value, bytes):
+ value = value.decode("utf-8")
+
+ # percent encode \n \r "
+ value = value.translate({10: "%0A", 13: "%0D", 34: "%22"})
+ return f'{name}="{value}"'
+
+
+def format_header_param_html5(name: str, value: _TYPE_FIELD_VALUE) -> str:
+ """
+ .. deprecated:: 2.0.0
+ Renamed to :func:`format_multipart_header_param`. Will be
+ removed in urllib3 v2.1.0.
+ """
+ import warnings
+
+ warnings.warn(
+ "'format_header_param_html5' has been renamed to "
+ "'format_multipart_header_param'. The old name will be "
+ "removed in urllib3 v2.1.0.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return format_multipart_header_param(name, value)
+
+
+def format_header_param(name: str, value: _TYPE_FIELD_VALUE) -> str:
+ """
+ .. deprecated:: 2.0.0
+ Renamed to :func:`format_multipart_header_param`. Will be
+ removed in urllib3 v2.1.0.
+ """
+ import warnings
+
+ warnings.warn(
+ "'format_header_param' has been renamed to "
+ "'format_multipart_header_param'. The old name will be "
+ "removed in urllib3 v2.1.0.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return format_multipart_header_param(name, value)
+
+
+class RequestField:
+ """
+ A data container for request body parameters.
+
+ :param name:
+ The name of this request field. Must be unicode.
+ :param data:
+ The data/value body.
+ :param filename:
+ An optional filename of the request field. Must be unicode.
+ :param headers:
+ An optional dict-like object of headers to initially use for the field.
+
+ .. versionchanged:: 2.0.0
+ The ``header_formatter`` parameter is deprecated and will
+ be removed in urllib3 v2.1.0.
+ """
+
+ def __init__(
+ self,
+ name: str,
+ data: _TYPE_FIELD_VALUE,
+ filename: str | None = None,
+ headers: typing.Mapping[str, str] | None = None,
+ header_formatter: typing.Callable[[str, _TYPE_FIELD_VALUE], str] | None = None,
+ ):
+ self._name = name
+ self._filename = filename
+ self.data = data
+ self.headers: dict[str, str | None] = {}
+ if headers:
+ self.headers = dict(headers)
+
+ if header_formatter is not None:
+ import warnings
+
+ warnings.warn(
+ "The 'header_formatter' parameter is deprecated and "
+ "will be removed in urllib3 v2.1.0.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ self.header_formatter = header_formatter
+ else:
+ self.header_formatter = format_multipart_header_param
+
+ @classmethod
+ def from_tuples(
+ cls,
+ fieldname: str,
+ value: _TYPE_FIELD_VALUE_TUPLE,
+ header_formatter: typing.Callable[[str, _TYPE_FIELD_VALUE], str] | None = None,
+ ) -> RequestField:
+ """
+ A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.
+
+ Supports constructing :class:`~urllib3.fields.RequestField` from
+ parameter of key/value strings AND key/filetuple. A filetuple is a
+ (filename, data, MIME type) tuple where the MIME type is optional.
+ For example::
+
+ 'foo': 'bar',
+ 'fakefile': ('foofile.txt', 'contents of foofile'),
+ 'realfile': ('barfile.txt', open('realfile').read()),
+ 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'),
+ 'nonamefile': 'contents of nonamefile field',
+
+ Field names and filenames must be unicode.
+ """
+ filename: str | None
+ content_type: str | None
+ data: _TYPE_FIELD_VALUE
+
+ if isinstance(value, tuple):
+ if len(value) == 3:
+ filename, data, content_type = value
+ else:
+ filename, data = value
+ content_type = guess_content_type(filename)
+ else:
+ filename = None
+ content_type = None
+ data = value
+
+ request_param = cls(
+ fieldname, data, filename=filename, header_formatter=header_formatter
+ )
+ request_param.make_multipart(content_type=content_type)
+
+ return request_param
+
+ def _render_part(self, name: str, value: _TYPE_FIELD_VALUE) -> str:
+ """
+ Override this method to change how each multipart header
+ parameter is formatted. By default, this calls
+ :func:`format_multipart_header_param`.
+
+ :param name:
+ The name of the parameter, an ASCII-only ``str``.
+ :param value:
+ The value of the parameter, a ``str`` or UTF-8 encoded
+ ``bytes``.
+
+ :meta public:
+ """
+ return self.header_formatter(name, value)
+
+ def _render_parts(
+ self,
+ header_parts: (
+ dict[str, _TYPE_FIELD_VALUE | None]
+ | typing.Sequence[tuple[str, _TYPE_FIELD_VALUE | None]]
+ ),
+ ) -> str:
+ """
+ Helper function to format and quote a single header.
+
+ Useful for single headers that are composed of multiple items. E.g.,
+ 'Content-Disposition' fields.
+
+ :param header_parts:
+ A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format
+ as `k1="v1"; k2="v2"; ...`.
+ """
+ iterable: typing.Iterable[tuple[str, _TYPE_FIELD_VALUE | None]]
+
+ parts = []
+ if isinstance(header_parts, dict):
+ iterable = header_parts.items()
+ else:
+ iterable = header_parts
+
+ for name, value in iterable:
+ if value is not None:
+ parts.append(self._render_part(name, value))
+
+ return "; ".join(parts)
+
+ def render_headers(self) -> str:
+ """
+ Renders the headers for this request field.
+ """
+ lines = []
+
+ sort_keys = ["Content-Disposition", "Content-Type", "Content-Location"]
+ for sort_key in sort_keys:
+ if self.headers.get(sort_key, False):
+ lines.append(f"{sort_key}: {self.headers[sort_key]}")
+
+ for header_name, header_value in self.headers.items():
+ if header_name not in sort_keys:
+ if header_value:
+ lines.append(f"{header_name}: {header_value}")
+
+ lines.append("\r\n")
+ return "\r\n".join(lines)
+
+ def make_multipart(
+ self,
+ content_disposition: str | None = None,
+ content_type: str | None = None,
+ content_location: str | None = None,
+ ) -> None:
+ """
+ Makes this request field into a multipart request field.
+
+ This method overrides "Content-Disposition", "Content-Type" and
+ "Content-Location" headers to the request parameter.
+
+ :param content_disposition:
+ The 'Content-Disposition' of the request body. Defaults to 'form-data'
+ :param content_type:
+ The 'Content-Type' of the request body.
+ :param content_location:
+ The 'Content-Location' of the request body.
+
+ """
+ content_disposition = (content_disposition or "form-data") + "; ".join(
+ [
+ "",
+ self._render_parts(
+ (("name", self._name), ("filename", self._filename))
+ ),
+ ]
+ )
+
+ self.headers["Content-Disposition"] = content_disposition
+ self.headers["Content-Type"] = content_type
+ self.headers["Content-Location"] = content_location
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/filepost.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/filepost.py
new file mode 100644
index 0000000000000000000000000000000000000000..14f70b05b4778f91137e4a9e7059d7514aa44d28
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/filepost.py
@@ -0,0 +1,89 @@
+from __future__ import annotations
+
+import binascii
+import codecs
+import os
+import typing
+from io import BytesIO
+
+from .fields import _TYPE_FIELD_VALUE_TUPLE, RequestField
+
+writer = codecs.lookup("utf-8")[3]
+
+_TYPE_FIELDS_SEQUENCE = typing.Sequence[
+ typing.Union[tuple[str, _TYPE_FIELD_VALUE_TUPLE], RequestField]
+]
+_TYPE_FIELDS = typing.Union[
+ _TYPE_FIELDS_SEQUENCE,
+ typing.Mapping[str, _TYPE_FIELD_VALUE_TUPLE],
+]
+
+
+def choose_boundary() -> str:
+ """
+ Our embarrassingly-simple replacement for mimetools.choose_boundary.
+ """
+ return binascii.hexlify(os.urandom(16)).decode()
+
+
+def iter_field_objects(fields: _TYPE_FIELDS) -> typing.Iterable[RequestField]:
+ """
+ Iterate over fields.
+
+ Supports list of (k, v) tuples and dicts, and lists of
+ :class:`~urllib3.fields.RequestField`.
+
+ """
+ iterable: typing.Iterable[RequestField | tuple[str, _TYPE_FIELD_VALUE_TUPLE]]
+
+ if isinstance(fields, typing.Mapping):
+ iterable = fields.items()
+ else:
+ iterable = fields
+
+ for field in iterable:
+ if isinstance(field, RequestField):
+ yield field
+ else:
+ yield RequestField.from_tuples(*field)
+
+
+def encode_multipart_formdata(
+ fields: _TYPE_FIELDS, boundary: str | None = None
+) -> tuple[bytes, str]:
+ """
+ Encode a dictionary of ``fields`` using the multipart/form-data MIME format.
+
+ :param fields:
+ Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`).
+ Values are processed by :func:`urllib3.fields.RequestField.from_tuples`.
+
+ :param boundary:
+ If not specified, then a random boundary will be generated using
+ :func:`urllib3.filepost.choose_boundary`.
+ """
+ body = BytesIO()
+ if boundary is None:
+ boundary = choose_boundary()
+
+ for field in iter_field_objects(fields):
+ body.write(f"--{boundary}\r\n".encode("latin-1"))
+
+ writer(body).write(field.render_headers())
+ data = field.data
+
+ if isinstance(data, int):
+ data = str(data) # Backwards compatibility
+
+ if isinstance(data, str):
+ writer(body).write(data)
+ else:
+ body.write(data)
+
+ body.write(b"\r\n")
+
+ body.write(f"--{boundary}--\r\n".encode("latin-1"))
+
+ content_type = f"multipart/form-data; boundary={boundary}"
+
+ return body.getvalue(), content_type
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/http2/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/http2/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..133e1d8f237f6fddd557ae1c0e0cf738f7cc2748
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/http2/__init__.py
@@ -0,0 +1,53 @@
+from __future__ import annotations
+
+from importlib.metadata import version
+
+__all__ = [
+ "inject_into_urllib3",
+ "extract_from_urllib3",
+]
+
+import typing
+
+orig_HTTPSConnection: typing.Any = None
+
+
+def inject_into_urllib3() -> None:
+ # First check if h2 version is valid
+ h2_version = version("h2")
+ if not h2_version.startswith("4."):
+ raise ImportError(
+ "urllib3 v2 supports h2 version 4.x.x, currently "
+ f"the 'h2' module is compiled with {h2_version!r}. "
+ "See: https://github.com/urllib3/urllib3/issues/3290"
+ )
+
+ # Import here to avoid circular dependencies.
+ from .. import connection as urllib3_connection
+ from .. import util as urllib3_util
+ from ..connectionpool import HTTPSConnectionPool
+ from ..util import ssl_ as urllib3_util_ssl
+ from .connection import HTTP2Connection
+
+ global orig_HTTPSConnection
+ orig_HTTPSConnection = urllib3_connection.HTTPSConnection
+
+ HTTPSConnectionPool.ConnectionCls = HTTP2Connection
+ urllib3_connection.HTTPSConnection = HTTP2Connection # type: ignore[misc]
+
+ # TODO: Offer 'http/1.1' as well, but for testing purposes this is handy.
+ urllib3_util.ALPN_PROTOCOLS = ["h2"]
+ urllib3_util_ssl.ALPN_PROTOCOLS = ["h2"]
+
+
+def extract_from_urllib3() -> None:
+ from .. import connection as urllib3_connection
+ from .. import util as urllib3_util
+ from ..connectionpool import HTTPSConnectionPool
+ from ..util import ssl_ as urllib3_util_ssl
+
+ HTTPSConnectionPool.ConnectionCls = orig_HTTPSConnection
+ urllib3_connection.HTTPSConnection = orig_HTTPSConnection # type: ignore[misc]
+
+ urllib3_util.ALPN_PROTOCOLS = ["http/1.1"]
+ urllib3_util_ssl.ALPN_PROTOCOLS = ["http/1.1"]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/http2/connection.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/http2/connection.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a026da0a8357e324ded47b82b24042713b9bf06
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/http2/connection.py
@@ -0,0 +1,356 @@
+from __future__ import annotations
+
+import logging
+import re
+import threading
+import types
+import typing
+
+import h2.config
+import h2.connection
+import h2.events
+
+from .._base_connection import _TYPE_BODY
+from .._collections import HTTPHeaderDict
+from ..connection import HTTPSConnection, _get_default_user_agent
+from ..exceptions import ConnectionError
+from ..response import BaseHTTPResponse
+
+orig_HTTPSConnection = HTTPSConnection
+
+T = typing.TypeVar("T")
+
+log = logging.getLogger(__name__)
+
+RE_IS_LEGAL_HEADER_NAME = re.compile(rb"^[!#$%&'*+\-.^_`|~0-9a-z]+$")
+RE_IS_ILLEGAL_HEADER_VALUE = re.compile(rb"[\0\x00\x0a\x0d\r\n]|^[ \r\n\t]|[ \r\n\t]$")
+
+
+def _is_legal_header_name(name: bytes) -> bool:
+ """
+ "An implementation that validates fields according to the definitions in Sections
+ 5.1 and 5.5 of [HTTP] only needs an additional check that field names do not
+ include uppercase characters." (https://httpwg.org/specs/rfc9113.html#n-field-validity)
+
+ `http.client._is_legal_header_name` does not validate the field name according to the
+ HTTP 1.1 spec, so we do that here, in addition to checking for uppercase characters.
+
+ This does not allow for the `:` character in the header name, so should not
+ be used to validate pseudo-headers.
+ """
+ return bool(RE_IS_LEGAL_HEADER_NAME.match(name))
+
+
+def _is_illegal_header_value(value: bytes) -> bool:
+ """
+ "A field value MUST NOT contain the zero value (ASCII NUL, 0x00), line feed
+ (ASCII LF, 0x0a), or carriage return (ASCII CR, 0x0d) at any position. A field
+ value MUST NOT start or end with an ASCII whitespace character (ASCII SP or HTAB,
+ 0x20 or 0x09)." (https://httpwg.org/specs/rfc9113.html#n-field-validity)
+ """
+ return bool(RE_IS_ILLEGAL_HEADER_VALUE.search(value))
+
+
+class _LockedObject(typing.Generic[T]):
+ """
+ A wrapper class that hides a specific object behind a lock.
+ The goal here is to provide a simple way to protect access to an object
+ that cannot safely be simultaneously accessed from multiple threads. The
+ intended use of this class is simple: take hold of it with a context
+ manager, which returns the protected object.
+ """
+
+ __slots__ = (
+ "lock",
+ "_obj",
+ )
+
+ def __init__(self, obj: T):
+ self.lock = threading.RLock()
+ self._obj = obj
+
+ def __enter__(self) -> T:
+ self.lock.acquire()
+ return self._obj
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: types.TracebackType | None,
+ ) -> None:
+ self.lock.release()
+
+
+class HTTP2Connection(HTTPSConnection):
+ def __init__(
+ self, host: str, port: int | None = None, **kwargs: typing.Any
+ ) -> None:
+ self._h2_conn = self._new_h2_conn()
+ self._h2_stream: int | None = None
+ self._headers: list[tuple[bytes, bytes]] = []
+
+ if "proxy" in kwargs or "proxy_config" in kwargs: # Defensive:
+ raise NotImplementedError("Proxies aren't supported with HTTP/2")
+
+ super().__init__(host, port, **kwargs)
+
+ if self._tunnel_host is not None:
+ raise NotImplementedError("Tunneling isn't supported with HTTP/2")
+
+ def _new_h2_conn(self) -> _LockedObject[h2.connection.H2Connection]:
+ config = h2.config.H2Configuration(client_side=True)
+ return _LockedObject(h2.connection.H2Connection(config=config))
+
+ def connect(self) -> None:
+ super().connect()
+ with self._h2_conn as conn:
+ conn.initiate_connection()
+ if data_to_send := conn.data_to_send():
+ self.sock.sendall(data_to_send)
+
+ def putrequest( # type: ignore[override]
+ self,
+ method: str,
+ url: str,
+ **kwargs: typing.Any,
+ ) -> None:
+ """putrequest
+ This deviates from the HTTPConnection method signature since we never need to override
+ sending accept-encoding headers or the host header.
+ """
+ if "skip_host" in kwargs:
+ raise NotImplementedError("`skip_host` isn't supported")
+ if "skip_accept_encoding" in kwargs:
+ raise NotImplementedError("`skip_accept_encoding` isn't supported")
+
+ self._request_url = url or "/"
+ self._validate_path(url) # type: ignore[attr-defined]
+
+ if ":" in self.host:
+ authority = f"[{self.host}]:{self.port or 443}"
+ else:
+ authority = f"{self.host}:{self.port or 443}"
+
+ self._headers.append((b":scheme", b"https"))
+ self._headers.append((b":method", method.encode()))
+ self._headers.append((b":authority", authority.encode()))
+ self._headers.append((b":path", url.encode()))
+
+ with self._h2_conn as conn:
+ self._h2_stream = conn.get_next_available_stream_id()
+
+ def putheader(self, header: str | bytes, *values: str | bytes) -> None: # type: ignore[override]
+ # TODO SKIPPABLE_HEADERS from urllib3 are ignored.
+ header = header.encode() if isinstance(header, str) else header
+ header = header.lower() # A lot of upstream code uses capitalized headers.
+ if not _is_legal_header_name(header):
+ raise ValueError(f"Illegal header name {str(header)}")
+
+ for value in values:
+ value = value.encode() if isinstance(value, str) else value
+ if _is_illegal_header_value(value):
+ raise ValueError(f"Illegal header value {str(value)}")
+ self._headers.append((header, value))
+
+ def endheaders(self, message_body: typing.Any = None) -> None: # type: ignore[override]
+ if self._h2_stream is None:
+ raise ConnectionError("Must call `putrequest` first.")
+
+ with self._h2_conn as conn:
+ conn.send_headers(
+ stream_id=self._h2_stream,
+ headers=self._headers,
+ end_stream=(message_body is None),
+ )
+ if data_to_send := conn.data_to_send():
+ self.sock.sendall(data_to_send)
+ self._headers = [] # Reset headers for the next request.
+
+ def send(self, data: typing.Any) -> None:
+ """Send data to the server.
+ `data` can be: `str`, `bytes`, an iterable, or file-like objects
+ that support a .read() method.
+ """
+ if self._h2_stream is None:
+ raise ConnectionError("Must call `putrequest` first.")
+
+ with self._h2_conn as conn:
+ if data_to_send := conn.data_to_send():
+ self.sock.sendall(data_to_send)
+
+ if hasattr(data, "read"): # file-like objects
+ while True:
+ chunk = data.read(self.blocksize)
+ if not chunk:
+ break
+ if isinstance(chunk, str):
+ chunk = chunk.encode()
+ conn.send_data(self._h2_stream, chunk, end_stream=False)
+ if data_to_send := conn.data_to_send():
+ self.sock.sendall(data_to_send)
+ conn.end_stream(self._h2_stream)
+ return
+
+ if isinstance(data, str): # str -> bytes
+ data = data.encode()
+
+ try:
+ if isinstance(data, bytes):
+ conn.send_data(self._h2_stream, data, end_stream=True)
+ if data_to_send := conn.data_to_send():
+ self.sock.sendall(data_to_send)
+ else:
+ for chunk in data:
+ conn.send_data(self._h2_stream, chunk, end_stream=False)
+ if data_to_send := conn.data_to_send():
+ self.sock.sendall(data_to_send)
+ conn.end_stream(self._h2_stream)
+ except TypeError:
+ raise TypeError(
+ "`data` should be str, bytes, iterable, or file. got %r"
+ % type(data)
+ )
+
+ def set_tunnel(
+ self,
+ host: str,
+ port: int | None = None,
+ headers: typing.Mapping[str, str] | None = None,
+ scheme: str = "http",
+ ) -> None:
+ raise NotImplementedError(
+ "HTTP/2 does not support setting up a tunnel through a proxy"
+ )
+
+ def getresponse( # type: ignore[override]
+ self,
+ ) -> HTTP2Response:
+ status = None
+ data = bytearray()
+ with self._h2_conn as conn:
+ end_stream = False
+ while not end_stream:
+ # TODO: Arbitrary read value.
+ if received_data := self.sock.recv(65535):
+ events = conn.receive_data(received_data)
+ for event in events:
+ if isinstance(event, h2.events.ResponseReceived):
+ headers = HTTPHeaderDict()
+ for header, value in event.headers:
+ if header == b":status":
+ status = int(value.decode())
+ else:
+ headers.add(
+ header.decode("ascii"), value.decode("ascii")
+ )
+
+ elif isinstance(event, h2.events.DataReceived):
+ data += event.data
+ conn.acknowledge_received_data(
+ event.flow_controlled_length, event.stream_id
+ )
+
+ elif isinstance(event, h2.events.StreamEnded):
+ end_stream = True
+
+ if data_to_send := conn.data_to_send():
+ self.sock.sendall(data_to_send)
+
+ assert status is not None
+ return HTTP2Response(
+ status=status,
+ headers=headers,
+ request_url=self._request_url,
+ data=bytes(data),
+ )
+
+ def request( # type: ignore[override]
+ self,
+ method: str,
+ url: str,
+ body: _TYPE_BODY | None = None,
+ headers: typing.Mapping[str, str] | None = None,
+ *,
+ preload_content: bool = True,
+ decode_content: bool = True,
+ enforce_content_length: bool = True,
+ **kwargs: typing.Any,
+ ) -> None:
+ """Send an HTTP/2 request"""
+ if "chunked" in kwargs:
+ # TODO this is often present from upstream.
+ # raise NotImplementedError("`chunked` isn't supported with HTTP/2")
+ pass
+
+ if self.sock is not None:
+ self.sock.settimeout(self.timeout)
+
+ self.putrequest(method, url)
+
+ headers = headers or {}
+ for k, v in headers.items():
+ if k.lower() == "transfer-encoding" and v == "chunked":
+ continue
+ else:
+ self.putheader(k, v)
+
+ if b"user-agent" not in dict(self._headers):
+ self.putheader(b"user-agent", _get_default_user_agent())
+
+ if body:
+ self.endheaders(message_body=body)
+ self.send(body)
+ else:
+ self.endheaders()
+
+ def close(self) -> None:
+ with self._h2_conn as conn:
+ try:
+ conn.close_connection()
+ if data := conn.data_to_send():
+ self.sock.sendall(data)
+ except Exception:
+ pass
+
+ # Reset all our HTTP/2 connection state.
+ self._h2_conn = self._new_h2_conn()
+ self._h2_stream = None
+ self._headers = []
+
+ super().close()
+
+
+class HTTP2Response(BaseHTTPResponse):
+ # TODO: This is a woefully incomplete response object, but works for non-streaming.
+ def __init__(
+ self,
+ status: int,
+ headers: HTTPHeaderDict,
+ request_url: str,
+ data: bytes,
+ decode_content: bool = False, # TODO: support decoding
+ ) -> None:
+ super().__init__(
+ status=status,
+ headers=headers,
+ # Following CPython, we map HTTP versions to major * 10 + minor integers
+ version=20,
+ version_string="HTTP/2",
+ # No reason phrase in HTTP/2
+ reason=None,
+ decode_content=decode_content,
+ request_url=request_url,
+ )
+ self._data = data
+ self.length_remaining = 0
+
+ @property
+ def data(self) -> bytes:
+ return self._data
+
+ def get_redirect_location(self) -> None:
+ return None
+
+ def close(self) -> None:
+ pass
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/http2/probe.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/http2/probe.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ea900764f0885eafaac9454523417d86e33df2d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/http2/probe.py
@@ -0,0 +1,87 @@
+from __future__ import annotations
+
+import threading
+
+
+class _HTTP2ProbeCache:
+ __slots__ = (
+ "_lock",
+ "_cache_locks",
+ "_cache_values",
+ )
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._cache_locks: dict[tuple[str, int], threading.RLock] = {}
+ self._cache_values: dict[tuple[str, int], bool | None] = {}
+
+ def acquire_and_get(self, host: str, port: int) -> bool | None:
+ # By the end of this block we know that
+ # _cache_[values,locks] is available.
+ value = None
+ with self._lock:
+ key = (host, port)
+ try:
+ value = self._cache_values[key]
+ # If it's a known value we return right away.
+ if value is not None:
+ return value
+ except KeyError:
+ self._cache_locks[key] = threading.RLock()
+ self._cache_values[key] = None
+
+ # If the value is unknown, we acquire the lock to signal
+ # to the requesting thread that the probe is in progress
+ # or that the current thread needs to return their findings.
+ key_lock = self._cache_locks[key]
+ key_lock.acquire()
+ try:
+ # If the by the time we get the lock the value has been
+ # updated we want to return the updated value.
+ value = self._cache_values[key]
+
+ # In case an exception like KeyboardInterrupt is raised here.
+ except BaseException as e: # Defensive:
+ assert not isinstance(e, KeyError) # KeyError shouldn't be possible.
+ key_lock.release()
+ raise
+
+ return value
+
+ def set_and_release(
+ self, host: str, port: int, supports_http2: bool | None
+ ) -> None:
+ key = (host, port)
+ key_lock = self._cache_locks[key]
+ with key_lock: # Uses an RLock, so can be locked again from same thread.
+ if supports_http2 is None and self._cache_values[key] is not None:
+ raise ValueError(
+ "Cannot reset HTTP/2 support for origin after value has been set."
+ ) # Defensive: not expected in normal usage
+
+ self._cache_values[key] = supports_http2
+ key_lock.release()
+
+ def _values(self) -> dict[tuple[str, int], bool | None]:
+ """This function is for testing purposes only. Gets the current state of the probe cache"""
+ with self._lock:
+ return {k: v for k, v in self._cache_values.items()}
+
+ def _reset(self) -> None:
+ """This function is for testing purposes only. Reset the cache values"""
+ with self._lock:
+ self._cache_locks = {}
+ self._cache_values = {}
+
+
+_HTTP2_PROBE_CACHE = _HTTP2ProbeCache()
+
+set_and_release = _HTTP2_PROBE_CACHE.set_and_release
+acquire_and_get = _HTTP2_PROBE_CACHE.acquire_and_get
+_values = _HTTP2_PROBE_CACHE._values
+_reset = _HTTP2_PROBE_CACHE._reset
+
+__all__ = [
+ "set_and_release",
+ "acquire_and_get",
+]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/poolmanager.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/poolmanager.py
new file mode 100644
index 0000000000000000000000000000000000000000..28ec82f0168543a8aee7cdb79a4b46f10bb2cc91
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/poolmanager.py
@@ -0,0 +1,651 @@
+from __future__ import annotations
+
+import functools
+import logging
+import typing
+import warnings
+from types import TracebackType
+from urllib.parse import urljoin
+
+from ._collections import HTTPHeaderDict, RecentlyUsedContainer
+from ._request_methods import RequestMethods
+from .connection import ProxyConfig
+from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, port_by_scheme
+from .exceptions import (
+ LocationValueError,
+ MaxRetryError,
+ ProxySchemeUnknown,
+ URLSchemeUnknown,
+)
+from .response import BaseHTTPResponse
+from .util.connection import _TYPE_SOCKET_OPTIONS
+from .util.proxy import connection_requires_http_tunnel
+from .util.retry import Retry
+from .util.timeout import Timeout
+from .util.url import Url, parse_url
+
+if typing.TYPE_CHECKING:
+ import ssl
+
+ from typing_extensions import Self
+
+__all__ = ["PoolManager", "ProxyManager", "proxy_from_url"]
+
+
+log = logging.getLogger(__name__)
+
+SSL_KEYWORDS = (
+ "key_file",
+ "cert_file",
+ "cert_reqs",
+ "ca_certs",
+ "ca_cert_data",
+ "ssl_version",
+ "ssl_minimum_version",
+ "ssl_maximum_version",
+ "ca_cert_dir",
+ "ssl_context",
+ "key_password",
+ "server_hostname",
+)
+# Default value for `blocksize` - a new parameter introduced to
+# http.client.HTTPConnection & http.client.HTTPSConnection in Python 3.7
+_DEFAULT_BLOCKSIZE = 16384
+
+
+class PoolKey(typing.NamedTuple):
+ """
+ All known keyword arguments that could be provided to the pool manager, its
+ pools, or the underlying connections.
+
+ All custom key schemes should include the fields in this key at a minimum.
+ """
+
+ key_scheme: str
+ key_host: str
+ key_port: int | None
+ key_timeout: Timeout | float | int | None
+ key_retries: Retry | bool | int | None
+ key_block: bool | None
+ key_source_address: tuple[str, int] | None
+ key_key_file: str | None
+ key_key_password: str | None
+ key_cert_file: str | None
+ key_cert_reqs: str | None
+ key_ca_certs: str | None
+ key_ca_cert_data: str | bytes | None
+ key_ssl_version: int | str | None
+ key_ssl_minimum_version: ssl.TLSVersion | None
+ key_ssl_maximum_version: ssl.TLSVersion | None
+ key_ca_cert_dir: str | None
+ key_ssl_context: ssl.SSLContext | None
+ key_maxsize: int | None
+ key_headers: frozenset[tuple[str, str]] | None
+ key__proxy: Url | None
+ key__proxy_headers: frozenset[tuple[str, str]] | None
+ key__proxy_config: ProxyConfig | None
+ key_socket_options: _TYPE_SOCKET_OPTIONS | None
+ key__socks_options: frozenset[tuple[str, str]] | None
+ key_assert_hostname: bool | str | None
+ key_assert_fingerprint: str | None
+ key_server_hostname: str | None
+ key_blocksize: int | None
+
+
+def _default_key_normalizer(
+ key_class: type[PoolKey], request_context: dict[str, typing.Any]
+) -> PoolKey:
+ """
+ Create a pool key out of a request context dictionary.
+
+ According to RFC 3986, both the scheme and host are case-insensitive.
+ Therefore, this function normalizes both before constructing the pool
+ key for an HTTPS request. If you wish to change this behaviour, provide
+ alternate callables to ``key_fn_by_scheme``.
+
+ :param key_class:
+ The class to use when constructing the key. This should be a namedtuple
+ with the ``scheme`` and ``host`` keys at a minimum.
+ :type key_class: namedtuple
+ :param request_context:
+ A dictionary-like object that contain the context for a request.
+ :type request_context: dict
+
+ :return: A namedtuple that can be used as a connection pool key.
+ :rtype: PoolKey
+ """
+ # Since we mutate the dictionary, make a copy first
+ context = request_context.copy()
+ context["scheme"] = context["scheme"].lower()
+ context["host"] = context["host"].lower()
+
+ # These are both dictionaries and need to be transformed into frozensets
+ for key in ("headers", "_proxy_headers", "_socks_options"):
+ if key in context and context[key] is not None:
+ context[key] = frozenset(context[key].items())
+
+ # The socket_options key may be a list and needs to be transformed into a
+ # tuple.
+ socket_opts = context.get("socket_options")
+ if socket_opts is not None:
+ context["socket_options"] = tuple(socket_opts)
+
+ # Map the kwargs to the names in the namedtuple - this is necessary since
+ # namedtuples can't have fields starting with '_'.
+ for key in list(context.keys()):
+ context["key_" + key] = context.pop(key)
+
+ # Default to ``None`` for keys missing from the context
+ for field in key_class._fields:
+ if field not in context:
+ context[field] = None
+
+ # Default key_blocksize to _DEFAULT_BLOCKSIZE if missing from the context
+ if context.get("key_blocksize") is None:
+ context["key_blocksize"] = _DEFAULT_BLOCKSIZE
+
+ return key_class(**context)
+
+
+#: A dictionary that maps a scheme to a callable that creates a pool key.
+#: This can be used to alter the way pool keys are constructed, if desired.
+#: Each PoolManager makes a copy of this dictionary so they can be configured
+#: globally here, or individually on the instance.
+key_fn_by_scheme = {
+ "http": functools.partial(_default_key_normalizer, PoolKey),
+ "https": functools.partial(_default_key_normalizer, PoolKey),
+}
+
+pool_classes_by_scheme = {"http": HTTPConnectionPool, "https": HTTPSConnectionPool}
+
+
+class PoolManager(RequestMethods):
+ """
+ Allows for arbitrary requests while transparently keeping track of
+ necessary connection pools for you.
+
+ :param num_pools:
+ Number of connection pools to cache before discarding the least
+ recently used pool.
+
+ :param headers:
+ Headers to include with all requests, unless other headers are given
+ explicitly.
+
+ :param \\**connection_pool_kw:
+ Additional parameters are used to create fresh
+ :class:`urllib3.connectionpool.ConnectionPool` instances.
+
+ Example:
+
+ .. code-block:: python
+
+ import urllib3
+
+ http = urllib3.PoolManager(num_pools=2)
+
+ resp1 = http.request("GET", "https://google.com/")
+ resp2 = http.request("GET", "https://google.com/mail")
+ resp3 = http.request("GET", "https://yahoo.com/")
+
+ print(len(http.pools))
+ # 2
+
+ """
+
+ proxy: Url | None = None
+ proxy_config: ProxyConfig | None = None
+
+ def __init__(
+ self,
+ num_pools: int = 10,
+ headers: typing.Mapping[str, str] | None = None,
+ **connection_pool_kw: typing.Any,
+ ) -> None:
+ super().__init__(headers)
+ # PoolManager handles redirects itself in PoolManager.urlopen().
+ # It always passes redirect=False to the underlying connection pool to
+ # suppress per-pool redirect handling. If the user supplied a non-Retry
+ # value (int/bool/etc) for retries and we let the pool normalize it
+ # while redirect=False, the resulting Retry object would have redirect
+ # handling disabled, which can interfere with PoolManager's own
+ # redirect logic. Normalize here so redirects remain governed solely by
+ # PoolManager logic.
+ if "retries" in connection_pool_kw:
+ retries = connection_pool_kw["retries"]
+ if not isinstance(retries, Retry):
+ retries = Retry.from_int(retries)
+ connection_pool_kw = connection_pool_kw.copy()
+ connection_pool_kw["retries"] = retries
+ self.connection_pool_kw = connection_pool_kw
+
+ self.pools: RecentlyUsedContainer[PoolKey, HTTPConnectionPool]
+ self.pools = RecentlyUsedContainer(num_pools)
+
+ # Locally set the pool classes and keys so other PoolManagers can
+ # override them.
+ self.pool_classes_by_scheme = pool_classes_by_scheme
+ self.key_fn_by_scheme = key_fn_by_scheme.copy()
+
+ def __enter__(self) -> Self:
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: TracebackType | None,
+ ) -> typing.Literal[False]:
+ self.clear()
+ # Return False to re-raise any potential exceptions
+ return False
+
+ def _new_pool(
+ self,
+ scheme: str,
+ host: str,
+ port: int,
+ request_context: dict[str, typing.Any] | None = None,
+ ) -> HTTPConnectionPool:
+ """
+ Create a new :class:`urllib3.connectionpool.ConnectionPool` based on host, port, scheme, and
+ any additional pool keyword arguments.
+
+ If ``request_context`` is provided, it is provided as keyword arguments
+ to the pool class used. This method is used to actually create the
+ connection pools handed out by :meth:`connection_from_url` and
+ companion methods. It is intended to be overridden for customization.
+ """
+ pool_cls: type[HTTPConnectionPool] = self.pool_classes_by_scheme[scheme]
+ if request_context is None:
+ request_context = self.connection_pool_kw.copy()
+
+ # Default blocksize to _DEFAULT_BLOCKSIZE if missing or explicitly
+ # set to 'None' in the request_context.
+ if request_context.get("blocksize") is None:
+ request_context["blocksize"] = _DEFAULT_BLOCKSIZE
+
+ # Although the context has everything necessary to create the pool,
+ # this function has historically only used the scheme, host, and port
+ # in the positional args. When an API change is acceptable these can
+ # be removed.
+ for key in ("scheme", "host", "port"):
+ request_context.pop(key, None)
+
+ if scheme == "http":
+ for kw in SSL_KEYWORDS:
+ request_context.pop(kw, None)
+
+ return pool_cls(host, port, **request_context)
+
+ def clear(self) -> None:
+ """
+ Empty our store of pools and direct them all to close.
+
+ This will not affect in-flight connections, but they will not be
+ re-used after completion.
+ """
+ self.pools.clear()
+
+ def connection_from_host(
+ self,
+ host: str | None,
+ port: int | None = None,
+ scheme: str | None = "http",
+ pool_kwargs: dict[str, typing.Any] | None = None,
+ ) -> HTTPConnectionPool:
+ """
+ Get a :class:`urllib3.connectionpool.ConnectionPool` based on the host, port, and scheme.
+
+ If ``port`` isn't given, it will be derived from the ``scheme`` using
+ ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is
+ provided, it is merged with the instance's ``connection_pool_kw``
+ variable and used to create the new connection pool, if one is
+ needed.
+ """
+
+ if not host:
+ raise LocationValueError("No host specified.")
+
+ request_context = self._merge_pool_kwargs(pool_kwargs)
+ request_context["scheme"] = scheme or "http"
+ if not port:
+ port = port_by_scheme.get(request_context["scheme"].lower(), 80)
+ request_context["port"] = port
+ request_context["host"] = host
+
+ return self.connection_from_context(request_context)
+
+ def connection_from_context(
+ self, request_context: dict[str, typing.Any]
+ ) -> HTTPConnectionPool:
+ """
+ Get a :class:`urllib3.connectionpool.ConnectionPool` based on the request context.
+
+ ``request_context`` must at least contain the ``scheme`` key and its
+ value must be a key in ``key_fn_by_scheme`` instance variable.
+ """
+ if "strict" in request_context:
+ warnings.warn(
+ "The 'strict' parameter is no longer needed on Python 3+. "
+ "This will raise an error in urllib3 v2.1.0.",
+ DeprecationWarning,
+ )
+ request_context.pop("strict")
+
+ scheme = request_context["scheme"].lower()
+ pool_key_constructor = self.key_fn_by_scheme.get(scheme)
+ if not pool_key_constructor:
+ raise URLSchemeUnknown(scheme)
+ pool_key = pool_key_constructor(request_context)
+
+ return self.connection_from_pool_key(pool_key, request_context=request_context)
+
+ def connection_from_pool_key(
+ self, pool_key: PoolKey, request_context: dict[str, typing.Any]
+ ) -> HTTPConnectionPool:
+ """
+ Get a :class:`urllib3.connectionpool.ConnectionPool` based on the provided pool key.
+
+ ``pool_key`` should be a namedtuple that only contains immutable
+ objects. At a minimum it must have the ``scheme``, ``host``, and
+ ``port`` fields.
+ """
+ with self.pools.lock:
+ # If the scheme, host, or port doesn't match existing open
+ # connections, open a new ConnectionPool.
+ pool = self.pools.get(pool_key)
+ if pool:
+ return pool
+
+ # Make a fresh ConnectionPool of the desired type
+ scheme = request_context["scheme"]
+ host = request_context["host"]
+ port = request_context["port"]
+ pool = self._new_pool(scheme, host, port, request_context=request_context)
+ self.pools[pool_key] = pool
+
+ return pool
+
+ def connection_from_url(
+ self, url: str, pool_kwargs: dict[str, typing.Any] | None = None
+ ) -> HTTPConnectionPool:
+ """
+ Similar to :func:`urllib3.connectionpool.connection_from_url`.
+
+ If ``pool_kwargs`` is not provided and a new pool needs to be
+ constructed, ``self.connection_pool_kw`` is used to initialize
+ the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs``
+ is provided, it is used instead. Note that if a new pool does not
+ need to be created for the request, the provided ``pool_kwargs`` are
+ not used.
+ """
+ u = parse_url(url)
+ return self.connection_from_host(
+ u.host, port=u.port, scheme=u.scheme, pool_kwargs=pool_kwargs
+ )
+
+ def _merge_pool_kwargs(
+ self, override: dict[str, typing.Any] | None
+ ) -> dict[str, typing.Any]:
+ """
+ Merge a dictionary of override values for self.connection_pool_kw.
+
+ This does not modify self.connection_pool_kw and returns a new dict.
+ Any keys in the override dictionary with a value of ``None`` are
+ removed from the merged dictionary.
+ """
+ base_pool_kwargs = self.connection_pool_kw.copy()
+ if override:
+ for key, value in override.items():
+ if value is None:
+ try:
+ del base_pool_kwargs[key]
+ except KeyError:
+ pass
+ else:
+ base_pool_kwargs[key] = value
+ return base_pool_kwargs
+
+ def _proxy_requires_url_absolute_form(self, parsed_url: Url) -> bool:
+ """
+ Indicates if the proxy requires the complete destination URL in the
+ request. Normally this is only needed when not using an HTTP CONNECT
+ tunnel.
+ """
+ if self.proxy is None:
+ return False
+
+ return not connection_requires_http_tunnel(
+ self.proxy, self.proxy_config, parsed_url.scheme
+ )
+
+ def urlopen( # type: ignore[override]
+ self, method: str, url: str, redirect: bool = True, **kw: typing.Any
+ ) -> BaseHTTPResponse:
+ """
+ Same as :meth:`urllib3.HTTPConnectionPool.urlopen`
+ with custom cross-host redirect logic and only sends the request-uri
+ portion of the ``url``.
+
+ The given ``url`` parameter must be absolute, such that an appropriate
+ :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.
+ """
+ u = parse_url(url)
+
+ if u.scheme is None:
+ warnings.warn(
+ "URLs without a scheme (ie 'https://') are deprecated and will raise an error "
+ "in a future version of urllib3. To avoid this DeprecationWarning ensure all URLs "
+ "start with 'https://' or 'http://'. Read more in this issue: "
+ "https://github.com/urllib3/urllib3/issues/2920",
+ category=DeprecationWarning,
+ stacklevel=2,
+ )
+
+ conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
+
+ kw["assert_same_host"] = False
+ kw["redirect"] = False
+
+ if "headers" not in kw:
+ kw["headers"] = self.headers
+
+ if self._proxy_requires_url_absolute_form(u):
+ response = conn.urlopen(method, url, **kw)
+ else:
+ response = conn.urlopen(method, u.request_uri, **kw)
+
+ redirect_location = redirect and response.get_redirect_location()
+ if not redirect_location:
+ return response
+
+ # Support relative URLs for redirecting.
+ redirect_location = urljoin(url, redirect_location)
+
+ if response.status == 303:
+ # Change the method according to RFC 9110, Section 15.4.4.
+ method = "GET"
+ # And lose the body not to transfer anything sensitive.
+ kw["body"] = None
+ kw["headers"] = HTTPHeaderDict(kw["headers"])._prepare_for_method_change()
+
+ retries = kw.get("retries", response.retries)
+ if not isinstance(retries, Retry):
+ retries = Retry.from_int(retries, redirect=redirect)
+
+ # Strip headers marked as unsafe to forward to the redirected location.
+ # Check remove_headers_on_redirect to avoid a potential network call within
+ # conn.is_same_host() which may use socket.gethostbyname() in the future.
+ if retries.remove_headers_on_redirect and not conn.is_same_host(
+ redirect_location
+ ):
+ new_headers = kw["headers"].copy()
+ for header in kw["headers"]:
+ if header.lower() in retries.remove_headers_on_redirect:
+ new_headers.pop(header, None)
+ kw["headers"] = new_headers
+
+ try:
+ retries = retries.increment(method, url, response=response, _pool=conn)
+ except MaxRetryError:
+ if retries.raise_on_redirect:
+ response.drain_conn()
+ raise
+ return response
+
+ kw["retries"] = retries
+ kw["redirect"] = redirect
+
+ log.info("Redirecting %s -> %s", url, redirect_location)
+
+ response.drain_conn()
+ return self.urlopen(method, redirect_location, **kw)
+
+
+class ProxyManager(PoolManager):
+ """
+ Behaves just like :class:`PoolManager`, but sends all requests through
+ the defined proxy, using the CONNECT method for HTTPS URLs.
+
+ :param proxy_url:
+ The URL of the proxy to be used.
+
+ :param proxy_headers:
+ A dictionary containing headers that will be sent to the proxy. In case
+ of HTTP they are being sent with each request, while in the
+ HTTPS/CONNECT case they are sent only once. Could be used for proxy
+ authentication.
+
+ :param proxy_ssl_context:
+ The proxy SSL context is used to establish the TLS connection to the
+ proxy when using HTTPS proxies.
+
+ :param use_forwarding_for_https:
+ (Defaults to False) If set to True will forward requests to the HTTPS
+ proxy to be made on behalf of the client instead of creating a TLS
+ tunnel via the CONNECT method. **Enabling this flag means that request
+ and response headers and content will be visible from the HTTPS proxy**
+ whereas tunneling keeps request and response headers and content
+ private. IP address, target hostname, SNI, and port are always visible
+ to an HTTPS proxy even when this flag is disabled.
+
+ :param proxy_assert_hostname:
+ The hostname of the certificate to verify against.
+
+ :param proxy_assert_fingerprint:
+ The fingerprint of the certificate to verify against.
+
+ Example:
+
+ .. code-block:: python
+
+ import urllib3
+
+ proxy = urllib3.ProxyManager("https://localhost:3128/")
+
+ resp1 = proxy.request("GET", "https://google.com/")
+ resp2 = proxy.request("GET", "https://httpbin.org/")
+
+ print(len(proxy.pools))
+ # 1
+
+ resp3 = proxy.request("GET", "https://httpbin.org/")
+ resp4 = proxy.request("GET", "https://twitter.com/")
+
+ print(len(proxy.pools))
+ # 3
+
+ """
+
+ def __init__(
+ self,
+ proxy_url: str,
+ num_pools: int = 10,
+ headers: typing.Mapping[str, str] | None = None,
+ proxy_headers: typing.Mapping[str, str] | None = None,
+ proxy_ssl_context: ssl.SSLContext | None = None,
+ use_forwarding_for_https: bool = False,
+ proxy_assert_hostname: None | str | typing.Literal[False] = None,
+ proxy_assert_fingerprint: str | None = None,
+ **connection_pool_kw: typing.Any,
+ ) -> None:
+ if isinstance(proxy_url, HTTPConnectionPool):
+ str_proxy_url = f"{proxy_url.scheme}://{proxy_url.host}:{proxy_url.port}"
+ else:
+ str_proxy_url = proxy_url
+ proxy = parse_url(str_proxy_url)
+
+ if proxy.scheme not in ("http", "https"):
+ raise ProxySchemeUnknown(proxy.scheme)
+
+ if not proxy.port:
+ port = port_by_scheme.get(proxy.scheme, 80)
+ proxy = proxy._replace(port=port)
+
+ self.proxy = proxy
+ self.proxy_headers = proxy_headers or {}
+ self.proxy_ssl_context = proxy_ssl_context
+ self.proxy_config = ProxyConfig(
+ proxy_ssl_context,
+ use_forwarding_for_https,
+ proxy_assert_hostname,
+ proxy_assert_fingerprint,
+ )
+
+ connection_pool_kw["_proxy"] = self.proxy
+ connection_pool_kw["_proxy_headers"] = self.proxy_headers
+ connection_pool_kw["_proxy_config"] = self.proxy_config
+
+ super().__init__(num_pools, headers, **connection_pool_kw)
+
+ def connection_from_host(
+ self,
+ host: str | None,
+ port: int | None = None,
+ scheme: str | None = "http",
+ pool_kwargs: dict[str, typing.Any] | None = None,
+ ) -> HTTPConnectionPool:
+ if scheme == "https":
+ return super().connection_from_host(
+ host, port, scheme, pool_kwargs=pool_kwargs
+ )
+
+ return super().connection_from_host(
+ self.proxy.host, self.proxy.port, self.proxy.scheme, pool_kwargs=pool_kwargs # type: ignore[union-attr]
+ )
+
+ def _set_proxy_headers(
+ self, url: str, headers: typing.Mapping[str, str] | None = None
+ ) -> typing.Mapping[str, str]:
+ """
+ Sets headers needed by proxies: specifically, the Accept and Host
+ headers. Only sets headers not provided by the user.
+ """
+ headers_ = {"Accept": "*/*"}
+
+ netloc = parse_url(url).netloc
+ if netloc:
+ headers_["Host"] = netloc
+
+ if headers:
+ headers_.update(headers)
+ return headers_
+
+ def urlopen( # type: ignore[override]
+ self, method: str, url: str, redirect: bool = True, **kw: typing.Any
+ ) -> BaseHTTPResponse:
+ "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."
+ u = parse_url(url)
+ if not connection_requires_http_tunnel(self.proxy, self.proxy_config, u.scheme):
+ # For connections using HTTP CONNECT, httplib sets the necessary
+ # headers on the CONNECT to the proxy. If we're not using CONNECT,
+ # we'll definitely need to set 'Host' at the very least.
+ headers = kw.get("headers", self.headers)
+ kw["headers"] = self._set_proxy_headers(url, headers)
+
+ return super().urlopen(method, url, redirect=redirect, **kw)
+
+
+def proxy_from_url(url: str, **kw: typing.Any) -> ProxyManager:
+ return ProxyManager(proxy_url=url, **kw)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/py.typed b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..5f3ea3d919363f08ab03edbc85b6099bc4df5647
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/py.typed
@@ -0,0 +1,2 @@
+# Instruct type checkers to look for inline type annotations in this package.
+# See PEP 561.
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/response.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/response.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff6d1f4911c2e304a2d7822059d9574536f81aea
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/response.py
@@ -0,0 +1,1480 @@
+from __future__ import annotations
+
+import collections
+import io
+import json as _json
+import logging
+import socket
+import sys
+import typing
+import warnings
+import zlib
+from contextlib import contextmanager
+from http.client import HTTPMessage as _HttplibHTTPMessage
+from http.client import HTTPResponse as _HttplibHTTPResponse
+from socket import timeout as SocketTimeout
+
+if typing.TYPE_CHECKING:
+ from ._base_connection import BaseHTTPConnection
+
+try:
+ try:
+ import brotlicffi as brotli # type: ignore[import-not-found]
+ except ImportError:
+ import brotli # type: ignore[import-not-found]
+except ImportError:
+ brotli = None
+
+from . import util
+from ._base_connection import _TYPE_BODY
+from ._collections import HTTPHeaderDict
+from .connection import BaseSSLError, HTTPConnection, HTTPException
+from .exceptions import (
+ BodyNotHttplibCompatible,
+ DecodeError,
+ DependencyWarning,
+ HTTPError,
+ IncompleteRead,
+ InvalidChunkLength,
+ InvalidHeader,
+ ProtocolError,
+ ReadTimeoutError,
+ ResponseNotChunked,
+ SSLError,
+)
+from .util.response import is_fp_closed, is_response_to_head
+from .util.retry import Retry
+
+if typing.TYPE_CHECKING:
+ from .connectionpool import HTTPConnectionPool
+
+log = logging.getLogger(__name__)
+
+
+class ContentDecoder:
+ def decompress(self, data: bytes, max_length: int = -1) -> bytes:
+ raise NotImplementedError()
+
+ @property
+ def has_unconsumed_tail(self) -> bool:
+ raise NotImplementedError()
+
+ def flush(self) -> bytes:
+ raise NotImplementedError()
+
+
+class DeflateDecoder(ContentDecoder):
+ def __init__(self) -> None:
+ self._first_try = True
+ self._first_try_data = b""
+ self._unfed_data = b""
+ self._obj = zlib.decompressobj()
+
+ def decompress(self, data: bytes, max_length: int = -1) -> bytes:
+ data = self._unfed_data + data
+ self._unfed_data = b""
+ if not data and not self._obj.unconsumed_tail:
+ return data
+ original_max_length = max_length
+ if original_max_length < 0:
+ max_length = 0
+ elif original_max_length == 0:
+ # We should not pass 0 to the zlib decompressor because 0 is
+ # the default value that will make zlib decompress without a
+ # length limit.
+ # Data should be stored for subsequent calls.
+ self._unfed_data = data
+ return b""
+
+ # Subsequent calls always reuse `self._obj`. zlib requires
+ # passing the unconsumed tail if decompression is to continue.
+ if not self._first_try:
+ return self._obj.decompress(
+ self._obj.unconsumed_tail + data, max_length=max_length
+ )
+
+ # First call tries with RFC 1950 ZLIB format.
+ self._first_try_data += data
+ try:
+ decompressed = self._obj.decompress(data, max_length=max_length)
+ if decompressed:
+ self._first_try = False
+ self._first_try_data = b""
+ return decompressed
+ # On failure, it falls back to RFC 1951 DEFLATE format.
+ except zlib.error:
+ self._first_try = False
+ self._obj = zlib.decompressobj(-zlib.MAX_WBITS)
+ try:
+ return self.decompress(
+ self._first_try_data, max_length=original_max_length
+ )
+ finally:
+ self._first_try_data = b""
+
+ @property
+ def has_unconsumed_tail(self) -> bool:
+ return bool(self._unfed_data) or (
+ bool(self._obj.unconsumed_tail) and not self._first_try
+ )
+
+ def flush(self) -> bytes:
+ return self._obj.flush()
+
+
+class GzipDecoderState:
+ FIRST_MEMBER = 0
+ OTHER_MEMBERS = 1
+ SWALLOW_DATA = 2
+
+
+class GzipDecoder(ContentDecoder):
+ def __init__(self) -> None:
+ self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)
+ self._state = GzipDecoderState.FIRST_MEMBER
+ self._unconsumed_tail = b""
+
+ def decompress(self, data: bytes, max_length: int = -1) -> bytes:
+ ret = bytearray()
+ if self._state == GzipDecoderState.SWALLOW_DATA:
+ return bytes(ret)
+
+ if max_length == 0:
+ # We should not pass 0 to the zlib decompressor because 0 is
+ # the default value that will make zlib decompress without a
+ # length limit.
+ # Data should be stored for subsequent calls.
+ self._unconsumed_tail += data
+ return b""
+
+ # zlib requires passing the unconsumed tail to the subsequent
+ # call if decompression is to continue.
+ data = self._unconsumed_tail + data
+ if not data and self._obj.eof:
+ return bytes(ret)
+
+ while True:
+ try:
+ ret += self._obj.decompress(
+ data, max_length=max(max_length - len(ret), 0)
+ )
+ except zlib.error:
+ previous_state = self._state
+ # Ignore data after the first error
+ self._state = GzipDecoderState.SWALLOW_DATA
+ self._unconsumed_tail = b""
+ if previous_state == GzipDecoderState.OTHER_MEMBERS:
+ # Allow trailing garbage acceptable in other gzip clients
+ return bytes(ret)
+ raise
+
+ self._unconsumed_tail = data = (
+ self._obj.unconsumed_tail or self._obj.unused_data
+ )
+ if max_length > 0 and len(ret) >= max_length:
+ break
+
+ if not data:
+ return bytes(ret)
+ # When the end of a gzip member is reached, a new decompressor
+ # must be created for unused (possibly future) data.
+ if self._obj.eof:
+ self._state = GzipDecoderState.OTHER_MEMBERS
+ self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)
+
+ return bytes(ret)
+
+ @property
+ def has_unconsumed_tail(self) -> bool:
+ return bool(self._unconsumed_tail)
+
+ def flush(self) -> bytes:
+ return self._obj.flush()
+
+
+if brotli is not None:
+
+ class BrotliDecoder(ContentDecoder):
+ # Supports both 'brotlipy' and 'Brotli' packages
+ # since they share an import name. The top branches
+ # are for 'brotlipy' and bottom branches for 'Brotli'
+ def __init__(self) -> None:
+ self._obj = brotli.Decompressor()
+ if hasattr(self._obj, "decompress"):
+ setattr(self, "_decompress", self._obj.decompress)
+ else:
+ setattr(self, "_decompress", self._obj.process)
+
+ # Requires Brotli >= 1.2.0 for `output_buffer_limit`.
+ def _decompress(self, data: bytes, output_buffer_limit: int = -1) -> bytes:
+ raise NotImplementedError()
+
+ def decompress(self, data: bytes, max_length: int = -1) -> bytes:
+ try:
+ if max_length > 0:
+ return self._decompress(data, output_buffer_limit=max_length)
+ else:
+ return self._decompress(data)
+ except TypeError:
+ # Fallback for Brotli/brotlicffi/brotlipy versions without
+ # the `output_buffer_limit` parameter.
+ warnings.warn(
+ "Brotli >= 1.2.0 is required to prevent decompression bombs.",
+ DependencyWarning,
+ )
+ return self._decompress(data)
+
+ @property
+ def has_unconsumed_tail(self) -> bool:
+ try:
+ return not self._obj.can_accept_more_data()
+ except AttributeError:
+ return False
+
+ def flush(self) -> bytes:
+ if hasattr(self._obj, "flush"):
+ return self._obj.flush() # type: ignore[no-any-return]
+ return b""
+
+
+try:
+ if sys.version_info >= (3, 14):
+ from compression import zstd
+ else:
+ from backports import zstd
+except ImportError:
+ HAS_ZSTD = False
+else:
+ HAS_ZSTD = True
+
+ class ZstdDecoder(ContentDecoder):
+ def __init__(self) -> None:
+ self._obj = zstd.ZstdDecompressor()
+
+ def decompress(self, data: bytes, max_length: int = -1) -> bytes:
+ if not data and not self.has_unconsumed_tail:
+ return b""
+ if self._obj.eof:
+ data = self._obj.unused_data + data
+ self._obj = zstd.ZstdDecompressor()
+ part = self._obj.decompress(data, max_length=max_length)
+ length = len(part)
+ data_parts = [part]
+ # Every loop iteration is supposed to read data from a separate frame.
+ # The loop breaks when:
+ # - enough data is read;
+ # - no more unused data is available;
+ # - end of the last read frame has not been reached (i.e.,
+ # more data has to be fed).
+ while (
+ self._obj.eof
+ and self._obj.unused_data
+ and (max_length < 0 or length < max_length)
+ ):
+ unused_data = self._obj.unused_data
+ if not self._obj.needs_input:
+ self._obj = zstd.ZstdDecompressor()
+ part = self._obj.decompress(
+ unused_data,
+ max_length=(max_length - length) if max_length > 0 else -1,
+ )
+ if part_length := len(part):
+ data_parts.append(part)
+ length += part_length
+ elif self._obj.needs_input:
+ break
+ return b"".join(data_parts)
+
+ @property
+ def has_unconsumed_tail(self) -> bool:
+ return not (self._obj.needs_input or self._obj.eof) or bool(
+ self._obj.unused_data
+ )
+
+ def flush(self) -> bytes:
+ if not self._obj.eof:
+ raise DecodeError("Zstandard data is incomplete")
+ return b""
+
+
+class MultiDecoder(ContentDecoder):
+ """
+ From RFC7231:
+ If one or more encodings have been applied to a representation, the
+ sender that applied the encodings MUST generate a Content-Encoding
+ header field that lists the content codings in the order in which
+ they were applied.
+ """
+
+ # Maximum allowed number of chained HTTP encodings in the
+ # Content-Encoding header.
+ max_decode_links = 5
+
+ def __init__(self, modes: str) -> None:
+ encodings = [m.strip() for m in modes.split(",")]
+ if len(encodings) > self.max_decode_links:
+ raise DecodeError(
+ "Too many content encodings in the chain: "
+ f"{len(encodings)} > {self.max_decode_links}"
+ )
+ self._decoders = [_get_decoder(e) for e in encodings]
+
+ def flush(self) -> bytes:
+ return self._decoders[0].flush()
+
+ def decompress(self, data: bytes, max_length: int = -1) -> bytes:
+ if max_length <= 0:
+ for d in reversed(self._decoders):
+ data = d.decompress(data)
+ return data
+
+ ret = bytearray()
+ # Every while loop iteration goes through all decoders once.
+ # It exits when enough data is read or no more data can be read.
+ # It is possible that the while loop iteration does not produce
+ # any data because we retrieve up to `max_length` from every
+ # decoder, and the amount of bytes may be insufficient for the
+ # next decoder to produce enough/any output.
+ while True:
+ any_data = False
+ for d in reversed(self._decoders):
+ data = d.decompress(data, max_length=max_length - len(ret))
+ if data:
+ any_data = True
+ # We should not break when no data is returned because
+ # next decoders may produce data even with empty input.
+ ret += data
+ if not any_data or len(ret) >= max_length:
+ return bytes(ret)
+ data = b""
+
+ @property
+ def has_unconsumed_tail(self) -> bool:
+ return any(d.has_unconsumed_tail for d in self._decoders)
+
+
+def _get_decoder(mode: str) -> ContentDecoder:
+ if "," in mode:
+ return MultiDecoder(mode)
+
+ # According to RFC 9110 section 8.4.1.3, recipients should
+ # consider x-gzip equivalent to gzip
+ if mode in ("gzip", "x-gzip"):
+ return GzipDecoder()
+
+ if brotli is not None and mode == "br":
+ return BrotliDecoder()
+
+ if HAS_ZSTD and mode == "zstd":
+ return ZstdDecoder()
+
+ return DeflateDecoder()
+
+
+class BytesQueueBuffer:
+ """Memory-efficient bytes buffer
+
+ To return decoded data in read() and still follow the BufferedIOBase API, we need a
+ buffer to always return the correct amount of bytes.
+
+ This buffer should be filled using calls to put()
+
+ Our maximum memory usage is determined by the sum of the size of:
+
+ * self.buffer, which contains the full data
+ * the largest chunk that we will copy in get()
+ """
+
+ def __init__(self) -> None:
+ self.buffer: typing.Deque[bytes | memoryview[bytes]] = collections.deque()
+ self._size: int = 0
+
+ def __len__(self) -> int:
+ return self._size
+
+ def put(self, data: bytes) -> None:
+ self.buffer.append(data)
+ self._size += len(data)
+
+ def get(self, n: int) -> bytes:
+ if n == 0:
+ return b""
+ elif not self.buffer:
+ raise RuntimeError("buffer is empty")
+ elif n < 0:
+ raise ValueError("n should be > 0")
+
+ if len(self.buffer[0]) == n and isinstance(self.buffer[0], bytes):
+ self._size -= n
+ return self.buffer.popleft()
+
+ fetched = 0
+ ret = io.BytesIO()
+ while fetched < n:
+ remaining = n - fetched
+ chunk = self.buffer.popleft()
+ chunk_length = len(chunk)
+ if remaining < chunk_length:
+ chunk = memoryview(chunk)
+ left_chunk, right_chunk = chunk[:remaining], chunk[remaining:]
+ ret.write(left_chunk)
+ self.buffer.appendleft(right_chunk)
+ self._size -= remaining
+ break
+ else:
+ ret.write(chunk)
+ self._size -= chunk_length
+ fetched += chunk_length
+
+ if not self.buffer:
+ break
+
+ return ret.getvalue()
+
+ def get_all(self) -> bytes:
+ buffer = self.buffer
+ if not buffer:
+ assert self._size == 0
+ return b""
+ if len(buffer) == 1:
+ result = buffer.pop()
+ if isinstance(result, memoryview):
+ result = result.tobytes()
+ else:
+ ret = io.BytesIO()
+ ret.writelines(buffer.popleft() for _ in range(len(buffer)))
+ result = ret.getvalue()
+ self._size = 0
+ return result
+
+
+class BaseHTTPResponse(io.IOBase):
+ CONTENT_DECODERS = ["gzip", "x-gzip", "deflate"]
+ if brotli is not None:
+ CONTENT_DECODERS += ["br"]
+ if HAS_ZSTD:
+ CONTENT_DECODERS += ["zstd"]
+ REDIRECT_STATUSES = [301, 302, 303, 307, 308]
+
+ DECODER_ERROR_CLASSES: tuple[type[Exception], ...] = (IOError, zlib.error)
+ if brotli is not None:
+ DECODER_ERROR_CLASSES += (brotli.error,)
+
+ if HAS_ZSTD:
+ DECODER_ERROR_CLASSES += (zstd.ZstdError,)
+
+ def __init__(
+ self,
+ *,
+ headers: typing.Mapping[str, str] | typing.Mapping[bytes, bytes] | None = None,
+ status: int,
+ version: int,
+ version_string: str,
+ reason: str | None,
+ decode_content: bool,
+ request_url: str | None,
+ retries: Retry | None = None,
+ ) -> None:
+ if isinstance(headers, HTTPHeaderDict):
+ self.headers = headers
+ else:
+ self.headers = HTTPHeaderDict(headers) # type: ignore[arg-type]
+ self.status = status
+ self.version = version
+ self.version_string = version_string
+ self.reason = reason
+ self.decode_content = decode_content
+ self._has_decoded_content = False
+ self._request_url: str | None = request_url
+ self.retries = retries
+
+ self.chunked = False
+ tr_enc = self.headers.get("transfer-encoding", "").lower()
+ # Don't incur the penalty of creating a list and then discarding it
+ encodings = (enc.strip() for enc in tr_enc.split(","))
+ if "chunked" in encodings:
+ self.chunked = True
+
+ self._decoder: ContentDecoder | None = None
+ self.length_remaining: int | None
+
+ def get_redirect_location(self) -> str | None | typing.Literal[False]:
+ """
+ Should we redirect and where to?
+
+ :returns: Truthy redirect location string if we got a redirect status
+ code and valid location. ``None`` if redirect status and no
+ location. ``False`` if not a redirect status code.
+ """
+ if self.status in self.REDIRECT_STATUSES:
+ return self.headers.get("location")
+ return False
+
+ @property
+ def data(self) -> bytes:
+ raise NotImplementedError()
+
+ def json(self) -> typing.Any:
+ """
+ Deserializes the body of the HTTP response as a Python object.
+
+ The body of the HTTP response must be encoded using UTF-8, as per
+ `RFC 8529 Section 8.1 `_.
+
+ To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to
+ your custom decoder instead.
+
+ If the body of the HTTP response is not decodable to UTF-8, a
+ `UnicodeDecodeError` will be raised. If the body of the HTTP response is not a
+ valid JSON document, a `json.JSONDecodeError` will be raised.
+
+ Read more :ref:`here `.
+
+ :returns: The body of the HTTP response as a Python object.
+ """
+ data = self.data.decode("utf-8")
+ return _json.loads(data)
+
+ @property
+ def url(self) -> str | None:
+ raise NotImplementedError()
+
+ @url.setter
+ def url(self, url: str | None) -> None:
+ raise NotImplementedError()
+
+ @property
+ def connection(self) -> BaseHTTPConnection | None:
+ raise NotImplementedError()
+
+ @property
+ def retries(self) -> Retry | None:
+ return self._retries
+
+ @retries.setter
+ def retries(self, retries: Retry | None) -> None:
+ # Override the request_url if retries has a redirect location.
+ if retries is not None and retries.history:
+ self.url = retries.history[-1].redirect_location
+ self._retries = retries
+
+ def stream(
+ self, amt: int | None = 2**16, decode_content: bool | None = None
+ ) -> typing.Iterator[bytes]:
+ raise NotImplementedError()
+
+ def read(
+ self,
+ amt: int | None = None,
+ decode_content: bool | None = None,
+ cache_content: bool = False,
+ ) -> bytes:
+ raise NotImplementedError()
+
+ def read1(
+ self,
+ amt: int | None = None,
+ decode_content: bool | None = None,
+ ) -> bytes:
+ raise NotImplementedError()
+
+ def read_chunked(
+ self,
+ amt: int | None = None,
+ decode_content: bool | None = None,
+ ) -> typing.Iterator[bytes]:
+ raise NotImplementedError()
+
+ def release_conn(self) -> None:
+ raise NotImplementedError()
+
+ def drain_conn(self) -> None:
+ raise NotImplementedError()
+
+ def shutdown(self) -> None:
+ raise NotImplementedError()
+
+ def close(self) -> None:
+ raise NotImplementedError()
+
+ def _init_decoder(self) -> None:
+ """
+ Set-up the _decoder attribute if necessary.
+ """
+ # Note: content-encoding value should be case-insensitive, per RFC 7230
+ # Section 3.2
+ content_encoding = self.headers.get("content-encoding", "").lower()
+ if self._decoder is None:
+ if content_encoding in self.CONTENT_DECODERS:
+ self._decoder = _get_decoder(content_encoding)
+ elif "," in content_encoding:
+ encodings = [
+ e.strip()
+ for e in content_encoding.split(",")
+ if e.strip() in self.CONTENT_DECODERS
+ ]
+ if encodings:
+ self._decoder = _get_decoder(content_encoding)
+
+ def _decode(
+ self,
+ data: bytes,
+ decode_content: bool | None,
+ flush_decoder: bool,
+ max_length: int | None = None,
+ ) -> bytes:
+ """
+ Decode the data passed in and potentially flush the decoder.
+ """
+ if not decode_content:
+ if self._has_decoded_content:
+ raise RuntimeError(
+ "Calling read(decode_content=False) is not supported after "
+ "read(decode_content=True) was called."
+ )
+ return data
+
+ if max_length is None or flush_decoder:
+ max_length = -1
+
+ try:
+ if self._decoder:
+ data = self._decoder.decompress(data, max_length=max_length)
+ self._has_decoded_content = True
+ except self.DECODER_ERROR_CLASSES as e:
+ content_encoding = self.headers.get("content-encoding", "").lower()
+ raise DecodeError(
+ "Received response with content-encoding: %s, but "
+ "failed to decode it." % content_encoding,
+ e,
+ ) from e
+ if flush_decoder:
+ data += self._flush_decoder()
+
+ return data
+
+ def _flush_decoder(self) -> bytes:
+ """
+ Flushes the decoder. Should only be called if the decoder is actually
+ being used.
+ """
+ if self._decoder:
+ return self._decoder.decompress(b"") + self._decoder.flush()
+ return b""
+
+ # Compatibility methods for `io` module
+ def readinto(self, b: bytearray) -> int:
+ temp = self.read(len(b))
+ if len(temp) == 0:
+ return 0
+ else:
+ b[: len(temp)] = temp
+ return len(temp)
+
+ # Methods used by dependent libraries
+ def getheaders(self) -> HTTPHeaderDict:
+ return self.headers
+
+ def getheader(self, name: str, default: str | None = None) -> str | None:
+ return self.headers.get(name, default)
+
+ # Compatibility method for http.cookiejar
+ def info(self) -> HTTPHeaderDict:
+ return self.headers
+
+ def geturl(self) -> str | None:
+ return self.url
+
+
+class HTTPResponse(BaseHTTPResponse):
+ """
+ HTTP Response container.
+
+ Backwards-compatible with :class:`http.client.HTTPResponse` but the response ``body`` is
+ loaded and decoded on-demand when the ``data`` property is accessed. This
+ class is also compatible with the Python standard library's :mod:`io`
+ module, and can hence be treated as a readable object in the context of that
+ framework.
+
+ Extra parameters for behaviour not present in :class:`http.client.HTTPResponse`:
+
+ :param preload_content:
+ If True, the response's body will be preloaded during construction.
+
+ :param decode_content:
+ If True, will attempt to decode the body based on the
+ 'content-encoding' header.
+
+ :param original_response:
+ When this HTTPResponse wrapper is generated from an :class:`http.client.HTTPResponse`
+ object, it's convenient to include the original for debug purposes. It's
+ otherwise unused.
+
+ :param retries:
+ The retries contains the last :class:`~urllib3.util.retry.Retry` that
+ was used during the request.
+
+ :param enforce_content_length:
+ Enforce content length checking. Body returned by server must match
+ value of Content-Length header, if present. Otherwise, raise error.
+ """
+
+ def __init__(
+ self,
+ body: _TYPE_BODY = "",
+ headers: typing.Mapping[str, str] | typing.Mapping[bytes, bytes] | None = None,
+ status: int = 0,
+ version: int = 0,
+ version_string: str = "HTTP/?",
+ reason: str | None = None,
+ preload_content: bool = True,
+ decode_content: bool = True,
+ original_response: _HttplibHTTPResponse | None = None,
+ pool: HTTPConnectionPool | None = None,
+ connection: HTTPConnection | None = None,
+ msg: _HttplibHTTPMessage | None = None,
+ retries: Retry | None = None,
+ enforce_content_length: bool = True,
+ request_method: str | None = None,
+ request_url: str | None = None,
+ auto_close: bool = True,
+ sock_shutdown: typing.Callable[[int], None] | None = None,
+ ) -> None:
+ super().__init__(
+ headers=headers,
+ status=status,
+ version=version,
+ version_string=version_string,
+ reason=reason,
+ decode_content=decode_content,
+ request_url=request_url,
+ retries=retries,
+ )
+
+ self.enforce_content_length = enforce_content_length
+ self.auto_close = auto_close
+
+ self._body = None
+ self._fp: _HttplibHTTPResponse | None = None
+ self._original_response = original_response
+ self._fp_bytes_read = 0
+ self.msg = msg
+
+ if body and isinstance(body, (str, bytes)):
+ self._body = body
+
+ self._pool = pool
+ self._connection = connection
+
+ if hasattr(body, "read"):
+ self._fp = body # type: ignore[assignment]
+ self._sock_shutdown = sock_shutdown
+
+ # Are we using the chunked-style of transfer encoding?
+ self.chunk_left: int | None = None
+
+ # Determine length of response
+ self.length_remaining = self._init_length(request_method)
+
+ # Used to return the correct amount of bytes for partial read()s
+ self._decoded_buffer = BytesQueueBuffer()
+
+ # If requested, preload the body.
+ if preload_content and not self._body:
+ self._body = self.read(decode_content=decode_content)
+
+ def release_conn(self) -> None:
+ if not self._pool or not self._connection:
+ return None
+
+ self._pool._put_conn(self._connection)
+ self._connection = None
+
+ def drain_conn(self) -> None:
+ """
+ Read and discard any remaining HTTP response data in the response connection.
+
+ Unread data in the HTTPResponse connection blocks the connection from being released back to the pool.
+ """
+ try:
+ self.read(
+ # Do not spend resources decoding the content unless
+ # decoding has already been initiated.
+ decode_content=self._has_decoded_content,
+ )
+ except (HTTPError, OSError, BaseSSLError, HTTPException):
+ pass
+
+ @property
+ def data(self) -> bytes:
+ # For backwards-compat with earlier urllib3 0.4 and earlier.
+ if self._body:
+ return self._body # type: ignore[return-value]
+
+ if self._fp:
+ return self.read(cache_content=True)
+
+ return None # type: ignore[return-value]
+
+ @property
+ def connection(self) -> HTTPConnection | None:
+ return self._connection
+
+ def isclosed(self) -> bool:
+ return is_fp_closed(self._fp)
+
+ def tell(self) -> int:
+ """
+ Obtain the number of bytes pulled over the wire so far. May differ from
+ the amount of content returned by :meth:``urllib3.response.HTTPResponse.read``
+ if bytes are encoded on the wire (e.g, compressed).
+ """
+ return self._fp_bytes_read
+
+ def _init_length(self, request_method: str | None) -> int | None:
+ """
+ Set initial length value for Response content if available.
+ """
+ length: int | None
+ content_length: str | None = self.headers.get("content-length")
+
+ if content_length is not None:
+ if self.chunked:
+ # This Response will fail with an IncompleteRead if it can't be
+ # received as chunked. This method falls back to attempt reading
+ # the response before raising an exception.
+ log.warning(
+ "Received response with both Content-Length and "
+ "Transfer-Encoding set. This is expressly forbidden "
+ "by RFC 7230 sec 3.3.2. Ignoring Content-Length and "
+ "attempting to process response as Transfer-Encoding: "
+ "chunked."
+ )
+ return None
+
+ try:
+ # RFC 7230 section 3.3.2 specifies multiple content lengths can
+ # be sent in a single Content-Length header
+ # (e.g. Content-Length: 42, 42). This line ensures the values
+ # are all valid ints and that as long as the `set` length is 1,
+ # all values are the same. Otherwise, the header is invalid.
+ lengths = {int(val) for val in content_length.split(",")}
+ if len(lengths) > 1:
+ raise InvalidHeader(
+ "Content-Length contained multiple "
+ "unmatching values (%s)" % content_length
+ )
+ length = lengths.pop()
+ except ValueError:
+ length = None
+ else:
+ if length < 0:
+ length = None
+
+ else: # if content_length is None
+ length = None
+
+ # Convert status to int for comparison
+ # In some cases, httplib returns a status of "_UNKNOWN"
+ try:
+ status = int(self.status)
+ except ValueError:
+ status = 0
+
+ # Check for responses that shouldn't include a body
+ if status in (204, 304) or 100 <= status < 200 or request_method == "HEAD":
+ length = 0
+
+ return length
+
+ @contextmanager
+ def _error_catcher(self) -> typing.Generator[None]:
+ """
+ Catch low-level python exceptions, instead re-raising urllib3
+ variants, so that low-level exceptions are not leaked in the
+ high-level api.
+
+ On exit, release the connection back to the pool.
+ """
+ clean_exit = False
+
+ try:
+ try:
+ yield
+
+ except SocketTimeout as e:
+ # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but
+ # there is yet no clean way to get at it from this context.
+ raise ReadTimeoutError(self._pool, None, "Read timed out.") from e # type: ignore[arg-type]
+
+ except BaseSSLError as e:
+ # FIXME: Is there a better way to differentiate between SSLErrors?
+ if "read operation timed out" not in str(e):
+ # SSL errors related to framing/MAC get wrapped and reraised here
+ raise SSLError(e) from e
+
+ raise ReadTimeoutError(self._pool, None, "Read timed out.") from e # type: ignore[arg-type]
+
+ except IncompleteRead as e:
+ if (
+ e.expected is not None
+ and e.partial is not None
+ and e.expected == -e.partial
+ ):
+ arg = "Response may not contain content."
+ else:
+ arg = f"Connection broken: {e!r}"
+ raise ProtocolError(arg, e) from e
+
+ except (HTTPException, OSError) as e:
+ raise ProtocolError(f"Connection broken: {e!r}", e) from e
+
+ # If no exception is thrown, we should avoid cleaning up
+ # unnecessarily.
+ clean_exit = True
+ finally:
+ # If we didn't terminate cleanly, we need to throw away our
+ # connection.
+ if not clean_exit:
+ # The response may not be closed but we're not going to use it
+ # anymore so close it now to ensure that the connection is
+ # released back to the pool.
+ if self._original_response:
+ self._original_response.close()
+
+ # Closing the response may not actually be sufficient to close
+ # everything, so if we have a hold of the connection close that
+ # too.
+ if self._connection:
+ self._connection.close()
+
+ # If we hold the original response but it's closed now, we should
+ # return the connection back to the pool.
+ if self._original_response and self._original_response.isclosed():
+ self.release_conn()
+
+ def _fp_read(
+ self,
+ amt: int | None = None,
+ *,
+ read1: bool = False,
+ ) -> bytes:
+ """
+ Read a response with the thought that reading the number of bytes
+ larger than can fit in a 32-bit int at a time via SSL in some
+ known cases leads to an overflow error that has to be prevented
+ if `amt` or `self.length_remaining` indicate that a problem may
+ happen.
+
+ The known cases:
+ * CPython < 3.9.7 because of a bug
+ https://github.com/urllib3/urllib3/issues/2513#issuecomment-1152559900.
+ * urllib3 injected with pyOpenSSL-backed SSL-support.
+ * CPython < 3.10 only when `amt` does not fit 32-bit int.
+ """
+ assert self._fp
+ c_int_max = 2**31 - 1
+ if (
+ (amt and amt > c_int_max)
+ or (
+ amt is None
+ and self.length_remaining
+ and self.length_remaining > c_int_max
+ )
+ ) and (util.IS_PYOPENSSL or sys.version_info < (3, 10)):
+ if read1:
+ return self._fp.read1(c_int_max)
+ buffer = io.BytesIO()
+ # Besides `max_chunk_amt` being a maximum chunk size, it
+ # affects memory overhead of reading a response by this
+ # method in CPython.
+ # `c_int_max` equal to 2 GiB - 1 byte is the actual maximum
+ # chunk size that does not lead to an overflow error, but
+ # 256 MiB is a compromise.
+ max_chunk_amt = 2**28
+ while amt is None or amt != 0:
+ if amt is not None:
+ chunk_amt = min(amt, max_chunk_amt)
+ amt -= chunk_amt
+ else:
+ chunk_amt = max_chunk_amt
+ data = self._fp.read(chunk_amt)
+ if not data:
+ break
+ buffer.write(data)
+ del data # to reduce peak memory usage by `max_chunk_amt`.
+ return buffer.getvalue()
+ elif read1:
+ return self._fp.read1(amt) if amt is not None else self._fp.read1()
+ else:
+ # StringIO doesn't like amt=None
+ return self._fp.read(amt) if amt is not None else self._fp.read()
+
+ def _raw_read(
+ self,
+ amt: int | None = None,
+ *,
+ read1: bool = False,
+ ) -> bytes:
+ """
+ Reads `amt` of bytes from the socket.
+ """
+ if self._fp is None:
+ return None # type: ignore[return-value]
+
+ fp_closed = getattr(self._fp, "closed", False)
+
+ with self._error_catcher():
+ data = self._fp_read(amt, read1=read1) if not fp_closed else b""
+ if amt is not None and amt != 0 and not data:
+ # Platform-specific: Buggy versions of Python.
+ # Close the connection when no data is returned
+ #
+ # This is redundant to what httplib/http.client _should_
+ # already do. However, versions of python released before
+ # December 15, 2012 (http://bugs.python.org/issue16298) do
+ # not properly close the connection in all cases. There is
+ # no harm in redundantly calling close.
+ self._fp.close()
+ if (
+ self.enforce_content_length
+ and self.length_remaining is not None
+ and self.length_remaining != 0
+ ):
+ # This is an edge case that httplib failed to cover due
+ # to concerns of backward compatibility. We're
+ # addressing it here to make sure IncompleteRead is
+ # raised during streaming, so all calls with incorrect
+ # Content-Length are caught.
+ raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
+ elif read1 and (
+ (amt != 0 and not data) or self.length_remaining == len(data)
+ ):
+ # All data has been read, but `self._fp.read1` in
+ # CPython 3.12 and older doesn't always close
+ # `http.client.HTTPResponse`, so we close it here.
+ # See https://github.com/python/cpython/issues/113199
+ self._fp.close()
+
+ if data:
+ self._fp_bytes_read += len(data)
+ if self.length_remaining is not None:
+ self.length_remaining -= len(data)
+ return data
+
+ def read(
+ self,
+ amt: int | None = None,
+ decode_content: bool | None = None,
+ cache_content: bool = False,
+ ) -> bytes:
+ """
+ Similar to :meth:`http.client.HTTPResponse.read`, but with two additional
+ parameters: ``decode_content`` and ``cache_content``.
+
+ :param amt:
+ How much of the content to read. If specified, caching is skipped
+ because it doesn't make sense to cache partial content as the full
+ response.
+
+ :param decode_content:
+ If True, will attempt to decode the body based on the
+ 'content-encoding' header.
+
+ :param cache_content:
+ If True, will save the returned data such that the same result is
+ returned despite of the state of the underlying file object. This
+ is useful if you want the ``.data`` property to continue working
+ after having ``.read()`` the file object. (Overridden if ``amt`` is
+ set.)
+ """
+ self._init_decoder()
+ if decode_content is None:
+ decode_content = self.decode_content
+
+ if amt and amt < 0:
+ # Negative numbers and `None` should be treated the same.
+ amt = None
+ elif amt is not None:
+ cache_content = False
+
+ if self._decoder and self._decoder.has_unconsumed_tail:
+ decoded_data = self._decode(
+ b"",
+ decode_content,
+ flush_decoder=False,
+ max_length=amt - len(self._decoded_buffer),
+ )
+ self._decoded_buffer.put(decoded_data)
+ if len(self._decoded_buffer) >= amt:
+ return self._decoded_buffer.get(amt)
+
+ data = self._raw_read(amt)
+
+ flush_decoder = amt is None or (amt != 0 and not data)
+
+ if (
+ not data
+ and len(self._decoded_buffer) == 0
+ and not (self._decoder and self._decoder.has_unconsumed_tail)
+ ):
+ return data
+
+ if amt is None:
+ data = self._decode(data, decode_content, flush_decoder)
+ if cache_content:
+ self._body = data
+ else:
+ # do not waste memory on buffer when not decoding
+ if not decode_content:
+ if self._has_decoded_content:
+ raise RuntimeError(
+ "Calling read(decode_content=False) is not supported after "
+ "read(decode_content=True) was called."
+ )
+ return data
+
+ decoded_data = self._decode(
+ data,
+ decode_content,
+ flush_decoder,
+ max_length=amt - len(self._decoded_buffer),
+ )
+ self._decoded_buffer.put(decoded_data)
+
+ while len(self._decoded_buffer) < amt and data:
+ # TODO make sure to initially read enough data to get past the headers
+ # For example, the GZ file header takes 10 bytes, we don't want to read
+ # it one byte at a time
+ data = self._raw_read(amt)
+ decoded_data = self._decode(
+ data,
+ decode_content,
+ flush_decoder,
+ max_length=amt - len(self._decoded_buffer),
+ )
+ self._decoded_buffer.put(decoded_data)
+ data = self._decoded_buffer.get(amt)
+
+ return data
+
+ def read1(
+ self,
+ amt: int | None = None,
+ decode_content: bool | None = None,
+ ) -> bytes:
+ """
+ Similar to ``http.client.HTTPResponse.read1`` and documented
+ in :meth:`io.BufferedReader.read1`, but with an additional parameter:
+ ``decode_content``.
+
+ :param amt:
+ How much of the content to read.
+
+ :param decode_content:
+ If True, will attempt to decode the body based on the
+ 'content-encoding' header.
+ """
+ if decode_content is None:
+ decode_content = self.decode_content
+ if amt and amt < 0:
+ # Negative numbers and `None` should be treated the same.
+ amt = None
+ # try and respond without going to the network
+ if self._has_decoded_content:
+ if not decode_content:
+ raise RuntimeError(
+ "Calling read1(decode_content=False) is not supported after "
+ "read1(decode_content=True) was called."
+ )
+ if (
+ self._decoder
+ and self._decoder.has_unconsumed_tail
+ and (amt is None or len(self._decoded_buffer) < amt)
+ ):
+ decoded_data = self._decode(
+ b"",
+ decode_content,
+ flush_decoder=False,
+ max_length=(
+ amt - len(self._decoded_buffer) if amt is not None else None
+ ),
+ )
+ self._decoded_buffer.put(decoded_data)
+ if len(self._decoded_buffer) > 0:
+ if amt is None:
+ return self._decoded_buffer.get_all()
+ return self._decoded_buffer.get(amt)
+ if amt == 0:
+ return b""
+
+ # FIXME, this method's type doesn't say returning None is possible
+ data = self._raw_read(amt, read1=True)
+ if not decode_content or data is None:
+ return data
+
+ self._init_decoder()
+ while True:
+ flush_decoder = not data
+ decoded_data = self._decode(
+ data, decode_content, flush_decoder, max_length=amt
+ )
+ self._decoded_buffer.put(decoded_data)
+ if decoded_data or flush_decoder:
+ break
+ data = self._raw_read(8192, read1=True)
+
+ if amt is None:
+ return self._decoded_buffer.get_all()
+ return self._decoded_buffer.get(amt)
+
+ def stream(
+ self, amt: int | None = 2**16, decode_content: bool | None = None
+ ) -> typing.Generator[bytes]:
+ """
+ A generator wrapper for the read() method. A call will block until
+ ``amt`` bytes have been read from the connection or until the
+ connection is closed.
+
+ :param amt:
+ How much of the content to read. The generator will return up to
+ much data per iteration, but may return less. This is particularly
+ likely when using compressed data. However, the empty string will
+ never be returned.
+
+ :param decode_content:
+ If True, will attempt to decode the body based on the
+ 'content-encoding' header.
+ """
+ if self.chunked and self.supports_chunked_reads():
+ yield from self.read_chunked(amt, decode_content=decode_content)
+ else:
+ while (
+ not is_fp_closed(self._fp)
+ or len(self._decoded_buffer) > 0
+ or (self._decoder and self._decoder.has_unconsumed_tail)
+ ):
+ data = self.read(amt=amt, decode_content=decode_content)
+
+ if data:
+ yield data
+
+ # Overrides from io.IOBase
+ def readable(self) -> bool:
+ return True
+
+ def shutdown(self) -> None:
+ if not self._sock_shutdown:
+ raise ValueError("Cannot shutdown socket as self._sock_shutdown is not set")
+ if self._connection is None:
+ raise RuntimeError(
+ "Cannot shutdown as connection has already been released to the pool"
+ )
+ self._sock_shutdown(socket.SHUT_RD)
+
+ def close(self) -> None:
+ self._sock_shutdown = None
+
+ if not self.closed and self._fp:
+ self._fp.close()
+
+ if self._connection:
+ self._connection.close()
+
+ if not self.auto_close:
+ io.IOBase.close(self)
+
+ @property
+ def closed(self) -> bool:
+ if not self.auto_close:
+ return io.IOBase.closed.__get__(self) # type: ignore[no-any-return]
+ elif self._fp is None:
+ return True
+ elif hasattr(self._fp, "isclosed"):
+ return self._fp.isclosed()
+ elif hasattr(self._fp, "closed"):
+ return self._fp.closed
+ else:
+ return True
+
+ def fileno(self) -> int:
+ if self._fp is None:
+ raise OSError("HTTPResponse has no file to get a fileno from")
+ elif hasattr(self._fp, "fileno"):
+ return self._fp.fileno()
+ else:
+ raise OSError(
+ "The file-like object this HTTPResponse is wrapped "
+ "around has no file descriptor"
+ )
+
+ def flush(self) -> None:
+ if (
+ self._fp is not None
+ and hasattr(self._fp, "flush")
+ and not getattr(self._fp, "closed", False)
+ ):
+ return self._fp.flush()
+
+ def supports_chunked_reads(self) -> bool:
+ """
+ Checks if the underlying file-like object looks like a
+ :class:`http.client.HTTPResponse` object. We do this by testing for
+ the fp attribute. If it is present we assume it returns raw chunks as
+ processed by read_chunked().
+ """
+ return hasattr(self._fp, "fp")
+
+ def _update_chunk_length(self) -> None:
+ # First, we'll figure out length of a chunk and then
+ # we'll try to read it from socket.
+ if self.chunk_left is not None:
+ return None
+ line = self._fp.fp.readline() # type: ignore[union-attr]
+ line = line.split(b";", 1)[0]
+ try:
+ self.chunk_left = int(line, 16)
+ except ValueError:
+ self.close()
+ if line:
+ # Invalid chunked protocol response, abort.
+ raise InvalidChunkLength(self, line) from None
+ else:
+ # Truncated at start of next chunk
+ raise ProtocolError("Response ended prematurely") from None
+
+ def _handle_chunk(self, amt: int | None) -> bytes:
+ returned_chunk = None
+ if amt is None:
+ chunk = self._fp._safe_read(self.chunk_left) # type: ignore[union-attr]
+ returned_chunk = chunk
+ self._fp._safe_read(2) # type: ignore[union-attr] # Toss the CRLF at the end of the chunk.
+ self.chunk_left = None
+ elif self.chunk_left is not None and amt < self.chunk_left:
+ value = self._fp._safe_read(amt) # type: ignore[union-attr]
+ self.chunk_left = self.chunk_left - amt
+ returned_chunk = value
+ elif amt == self.chunk_left:
+ value = self._fp._safe_read(amt) # type: ignore[union-attr]
+ self._fp._safe_read(2) # type: ignore[union-attr] # Toss the CRLF at the end of the chunk.
+ self.chunk_left = None
+ returned_chunk = value
+ else: # amt > self.chunk_left
+ returned_chunk = self._fp._safe_read(self.chunk_left) # type: ignore[union-attr]
+ self._fp._safe_read(2) # type: ignore[union-attr] # Toss the CRLF at the end of the chunk.
+ self.chunk_left = None
+ return returned_chunk # type: ignore[no-any-return]
+
+ def read_chunked(
+ self, amt: int | None = None, decode_content: bool | None = None
+ ) -> typing.Generator[bytes]:
+ """
+ Similar to :meth:`HTTPResponse.read`, but with an additional
+ parameter: ``decode_content``.
+
+ :param amt:
+ How much of the content to read. If specified, caching is skipped
+ because it doesn't make sense to cache partial content as the full
+ response.
+
+ :param decode_content:
+ If True, will attempt to decode the body based on the
+ 'content-encoding' header.
+ """
+ self._init_decoder()
+ # FIXME: Rewrite this method and make it a class with a better structured logic.
+ if not self.chunked:
+ raise ResponseNotChunked(
+ "Response is not chunked. "
+ "Header 'transfer-encoding: chunked' is missing."
+ )
+ if not self.supports_chunked_reads():
+ raise BodyNotHttplibCompatible(
+ "Body should be http.client.HTTPResponse like. "
+ "It should have have an fp attribute which returns raw chunks."
+ )
+
+ with self._error_catcher():
+ # Don't bother reading the body of a HEAD request.
+ if self._original_response and is_response_to_head(self._original_response):
+ self._original_response.close()
+ return None
+
+ # If a response is already read and closed
+ # then return immediately.
+ if self._fp.fp is None: # type: ignore[union-attr]
+ return None
+
+ if amt and amt < 0:
+ # Negative numbers and `None` should be treated the same,
+ # but httplib handles only `None` correctly.
+ amt = None
+
+ while True:
+ # First, check if any data is left in the decoder's buffer.
+ if self._decoder and self._decoder.has_unconsumed_tail:
+ chunk = b""
+ else:
+ self._update_chunk_length()
+ if self.chunk_left == 0:
+ break
+ chunk = self._handle_chunk(amt)
+ decoded = self._decode(
+ chunk,
+ decode_content=decode_content,
+ flush_decoder=False,
+ max_length=amt,
+ )
+ if decoded:
+ yield decoded
+
+ if decode_content:
+ # On CPython and PyPy, we should never need to flush the
+ # decoder. However, on Jython we *might* need to, so
+ # lets defensively do it anyway.
+ decoded = self._flush_decoder()
+ if decoded: # Platform-specific: Jython.
+ yield decoded
+
+ # Chunk content ends with \r\n: discard it.
+ while self._fp is not None:
+ line = self._fp.fp.readline()
+ if not line:
+ # Some sites may not end with '\r\n'.
+ break
+ if line == b"\r\n":
+ break
+
+ # We read everything; close the "file".
+ if self._original_response:
+ self._original_response.close()
+
+ @property
+ def url(self) -> str | None:
+ """
+ Returns the URL that was the source of this response.
+ If the request that generated this response redirected, this method
+ will return the final redirect location.
+ """
+ return self._request_url
+
+ @url.setter
+ def url(self, url: str | None) -> None:
+ self._request_url = url
+
+ def __iter__(self) -> typing.Iterator[bytes]:
+ buffer: list[bytes] = []
+ for chunk in self.stream(decode_content=True):
+ if b"\n" in chunk:
+ chunks = chunk.split(b"\n")
+ yield b"".join(buffer) + chunks[0] + b"\n"
+ for x in chunks[1:-1]:
+ yield x + b"\n"
+ if chunks[-1]:
+ buffer = [chunks[-1]]
+ else:
+ buffer = []
+ else:
+ buffer.append(chunk)
+ if buffer:
+ yield b"".join(buffer)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..534126033c083203649022fa9b753a433f005556
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/__init__.py
@@ -0,0 +1,42 @@
+# For backwards compatibility, provide imports that used to be here.
+from __future__ import annotations
+
+from .connection import is_connection_dropped
+from .request import SKIP_HEADER, SKIPPABLE_HEADERS, make_headers
+from .response import is_fp_closed
+from .retry import Retry
+from .ssl_ import (
+ ALPN_PROTOCOLS,
+ IS_PYOPENSSL,
+ SSLContext,
+ assert_fingerprint,
+ create_urllib3_context,
+ resolve_cert_reqs,
+ resolve_ssl_version,
+ ssl_wrap_socket,
+)
+from .timeout import Timeout
+from .url import Url, parse_url
+from .wait import wait_for_read, wait_for_write
+
+__all__ = (
+ "IS_PYOPENSSL",
+ "SSLContext",
+ "ALPN_PROTOCOLS",
+ "Retry",
+ "Timeout",
+ "Url",
+ "assert_fingerprint",
+ "create_urllib3_context",
+ "is_connection_dropped",
+ "is_fp_closed",
+ "parse_url",
+ "make_headers",
+ "resolve_cert_reqs",
+ "resolve_ssl_version",
+ "ssl_wrap_socket",
+ "wait_for_read",
+ "wait_for_write",
+ "SKIP_HEADER",
+ "SKIPPABLE_HEADERS",
+)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/connection.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/connection.py
new file mode 100644
index 0000000000000000000000000000000000000000..f92519ee9124e91e5da7d60ccc3f274312ed3514
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/connection.py
@@ -0,0 +1,137 @@
+from __future__ import annotations
+
+import socket
+import typing
+
+from ..exceptions import LocationParseError
+from .timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT
+
+_TYPE_SOCKET_OPTIONS = list[tuple[int, int, typing.Union[int, bytes]]]
+
+if typing.TYPE_CHECKING:
+ from .._base_connection import BaseHTTPConnection
+
+
+def is_connection_dropped(conn: BaseHTTPConnection) -> bool: # Platform-specific
+ """
+ Returns True if the connection is dropped and should be closed.
+ :param conn: :class:`urllib3.connection.HTTPConnection` object.
+ """
+ return not conn.is_connected
+
+
+# This function is copied from socket.py in the Python 2.7 standard
+# library test suite. Added to its signature is only `socket_options`.
+# One additional modification is that we avoid binding to IPv6 servers
+# discovered in DNS if the system doesn't have IPv6 functionality.
+def create_connection(
+ address: tuple[str, int],
+ timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,
+ source_address: tuple[str, int] | None = None,
+ socket_options: _TYPE_SOCKET_OPTIONS | None = None,
+) -> socket.socket:
+ """Connect to *address* and return the socket object.
+
+ Convenience function. Connect to *address* (a 2-tuple ``(host,
+ port)``) and return the socket object. Passing the optional
+ *timeout* parameter will set the timeout on the socket instance
+ before attempting to connect. If no *timeout* is supplied, the
+ global default timeout setting returned by :func:`socket.getdefaulttimeout`
+ is used. If *source_address* is set it must be a tuple of (host, port)
+ for the socket to bind as a source address before making the connection.
+ An host of '' or port 0 tells the OS to use the default.
+ """
+
+ host, port = address
+ if host.startswith("["):
+ host = host.strip("[]")
+ err = None
+
+ # Using the value from allowed_gai_family() in the context of getaddrinfo lets
+ # us select whether to work with IPv4 DNS records, IPv6 records, or both.
+ # The original create_connection function always returns all records.
+ family = allowed_gai_family()
+
+ try:
+ host.encode("idna")
+ except UnicodeError:
+ raise LocationParseError(f"'{host}', label empty or too long") from None
+
+ for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
+ af, socktype, proto, canonname, sa = res
+ sock = None
+ try:
+ sock = socket.socket(af, socktype, proto)
+
+ # If provided, set socket level options before connecting.
+ _set_socket_options(sock, socket_options)
+
+ if timeout is not _DEFAULT_TIMEOUT:
+ sock.settimeout(timeout)
+ if source_address:
+ sock.bind(source_address)
+ sock.connect(sa)
+ # Break explicitly a reference cycle
+ err = None
+ return sock
+
+ except OSError as _:
+ err = _
+ if sock is not None:
+ sock.close()
+
+ if err is not None:
+ try:
+ raise err
+ finally:
+ # Break explicitly a reference cycle
+ err = None
+ else:
+ raise OSError("getaddrinfo returns an empty list")
+
+
+def _set_socket_options(
+ sock: socket.socket, options: _TYPE_SOCKET_OPTIONS | None
+) -> None:
+ if options is None:
+ return
+
+ for opt in options:
+ sock.setsockopt(*opt)
+
+
+def allowed_gai_family() -> socket.AddressFamily:
+ """This function is designed to work in the context of
+ getaddrinfo, where family=socket.AF_UNSPEC is the default and
+ will perform a DNS search for both IPv6 and IPv4 records."""
+
+ family = socket.AF_INET
+ if HAS_IPV6:
+ family = socket.AF_UNSPEC
+ return family
+
+
+def _has_ipv6(host: str) -> bool:
+ """Returns True if the system can bind an IPv6 address."""
+ sock = None
+ has_ipv6 = False
+
+ if socket.has_ipv6:
+ # has_ipv6 returns true if cPython was compiled with IPv6 support.
+ # It does not tell us if the system has IPv6 support enabled. To
+ # determine that we must bind to an IPv6 address.
+ # https://github.com/urllib3/urllib3/pull/611
+ # https://bugs.python.org/issue658327
+ try:
+ sock = socket.socket(socket.AF_INET6)
+ sock.bind((host, 0))
+ has_ipv6 = True
+ except Exception:
+ pass
+
+ if sock:
+ sock.close()
+ return has_ipv6
+
+
+HAS_IPV6 = _has_ipv6("::1")
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/proxy.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/proxy.py
new file mode 100644
index 0000000000000000000000000000000000000000..908fc6621d0afbed16bde2c1957a5cf28d3a84d8
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/proxy.py
@@ -0,0 +1,43 @@
+from __future__ import annotations
+
+import typing
+
+from .url import Url
+
+if typing.TYPE_CHECKING:
+ from ..connection import ProxyConfig
+
+
+def connection_requires_http_tunnel(
+ proxy_url: Url | None = None,
+ proxy_config: ProxyConfig | None = None,
+ destination_scheme: str | None = None,
+) -> bool:
+ """
+ Returns True if the connection requires an HTTP CONNECT through the proxy.
+
+ :param URL proxy_url:
+ URL of the proxy.
+ :param ProxyConfig proxy_config:
+ Proxy configuration from poolmanager.py
+ :param str destination_scheme:
+ The scheme of the destination. (i.e https, http, etc)
+ """
+ # If we're not using a proxy, no way to use a tunnel.
+ if proxy_url is None:
+ return False
+
+ # HTTP destinations never require tunneling, we always forward.
+ if destination_scheme == "http":
+ return False
+
+ # Support for forwarding with HTTPS proxies and HTTPS destinations.
+ if (
+ proxy_url.scheme == "https"
+ and proxy_config
+ and proxy_config.use_forwarding_for_https
+ ):
+ return False
+
+ # Otherwise always use a tunnel.
+ return True
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/request.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/request.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c2372ba7e777826a4eb124ddfb54f0240b65d67
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/request.py
@@ -0,0 +1,263 @@
+from __future__ import annotations
+
+import io
+import sys
+import typing
+from base64 import b64encode
+from enum import Enum
+
+from ..exceptions import UnrewindableBodyError
+from .util import to_bytes
+
+if typing.TYPE_CHECKING:
+ from typing import Final
+
+# Pass as a value within ``headers`` to skip
+# emitting some HTTP headers that are added automatically.
+# The only headers that are supported are ``Accept-Encoding``,
+# ``Host``, and ``User-Agent``.
+SKIP_HEADER = "@@@SKIP_HEADER@@@"
+SKIPPABLE_HEADERS = frozenset(["accept-encoding", "host", "user-agent"])
+
+ACCEPT_ENCODING = "gzip,deflate"
+try:
+ try:
+ import brotlicffi as _unused_module_brotli # type: ignore[import-not-found] # noqa: F401
+ except ImportError:
+ import brotli as _unused_module_brotli # type: ignore[import-not-found] # noqa: F401
+except ImportError:
+ pass
+else:
+ ACCEPT_ENCODING += ",br"
+
+try:
+ if sys.version_info >= (3, 14):
+ from compression import zstd as _unused_module_zstd # noqa: F401
+ else:
+ from backports import zstd as _unused_module_zstd # noqa: F401
+except ImportError:
+ pass
+else:
+ ACCEPT_ENCODING += ",zstd"
+
+
+class _TYPE_FAILEDTELL(Enum):
+ token = 0
+
+
+_FAILEDTELL: Final[_TYPE_FAILEDTELL] = _TYPE_FAILEDTELL.token
+
+_TYPE_BODY_POSITION = typing.Union[int, _TYPE_FAILEDTELL]
+
+# When sending a request with these methods we aren't expecting
+# a body so don't need to set an explicit 'Content-Length: 0'
+# The reason we do this in the negative instead of tracking methods
+# which 'should' have a body is because unknown methods should be
+# treated as if they were 'POST' which *does* expect a body.
+_METHODS_NOT_EXPECTING_BODY = {"GET", "HEAD", "DELETE", "TRACE", "OPTIONS", "CONNECT"}
+
+
+def make_headers(
+ keep_alive: bool | None = None,
+ accept_encoding: bool | list[str] | str | None = None,
+ user_agent: str | None = None,
+ basic_auth: str | None = None,
+ proxy_basic_auth: str | None = None,
+ disable_cache: bool | None = None,
+) -> dict[str, str]:
+ """
+ Shortcuts for generating request headers.
+
+ :param keep_alive:
+ If ``True``, adds 'connection: keep-alive' header.
+
+ :param accept_encoding:
+ Can be a boolean, list, or string.
+ ``True`` translates to 'gzip,deflate'. If the dependencies for
+ Brotli (either the ``brotli`` or ``brotlicffi`` package) and/or
+ Zstandard (the ``backports.zstd`` package for Python before 3.14)
+ algorithms are installed, then their encodings are
+ included in the string ('br' and 'zstd', respectively).
+ List will get joined by comma.
+ String will be used as provided.
+
+ :param user_agent:
+ String representing the user-agent you want, such as
+ "python-urllib3/0.6"
+
+ :param basic_auth:
+ Colon-separated username:password string for 'authorization: basic ...'
+ auth header.
+
+ :param proxy_basic_auth:
+ Colon-separated username:password string for 'proxy-authorization: basic ...'
+ auth header.
+
+ :param disable_cache:
+ If ``True``, adds 'cache-control: no-cache' header.
+
+ Example:
+
+ .. code-block:: python
+
+ import urllib3
+
+ print(urllib3.util.make_headers(keep_alive=True, user_agent="Batman/1.0"))
+ # {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}
+ print(urllib3.util.make_headers(accept_encoding=True))
+ # {'accept-encoding': 'gzip,deflate'}
+ """
+ headers: dict[str, str] = {}
+ if accept_encoding:
+ if isinstance(accept_encoding, str):
+ pass
+ elif isinstance(accept_encoding, list):
+ accept_encoding = ",".join(accept_encoding)
+ else:
+ accept_encoding = ACCEPT_ENCODING
+ headers["accept-encoding"] = accept_encoding
+
+ if user_agent:
+ headers["user-agent"] = user_agent
+
+ if keep_alive:
+ headers["connection"] = "keep-alive"
+
+ if basic_auth:
+ headers["authorization"] = (
+ f"Basic {b64encode(basic_auth.encode('latin-1')).decode()}"
+ )
+
+ if proxy_basic_auth:
+ headers["proxy-authorization"] = (
+ f"Basic {b64encode(proxy_basic_auth.encode('latin-1')).decode()}"
+ )
+
+ if disable_cache:
+ headers["cache-control"] = "no-cache"
+
+ return headers
+
+
+def set_file_position(
+ body: typing.Any, pos: _TYPE_BODY_POSITION | None
+) -> _TYPE_BODY_POSITION | None:
+ """
+ If a position is provided, move file to that point.
+ Otherwise, we'll attempt to record a position for future use.
+ """
+ if pos is not None:
+ rewind_body(body, pos)
+ elif getattr(body, "tell", None) is not None:
+ try:
+ pos = body.tell()
+ except OSError:
+ # This differentiates from None, allowing us to catch
+ # a failed `tell()` later when trying to rewind the body.
+ pos = _FAILEDTELL
+
+ return pos
+
+
+def rewind_body(body: typing.IO[typing.AnyStr], body_pos: _TYPE_BODY_POSITION) -> None:
+ """
+ Attempt to rewind body to a certain position.
+ Primarily used for request redirects and retries.
+
+ :param body:
+ File-like object that supports seek.
+
+ :param int pos:
+ Position to seek to in file.
+ """
+ body_seek = getattr(body, "seek", None)
+ if body_seek is not None and isinstance(body_pos, int):
+ try:
+ body_seek(body_pos)
+ except OSError as e:
+ raise UnrewindableBodyError(
+ "An error occurred when rewinding request body for redirect/retry."
+ ) from e
+ elif body_pos is _FAILEDTELL:
+ raise UnrewindableBodyError(
+ "Unable to record file position for rewinding "
+ "request body during a redirect/retry."
+ )
+ else:
+ raise ValueError(
+ f"body_pos must be of type integer, instead it was {type(body_pos)}."
+ )
+
+
+class ChunksAndContentLength(typing.NamedTuple):
+ chunks: typing.Iterable[bytes] | None
+ content_length: int | None
+
+
+def body_to_chunks(
+ body: typing.Any | None, method: str, blocksize: int
+) -> ChunksAndContentLength:
+ """Takes the HTTP request method, body, and blocksize and
+ transforms them into an iterable of chunks to pass to
+ socket.sendall() and an optional 'Content-Length' header.
+
+ A 'Content-Length' of 'None' indicates the length of the body
+ can't be determined so should use 'Transfer-Encoding: chunked'
+ for framing instead.
+ """
+
+ chunks: typing.Iterable[bytes] | None
+ content_length: int | None
+
+ # No body, we need to make a recommendation on 'Content-Length'
+ # based on whether that request method is expected to have
+ # a body or not.
+ if body is None:
+ chunks = None
+ if method.upper() not in _METHODS_NOT_EXPECTING_BODY:
+ content_length = 0
+ else:
+ content_length = None
+
+ # Bytes or strings become bytes
+ elif isinstance(body, (str, bytes)):
+ chunks = (to_bytes(body),)
+ content_length = len(chunks[0])
+
+ # File-like object, TODO: use seek() and tell() for length?
+ elif hasattr(body, "read"):
+
+ def chunk_readable() -> typing.Iterable[bytes]:
+ encode = isinstance(body, io.TextIOBase)
+ while True:
+ datablock = body.read(blocksize)
+ if not datablock:
+ break
+ if encode:
+ datablock = datablock.encode("utf-8")
+ yield datablock
+
+ chunks = chunk_readable()
+ content_length = None
+
+ # Otherwise we need to start checking via duck-typing.
+ else:
+ try:
+ # Check if the body implements the buffer API.
+ mv = memoryview(body)
+ except TypeError:
+ try:
+ # Check if the body is an iterable
+ chunks = iter(body)
+ content_length = None
+ except TypeError:
+ raise TypeError(
+ f"'body' must be a bytes-like object, file-like "
+ f"object, or iterable. Instead was {body!r}"
+ ) from None
+ else:
+ # Since it implements the buffer API can be passed directly to socket.sendall()
+ chunks = (body,)
+ content_length = mv.nbytes
+
+ return ChunksAndContentLength(chunks=chunks, content_length=content_length)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/response.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/response.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f4578696fa2e17a900c6890ec26d65e860b0b72
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/response.py
@@ -0,0 +1,101 @@
+from __future__ import annotations
+
+import http.client as httplib
+from email.errors import MultipartInvariantViolationDefect, StartBoundaryNotFoundDefect
+
+from ..exceptions import HeaderParsingError
+
+
+def is_fp_closed(obj: object) -> bool:
+ """
+ Checks whether a given file-like object is closed.
+
+ :param obj:
+ The file-like object to check.
+ """
+
+ try:
+ # Check `isclosed()` first, in case Python3 doesn't set `closed`.
+ # GH Issue #928
+ return obj.isclosed() # type: ignore[no-any-return, attr-defined]
+ except AttributeError:
+ pass
+
+ try:
+ # Check via the official file-like-object way.
+ return obj.closed # type: ignore[no-any-return, attr-defined]
+ except AttributeError:
+ pass
+
+ try:
+ # Check if the object is a container for another file-like object that
+ # gets released on exhaustion (e.g. HTTPResponse).
+ return obj.fp is None # type: ignore[attr-defined]
+ except AttributeError:
+ pass
+
+ raise ValueError("Unable to determine whether fp is closed.")
+
+
+def assert_header_parsing(headers: httplib.HTTPMessage) -> None:
+ """
+ Asserts whether all headers have been successfully parsed.
+ Extracts encountered errors from the result of parsing headers.
+
+ Only works on Python 3.
+
+ :param http.client.HTTPMessage headers: Headers to verify.
+
+ :raises urllib3.exceptions.HeaderParsingError:
+ If parsing errors are found.
+ """
+
+ # This will fail silently if we pass in the wrong kind of parameter.
+ # To make debugging easier add an explicit check.
+ if not isinstance(headers, httplib.HTTPMessage):
+ raise TypeError(f"expected httplib.Message, got {type(headers)}.")
+
+ unparsed_data = None
+
+ # get_payload is actually email.message.Message.get_payload;
+ # we're only interested in the result if it's not a multipart message
+ if not headers.is_multipart():
+ payload = headers.get_payload()
+
+ if isinstance(payload, (bytes, str)):
+ unparsed_data = payload
+
+ # httplib is assuming a response body is available
+ # when parsing headers even when httplib only sends
+ # header data to parse_headers() This results in
+ # defects on multipart responses in particular.
+ # See: https://github.com/urllib3/urllib3/issues/800
+
+ # So we ignore the following defects:
+ # - StartBoundaryNotFoundDefect:
+ # The claimed start boundary was never found.
+ # - MultipartInvariantViolationDefect:
+ # A message claimed to be a multipart but no subparts were found.
+ defects = [
+ defect
+ for defect in headers.defects
+ if not isinstance(
+ defect, (StartBoundaryNotFoundDefect, MultipartInvariantViolationDefect)
+ )
+ ]
+
+ if defects or unparsed_data:
+ raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data)
+
+
+def is_response_to_head(response: httplib.HTTPResponse) -> bool:
+ """
+ Checks whether the request of a response has been a HEAD-request.
+
+ :param http.client.HTTPResponse response:
+ Response to check if the originating request
+ used 'HEAD' as a method.
+ """
+ # FIXME: Can we do this somehow without accessing private httplib _method?
+ method_str = response._method # type: str # type: ignore[attr-defined]
+ return method_str.upper() == "HEAD"
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/retry.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/retry.py
new file mode 100644
index 0000000000000000000000000000000000000000..b21b4b64ebbd4748eb6fa4301f947b0d4965da8b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/retry.py
@@ -0,0 +1,549 @@
+from __future__ import annotations
+
+import email
+import logging
+import random
+import re
+import time
+import typing
+from itertools import takewhile
+from types import TracebackType
+
+from ..exceptions import (
+ ConnectTimeoutError,
+ InvalidHeader,
+ MaxRetryError,
+ ProtocolError,
+ ProxyError,
+ ReadTimeoutError,
+ ResponseError,
+)
+from .util import reraise
+
+if typing.TYPE_CHECKING:
+ from typing_extensions import Self
+
+ from ..connectionpool import ConnectionPool
+ from ..response import BaseHTTPResponse
+
+log = logging.getLogger(__name__)
+
+
+# Data structure for representing the metadata of requests that result in a retry.
+class RequestHistory(typing.NamedTuple):
+ method: str | None
+ url: str | None
+ error: Exception | None
+ status: int | None
+ redirect_location: str | None
+
+
+class Retry:
+ """Retry configuration.
+
+ Each retry attempt will create a new Retry object with updated values, so
+ they can be safely reused.
+
+ Retries can be defined as a default for a pool:
+
+ .. code-block:: python
+
+ retries = Retry(connect=5, read=2, redirect=5)
+ http = PoolManager(retries=retries)
+ response = http.request("GET", "https://example.com/")
+
+ Or per-request (which overrides the default for the pool):
+
+ .. code-block:: python
+
+ response = http.request("GET", "https://example.com/", retries=Retry(10))
+
+ Retries can be disabled by passing ``False``:
+
+ .. code-block:: python
+
+ response = http.request("GET", "https://example.com/", retries=False)
+
+ Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless
+ retries are disabled, in which case the causing exception will be raised.
+
+ :param int total:
+ Total number of retries to allow. Takes precedence over other counts.
+
+ Set to ``None`` to remove this constraint and fall back on other
+ counts.
+
+ Set to ``0`` to fail on the first retry.
+
+ Set to ``False`` to disable and imply ``raise_on_redirect=False``.
+
+ :param int connect:
+ How many connection-related errors to retry on.
+
+ These are errors raised before the request is sent to the remote server,
+ which we assume has not triggered the server to process the request.
+
+ Set to ``0`` to fail on the first retry of this type.
+
+ :param int read:
+ How many times to retry on read errors.
+
+ These errors are raised after the request was sent to the server, so the
+ request may have side-effects.
+
+ Set to ``0`` to fail on the first retry of this type.
+
+ :param int redirect:
+ How many redirects to perform. Limit this to avoid infinite redirect
+ loops.
+
+ A redirect is a HTTP response with a status code 301, 302, 303, 307 or
+ 308.
+
+ Set to ``0`` to fail on the first retry of this type.
+
+ Set to ``False`` to disable and imply ``raise_on_redirect=False``.
+
+ :param int status:
+ How many times to retry on bad status codes.
+
+ These are retries made on responses, where status code matches
+ ``status_forcelist``.
+
+ Set to ``0`` to fail on the first retry of this type.
+
+ :param int other:
+ How many times to retry on other errors.
+
+ Other errors are errors that are not connect, read, redirect or status errors.
+ These errors might be raised after the request was sent to the server, so the
+ request might have side-effects.
+
+ Set to ``0`` to fail on the first retry of this type.
+
+ If ``total`` is not set, it's a good idea to set this to 0 to account
+ for unexpected edge cases and avoid infinite retry loops.
+
+ :param Collection allowed_methods:
+ Set of uppercased HTTP method verbs that we should retry on.
+
+ By default, we only retry on methods which are considered to be
+ idempotent (multiple requests with the same parameters end with the
+ same state). See :attr:`Retry.DEFAULT_ALLOWED_METHODS`.
+
+ Set to a ``None`` value to retry on any verb.
+
+ :param Collection status_forcelist:
+ A set of integer HTTP status codes that we should force a retry on.
+ A retry is initiated if the request method is in ``allowed_methods``
+ and the response status code is in ``status_forcelist``.
+
+ By default, this is disabled with ``None``.
+
+ :param float backoff_factor:
+ A backoff factor to apply between attempts after the second try
+ (most errors are resolved immediately by a second try without a
+ delay). urllib3 will sleep for::
+
+ {backoff factor} * (2 ** ({number of previous retries}))
+
+ seconds. If `backoff_jitter` is non-zero, this sleep is extended by::
+
+ random.uniform(0, {backoff jitter})
+
+ seconds. For example, if the backoff_factor is 0.1, then :func:`Retry.sleep` will
+ sleep for [0.0s, 0.2s, 0.4s, 0.8s, ...] between retries. No backoff will ever
+ be longer than `backoff_max`.
+
+ By default, backoff is disabled (factor set to 0).
+
+ :param bool raise_on_redirect: Whether, if the number of redirects is
+ exhausted, to raise a MaxRetryError, or to return a response with a
+ response code in the 3xx range.
+
+ :param bool raise_on_status: Similar meaning to ``raise_on_redirect``:
+ whether we should raise an exception, or return a response,
+ if status falls in ``status_forcelist`` range and retries have
+ been exhausted.
+
+ :param tuple history: The history of the request encountered during
+ each call to :meth:`~Retry.increment`. The list is in the order
+ the requests occurred. Each list item is of class :class:`RequestHistory`.
+
+ :param bool respect_retry_after_header:
+ Whether to respect Retry-After header on status codes defined as
+ :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not.
+
+ :param Collection remove_headers_on_redirect:
+ Sequence of headers to remove from the request when a response
+ indicating a redirect is returned before firing off the redirected
+ request.
+
+ :param int retry_after_max: Number of seconds to allow as the maximum for
+ Retry-After headers. Defaults to :attr:`Retry.DEFAULT_RETRY_AFTER_MAX`.
+ Any Retry-After headers larger than this value will be limited to this
+ value.
+ """
+
+ #: Default methods to be used for ``allowed_methods``
+ DEFAULT_ALLOWED_METHODS = frozenset(
+ ["HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE"]
+ )
+
+ #: Default status codes to be used for ``status_forcelist``
+ RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])
+
+ #: Default headers to be used for ``remove_headers_on_redirect``
+ DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset(
+ ["Cookie", "Authorization", "Proxy-Authorization"]
+ )
+
+ #: Default maximum backoff time.
+ DEFAULT_BACKOFF_MAX = 120
+
+ # This is undocumented in the RFC. Setting to 6 hours matches other popular libraries.
+ #: Default maximum allowed value for Retry-After headers in seconds
+ DEFAULT_RETRY_AFTER_MAX: typing.Final[int] = 21600
+
+ # Backward compatibility; assigned outside of the class.
+ DEFAULT: typing.ClassVar[Retry]
+
+ def __init__(
+ self,
+ total: bool | int | None = 10,
+ connect: int | None = None,
+ read: int | None = None,
+ redirect: bool | int | None = None,
+ status: int | None = None,
+ other: int | None = None,
+ allowed_methods: typing.Collection[str] | None = DEFAULT_ALLOWED_METHODS,
+ status_forcelist: typing.Collection[int] | None = None,
+ backoff_factor: float = 0,
+ backoff_max: float = DEFAULT_BACKOFF_MAX,
+ raise_on_redirect: bool = True,
+ raise_on_status: bool = True,
+ history: tuple[RequestHistory, ...] | None = None,
+ respect_retry_after_header: bool = True,
+ remove_headers_on_redirect: typing.Collection[
+ str
+ ] = DEFAULT_REMOVE_HEADERS_ON_REDIRECT,
+ backoff_jitter: float = 0.0,
+ retry_after_max: int = DEFAULT_RETRY_AFTER_MAX,
+ ) -> None:
+ self.total = total
+ self.connect = connect
+ self.read = read
+ self.status = status
+ self.other = other
+
+ if redirect is False or total is False:
+ redirect = 0
+ raise_on_redirect = False
+
+ self.redirect = redirect
+ self.status_forcelist = status_forcelist or set()
+ self.allowed_methods = allowed_methods
+ self.backoff_factor = backoff_factor
+ self.backoff_max = backoff_max
+ self.retry_after_max = retry_after_max
+ self.raise_on_redirect = raise_on_redirect
+ self.raise_on_status = raise_on_status
+ self.history = history or ()
+ self.respect_retry_after_header = respect_retry_after_header
+ self.remove_headers_on_redirect = frozenset(
+ h.lower() for h in remove_headers_on_redirect
+ )
+ self.backoff_jitter = backoff_jitter
+
+ def new(self, **kw: typing.Any) -> Self:
+ params = dict(
+ total=self.total,
+ connect=self.connect,
+ read=self.read,
+ redirect=self.redirect,
+ status=self.status,
+ other=self.other,
+ allowed_methods=self.allowed_methods,
+ status_forcelist=self.status_forcelist,
+ backoff_factor=self.backoff_factor,
+ backoff_max=self.backoff_max,
+ retry_after_max=self.retry_after_max,
+ raise_on_redirect=self.raise_on_redirect,
+ raise_on_status=self.raise_on_status,
+ history=self.history,
+ remove_headers_on_redirect=self.remove_headers_on_redirect,
+ respect_retry_after_header=self.respect_retry_after_header,
+ backoff_jitter=self.backoff_jitter,
+ )
+
+ params.update(kw)
+ return type(self)(**params) # type: ignore[arg-type]
+
+ @classmethod
+ def from_int(
+ cls,
+ retries: Retry | bool | int | None,
+ redirect: bool | int | None = True,
+ default: Retry | bool | int | None = None,
+ ) -> Retry:
+ """Backwards-compatibility for the old retries format."""
+ if retries is None:
+ retries = default if default is not None else cls.DEFAULT
+
+ if isinstance(retries, Retry):
+ return retries
+
+ redirect = bool(redirect) and None
+ new_retries = cls(retries, redirect=redirect)
+ log.debug("Converted retries value: %r -> %r", retries, new_retries)
+ return new_retries
+
+ def get_backoff_time(self) -> float:
+ """Formula for computing the current backoff
+
+ :rtype: float
+ """
+ # We want to consider only the last consecutive errors sequence (Ignore redirects).
+ consecutive_errors_len = len(
+ list(
+ takewhile(lambda x: x.redirect_location is None, reversed(self.history))
+ )
+ )
+ if consecutive_errors_len <= 1:
+ return 0
+
+ backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1))
+ if self.backoff_jitter != 0.0:
+ backoff_value += random.random() * self.backoff_jitter
+ return float(max(0, min(self.backoff_max, backoff_value)))
+
+ def parse_retry_after(self, retry_after: str) -> float:
+ seconds: float
+ # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4
+ if re.match(r"^\s*[0-9]+\s*$", retry_after):
+ seconds = int(retry_after)
+ else:
+ retry_date_tuple = email.utils.parsedate_tz(retry_after)
+ if retry_date_tuple is None:
+ raise InvalidHeader(f"Invalid Retry-After header: {retry_after}")
+
+ retry_date = email.utils.mktime_tz(retry_date_tuple)
+ seconds = retry_date - time.time()
+
+ seconds = max(seconds, 0)
+
+ # Check the seconds do not exceed the specified maximum
+ if seconds > self.retry_after_max:
+ seconds = self.retry_after_max
+
+ return seconds
+
+ def get_retry_after(self, response: BaseHTTPResponse) -> float | None:
+ """Get the value of Retry-After in seconds."""
+
+ retry_after = response.headers.get("Retry-After")
+
+ if retry_after is None:
+ return None
+
+ return self.parse_retry_after(retry_after)
+
+ def sleep_for_retry(self, response: BaseHTTPResponse) -> bool:
+ retry_after = self.get_retry_after(response)
+ if retry_after:
+ time.sleep(retry_after)
+ return True
+
+ return False
+
+ def _sleep_backoff(self) -> None:
+ backoff = self.get_backoff_time()
+ if backoff <= 0:
+ return
+ time.sleep(backoff)
+
+ def sleep(self, response: BaseHTTPResponse | None = None) -> None:
+ """Sleep between retry attempts.
+
+ This method will respect a server's ``Retry-After`` response header
+ and sleep the duration of the time requested. If that is not present, it
+ will use an exponential backoff. By default, the backoff factor is 0 and
+ this method will return immediately.
+ """
+
+ if self.respect_retry_after_header and response:
+ slept = self.sleep_for_retry(response)
+ if slept:
+ return
+
+ self._sleep_backoff()
+
+ def _is_connection_error(self, err: Exception) -> bool:
+ """Errors when we're fairly sure that the server did not receive the
+ request, so it should be safe to retry.
+ """
+ if isinstance(err, ProxyError):
+ err = err.original_error
+ return isinstance(err, ConnectTimeoutError)
+
+ def _is_read_error(self, err: Exception) -> bool:
+ """Errors that occur after the request has been started, so we should
+ assume that the server began processing it.
+ """
+ return isinstance(err, (ReadTimeoutError, ProtocolError))
+
+ def _is_method_retryable(self, method: str) -> bool:
+ """Checks if a given HTTP method should be retried upon, depending if
+ it is included in the allowed_methods
+ """
+ if self.allowed_methods and method.upper() not in self.allowed_methods:
+ return False
+ return True
+
+ def is_retry(
+ self, method: str, status_code: int, has_retry_after: bool = False
+ ) -> bool:
+ """Is this method/status code retryable? (Based on allowlists and control
+ variables such as the number of total retries to allow, whether to
+ respect the Retry-After header, whether this header is present, and
+ whether the returned status code is on the list of status codes to
+ be retried upon on the presence of the aforementioned header)
+ """
+ if not self._is_method_retryable(method):
+ return False
+
+ if self.status_forcelist and status_code in self.status_forcelist:
+ return True
+
+ return bool(
+ self.total
+ and self.respect_retry_after_header
+ and has_retry_after
+ and (status_code in self.RETRY_AFTER_STATUS_CODES)
+ )
+
+ def is_exhausted(self) -> bool:
+ """Are we out of retries?"""
+ retry_counts = [
+ x
+ for x in (
+ self.total,
+ self.connect,
+ self.read,
+ self.redirect,
+ self.status,
+ self.other,
+ )
+ if x
+ ]
+ if not retry_counts:
+ return False
+
+ return min(retry_counts) < 0
+
+ def increment(
+ self,
+ method: str | None = None,
+ url: str | None = None,
+ response: BaseHTTPResponse | None = None,
+ error: Exception | None = None,
+ _pool: ConnectionPool | None = None,
+ _stacktrace: TracebackType | None = None,
+ ) -> Self:
+ """Return a new Retry object with incremented retry counters.
+
+ :param response: A response object, or None, if the server did not
+ return a response.
+ :type response: :class:`~urllib3.response.BaseHTTPResponse`
+ :param Exception error: An error encountered during the request, or
+ None if the response was received successfully.
+
+ :return: A new ``Retry`` object.
+ """
+ if self.total is False and error:
+ # Disabled, indicate to re-raise the error.
+ raise reraise(type(error), error, _stacktrace)
+
+ total = self.total
+ if total is not None:
+ total -= 1
+
+ connect = self.connect
+ read = self.read
+ redirect = self.redirect
+ status_count = self.status
+ other = self.other
+ cause = "unknown"
+ status = None
+ redirect_location = None
+
+ if error and self._is_connection_error(error):
+ # Connect retry?
+ if connect is False:
+ raise reraise(type(error), error, _stacktrace)
+ elif connect is not None:
+ connect -= 1
+
+ elif error and self._is_read_error(error):
+ # Read retry?
+ if read is False or method is None or not self._is_method_retryable(method):
+ raise reraise(type(error), error, _stacktrace)
+ elif read is not None:
+ read -= 1
+
+ elif error:
+ # Other retry?
+ if other is not None:
+ other -= 1
+
+ elif response and response.get_redirect_location():
+ # Redirect retry?
+ if redirect is not None:
+ redirect -= 1
+ cause = "too many redirects"
+ response_redirect_location = response.get_redirect_location()
+ if response_redirect_location:
+ redirect_location = response_redirect_location
+ status = response.status
+
+ else:
+ # Incrementing because of a server error like a 500 in
+ # status_forcelist and the given method is in the allowed_methods
+ cause = ResponseError.GENERIC_ERROR
+ if response and response.status:
+ if status_count is not None:
+ status_count -= 1
+ cause = ResponseError.SPECIFIC_ERROR.format(status_code=response.status)
+ status = response.status
+
+ history = self.history + (
+ RequestHistory(method, url, error, status, redirect_location),
+ )
+
+ new_retry = self.new(
+ total=total,
+ connect=connect,
+ read=read,
+ redirect=redirect,
+ status=status_count,
+ other=other,
+ history=history,
+ )
+
+ if new_retry.is_exhausted():
+ reason = error or ResponseError(cause)
+ raise MaxRetryError(_pool, url, reason) from reason # type: ignore[arg-type]
+
+ log.debug("Incremented Retry for (url='%s'): %r", url, new_retry)
+
+ return new_retry
+
+ def __repr__(self) -> str:
+ return (
+ f"{type(self).__name__}(total={self.total}, connect={self.connect}, "
+ f"read={self.read}, redirect={self.redirect}, status={self.status})"
+ )
+
+
+# For backwards compatibility (equivalent to pre-v1.9):
+Retry.DEFAULT = Retry(3)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/ssl_.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/ssl_.py
new file mode 100644
index 0000000000000000000000000000000000000000..56fe9093adaa86b30085aef2435e49f84841df12
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/ssl_.py
@@ -0,0 +1,527 @@
+from __future__ import annotations
+
+import hashlib
+import hmac
+import os
+import socket
+import sys
+import typing
+import warnings
+from binascii import unhexlify
+
+from ..exceptions import ProxySchemeUnsupported, SSLError
+from .url import _BRACELESS_IPV6_ADDRZ_RE, _IPV4_RE
+
+SSLContext = None
+SSLTransport = None
+HAS_NEVER_CHECK_COMMON_NAME = False
+IS_PYOPENSSL = False
+ALPN_PROTOCOLS = ["http/1.1"]
+
+_TYPE_VERSION_INFO = tuple[int, int, int, str, int]
+
+# Maps the length of a digest to a possible hash function producing this digest
+HASHFUNC_MAP = {
+ length: getattr(hashlib, algorithm, None)
+ for length, algorithm in ((32, "md5"), (40, "sha1"), (64, "sha256"))
+}
+
+
+def _is_bpo_43522_fixed(
+ implementation_name: str,
+ version_info: _TYPE_VERSION_INFO,
+ pypy_version_info: _TYPE_VERSION_INFO | None,
+) -> bool:
+ """Return True for CPython 3.9.3+ or 3.10+ and PyPy 7.3.8+ where
+ setting SSLContext.hostname_checks_common_name to False works.
+
+ Outside of CPython and PyPy we don't know which implementations work
+ or not so we conservatively use our hostname matching as we know that works
+ on all implementations.
+
+ https://github.com/urllib3/urllib3/issues/2192#issuecomment-821832963
+ https://foss.heptapod.net/pypy/pypy/-/issues/3539
+ """
+ if implementation_name == "pypy":
+ # https://foss.heptapod.net/pypy/pypy/-/issues/3129
+ return pypy_version_info >= (7, 3, 8) # type: ignore[operator]
+ elif implementation_name == "cpython":
+ major_minor = version_info[:2]
+ micro = version_info[2]
+ return (major_minor == (3, 9) and micro >= 3) or major_minor >= (3, 10)
+ else: # Defensive:
+ return False
+
+
+def _is_has_never_check_common_name_reliable(
+ openssl_version: str,
+ openssl_version_number: int,
+ implementation_name: str,
+ version_info: _TYPE_VERSION_INFO,
+ pypy_version_info: _TYPE_VERSION_INFO | None,
+) -> bool:
+ # As of May 2023, all released versions of LibreSSL fail to reject certificates with
+ # only common names, see https://github.com/urllib3/urllib3/pull/3024
+ is_openssl = openssl_version.startswith("OpenSSL ")
+ # Before fixing OpenSSL issue #14579, the SSL_new() API was not copying hostflags
+ # like X509_CHECK_FLAG_NEVER_CHECK_SUBJECT, which tripped up CPython.
+ # https://github.com/openssl/openssl/issues/14579
+ # This was released in OpenSSL 1.1.1l+ (>=0x101010cf)
+ is_openssl_issue_14579_fixed = openssl_version_number >= 0x101010CF
+
+ return is_openssl and (
+ is_openssl_issue_14579_fixed
+ or _is_bpo_43522_fixed(implementation_name, version_info, pypy_version_info)
+ )
+
+
+if typing.TYPE_CHECKING:
+ from ssl import VerifyMode
+ from typing import TypedDict
+
+ from .ssltransport import SSLTransport as SSLTransportType
+
+ class _TYPE_PEER_CERT_RET_DICT(TypedDict, total=False):
+ subjectAltName: tuple[tuple[str, str], ...]
+ subject: tuple[tuple[tuple[str, str], ...], ...]
+ serialNumber: str
+
+
+# Mapping from 'ssl.PROTOCOL_TLSX' to 'TLSVersion.X'
+_SSL_VERSION_TO_TLS_VERSION: dict[int, int] = {}
+
+try: # Do we have ssl at all?
+ import ssl
+ from ssl import ( # type: ignore[assignment]
+ CERT_REQUIRED,
+ HAS_NEVER_CHECK_COMMON_NAME,
+ OP_NO_COMPRESSION,
+ OP_NO_TICKET,
+ OPENSSL_VERSION,
+ OPENSSL_VERSION_NUMBER,
+ PROTOCOL_TLS,
+ PROTOCOL_TLS_CLIENT,
+ VERIFY_X509_STRICT,
+ OP_NO_SSLv2,
+ OP_NO_SSLv3,
+ SSLContext,
+ TLSVersion,
+ )
+
+ PROTOCOL_SSLv23 = PROTOCOL_TLS
+
+ # Needed for Python 3.9 which does not define this
+ VERIFY_X509_PARTIAL_CHAIN = getattr(ssl, "VERIFY_X509_PARTIAL_CHAIN", 0x80000)
+
+ # Setting SSLContext.hostname_checks_common_name = False didn't work before CPython
+ # 3.9.3, and 3.10 (but OK on PyPy) or OpenSSL 1.1.1l+
+ if HAS_NEVER_CHECK_COMMON_NAME and not _is_has_never_check_common_name_reliable(
+ OPENSSL_VERSION,
+ OPENSSL_VERSION_NUMBER,
+ sys.implementation.name,
+ sys.version_info,
+ sys.pypy_version_info if sys.implementation.name == "pypy" else None, # type: ignore[attr-defined]
+ ): # Defensive: for Python < 3.9.3
+ HAS_NEVER_CHECK_COMMON_NAME = False
+
+ # Need to be careful here in case old TLS versions get
+ # removed in future 'ssl' module implementations.
+ for attr in ("TLSv1", "TLSv1_1", "TLSv1_2"):
+ try:
+ _SSL_VERSION_TO_TLS_VERSION[getattr(ssl, f"PROTOCOL_{attr}")] = getattr(
+ TLSVersion, attr
+ )
+ except AttributeError: # Defensive:
+ continue
+
+ from .ssltransport import SSLTransport # type: ignore[assignment]
+except ImportError:
+ OP_NO_COMPRESSION = 0x20000 # type: ignore[assignment, misc]
+ OP_NO_TICKET = 0x4000 # type: ignore[assignment, misc]
+ OP_NO_SSLv2 = 0x1000000 # type: ignore[assignment, misc]
+ OP_NO_SSLv3 = 0x2000000 # type: ignore[assignment, misc]
+ PROTOCOL_SSLv23 = PROTOCOL_TLS = 2 # type: ignore[assignment, misc]
+ PROTOCOL_TLS_CLIENT = 16 # type: ignore[assignment, misc]
+ VERIFY_X509_PARTIAL_CHAIN = 0x80000
+ VERIFY_X509_STRICT = 0x20 # type: ignore[assignment, misc]
+
+
+_TYPE_PEER_CERT_RET = typing.Union["_TYPE_PEER_CERT_RET_DICT", bytes, None]
+
+
+def assert_fingerprint(cert: bytes | None, fingerprint: str) -> None:
+ """
+ Checks if given fingerprint matches the supplied certificate.
+
+ :param cert:
+ Certificate as bytes object.
+ :param fingerprint:
+ Fingerprint as string of hexdigits, can be interspersed by colons.
+ """
+
+ if cert is None:
+ raise SSLError("No certificate for the peer.")
+
+ fingerprint = fingerprint.replace(":", "").lower()
+ digest_length = len(fingerprint)
+ if digest_length not in HASHFUNC_MAP:
+ raise SSLError(f"Fingerprint of invalid length: {fingerprint}")
+ hashfunc = HASHFUNC_MAP.get(digest_length)
+ if hashfunc is None:
+ raise SSLError(
+ f"Hash function implementation unavailable for fingerprint length: {digest_length}"
+ )
+
+ # We need encode() here for py32; works on py2 and p33.
+ fingerprint_bytes = unhexlify(fingerprint.encode())
+
+ cert_digest = hashfunc(cert).digest()
+
+ if not hmac.compare_digest(cert_digest, fingerprint_bytes):
+ raise SSLError(
+ f'Fingerprints did not match. Expected "{fingerprint}", got "{cert_digest.hex()}"'
+ )
+
+
+def resolve_cert_reqs(candidate: None | int | str) -> VerifyMode:
+ """
+ Resolves the argument to a numeric constant, which can be passed to
+ the wrap_socket function/method from the ssl module.
+ Defaults to :data:`ssl.CERT_REQUIRED`.
+ If given a string it is assumed to be the name of the constant in the
+ :mod:`ssl` module or its abbreviation.
+ (So you can specify `REQUIRED` instead of `CERT_REQUIRED`.
+ If it's neither `None` nor a string we assume it is already the numeric
+ constant which can directly be passed to wrap_socket.
+ """
+ if candidate is None:
+ return CERT_REQUIRED
+
+ if isinstance(candidate, str):
+ res = getattr(ssl, candidate, None)
+ if res is None:
+ res = getattr(ssl, "CERT_" + candidate)
+ return res # type: ignore[no-any-return]
+
+ return candidate # type: ignore[return-value]
+
+
+def resolve_ssl_version(candidate: None | int | str) -> int:
+ """
+ like resolve_cert_reqs
+ """
+ if candidate is None:
+ return PROTOCOL_TLS
+
+ if isinstance(candidate, str):
+ res = getattr(ssl, candidate, None)
+ if res is None:
+ res = getattr(ssl, "PROTOCOL_" + candidate)
+ return typing.cast(int, res)
+
+ return candidate
+
+
+def create_urllib3_context(
+ ssl_version: int | None = None,
+ cert_reqs: int | None = None,
+ options: int | None = None,
+ ciphers: str | None = None,
+ ssl_minimum_version: int | None = None,
+ ssl_maximum_version: int | None = None,
+ verify_flags: int | None = None,
+) -> ssl.SSLContext:
+ """Creates and configures an :class:`ssl.SSLContext` instance for use with urllib3.
+
+ :param ssl_version:
+ The desired protocol version to use. This will default to
+ PROTOCOL_SSLv23 which will negotiate the highest protocol that both
+ the server and your installation of OpenSSL support.
+
+ This parameter is deprecated instead use 'ssl_minimum_version'.
+ :param ssl_minimum_version:
+ The minimum version of TLS to be used. Use the 'ssl.TLSVersion' enum for specifying the value.
+ :param ssl_maximum_version:
+ The maximum version of TLS to be used. Use the 'ssl.TLSVersion' enum for specifying the value.
+ Not recommended to set to anything other than 'ssl.TLSVersion.MAXIMUM_SUPPORTED' which is the
+ default value.
+ :param cert_reqs:
+ Whether to require the certificate verification. This defaults to
+ ``ssl.CERT_REQUIRED``.
+ :param options:
+ Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,
+ ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``.
+ :param ciphers:
+ Which cipher suites to allow the server to select. Defaults to either system configured
+ ciphers if OpenSSL 1.1.1+, otherwise uses a secure default set of ciphers.
+ :param verify_flags:
+ The flags for certificate verification operations. These default to
+ ``ssl.VERIFY_X509_PARTIAL_CHAIN`` and ``ssl.VERIFY_X509_STRICT`` for Python 3.13+.
+ :returns:
+ Constructed SSLContext object with specified options
+ :rtype: SSLContext
+ """
+ if SSLContext is None:
+ raise TypeError("Can't create an SSLContext object without an ssl module")
+
+ # This means 'ssl_version' was specified as an exact value.
+ if ssl_version not in (None, PROTOCOL_TLS, PROTOCOL_TLS_CLIENT):
+ # Disallow setting 'ssl_version' and 'ssl_minimum|maximum_version'
+ # to avoid conflicts.
+ if ssl_minimum_version is not None or ssl_maximum_version is not None:
+ raise ValueError(
+ "Can't specify both 'ssl_version' and either "
+ "'ssl_minimum_version' or 'ssl_maximum_version'"
+ )
+
+ # 'ssl_version' is deprecated and will be removed in the future.
+ else:
+ # Use 'ssl_minimum_version' and 'ssl_maximum_version' instead.
+ ssl_minimum_version = _SSL_VERSION_TO_TLS_VERSION.get(
+ ssl_version, TLSVersion.MINIMUM_SUPPORTED
+ )
+ ssl_maximum_version = _SSL_VERSION_TO_TLS_VERSION.get(
+ ssl_version, TLSVersion.MAXIMUM_SUPPORTED
+ )
+
+ # This warning message is pushing users to use 'ssl_minimum_version'
+ # instead of both min/max. Best practice is to only set the minimum version and
+ # keep the maximum version to be it's default value: 'TLSVersion.MAXIMUM_SUPPORTED'
+ warnings.warn(
+ "'ssl_version' option is deprecated and will be "
+ "removed in urllib3 v2.6.0. Instead use 'ssl_minimum_version'",
+ category=DeprecationWarning,
+ stacklevel=2,
+ )
+
+ # PROTOCOL_TLS is deprecated in Python 3.10 so we always use PROTOCOL_TLS_CLIENT
+ context = SSLContext(PROTOCOL_TLS_CLIENT)
+
+ if ssl_minimum_version is not None:
+ context.minimum_version = ssl_minimum_version
+ else: # Python <3.10 defaults to 'MINIMUM_SUPPORTED' so explicitly set TLSv1.2 here
+ context.minimum_version = TLSVersion.TLSv1_2
+
+ if ssl_maximum_version is not None:
+ context.maximum_version = ssl_maximum_version
+
+ # Unless we're given ciphers defer to either system ciphers in
+ # the case of OpenSSL 1.1.1+ or use our own secure default ciphers.
+ if ciphers:
+ context.set_ciphers(ciphers)
+
+ # Setting the default here, as we may have no ssl module on import
+ cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
+
+ if options is None:
+ options = 0
+ # SSLv2 is easily broken and is considered harmful and dangerous
+ options |= OP_NO_SSLv2
+ # SSLv3 has several problems and is now dangerous
+ options |= OP_NO_SSLv3
+ # Disable compression to prevent CRIME attacks for OpenSSL 1.0+
+ # (issue #309)
+ options |= OP_NO_COMPRESSION
+ # TLSv1.2 only. Unless set explicitly, do not request tickets.
+ # This may save some bandwidth on wire, and although the ticket is encrypted,
+ # there is a risk associated with it being on wire,
+ # if the server is not rotating its ticketing keys properly.
+ options |= OP_NO_TICKET
+
+ context.options |= options
+
+ if verify_flags is None:
+ verify_flags = 0
+ # In Python 3.13+ ssl.create_default_context() sets VERIFY_X509_PARTIAL_CHAIN
+ # and VERIFY_X509_STRICT so we do the same
+ if sys.version_info >= (3, 13):
+ verify_flags |= VERIFY_X509_PARTIAL_CHAIN
+ verify_flags |= VERIFY_X509_STRICT
+
+ context.verify_flags |= verify_flags
+
+ # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is
+ # necessary for conditional client cert authentication with TLS 1.3.
+ # The attribute is None for OpenSSL <= 1.1.0 or does not exist when using
+ # an SSLContext created by pyOpenSSL.
+ if getattr(context, "post_handshake_auth", None) is not None:
+ context.post_handshake_auth = True
+
+ # The order of the below lines setting verify_mode and check_hostname
+ # matter due to safe-guards SSLContext has to prevent an SSLContext with
+ # check_hostname=True, verify_mode=NONE/OPTIONAL.
+ # We always set 'check_hostname=False' for pyOpenSSL so we rely on our own
+ # 'ssl.match_hostname()' implementation.
+ if cert_reqs == ssl.CERT_REQUIRED and not IS_PYOPENSSL:
+ context.verify_mode = cert_reqs
+ context.check_hostname = True
+ else:
+ context.check_hostname = False
+ context.verify_mode = cert_reqs
+
+ try:
+ context.hostname_checks_common_name = False
+ except AttributeError: # Defensive: for CPython < 3.9.3; for PyPy < 7.3.8
+ pass
+
+ if "SSLKEYLOGFILE" in os.environ:
+ sslkeylogfile = os.path.expandvars(os.environ.get("SSLKEYLOGFILE"))
+ else:
+ sslkeylogfile = None
+ if sslkeylogfile:
+ context.keylog_filename = sslkeylogfile
+
+ return context
+
+
+@typing.overload
+def ssl_wrap_socket(
+ sock: socket.socket,
+ keyfile: str | None = ...,
+ certfile: str | None = ...,
+ cert_reqs: int | None = ...,
+ ca_certs: str | None = ...,
+ server_hostname: str | None = ...,
+ ssl_version: int | None = ...,
+ ciphers: str | None = ...,
+ ssl_context: ssl.SSLContext | None = ...,
+ ca_cert_dir: str | None = ...,
+ key_password: str | None = ...,
+ ca_cert_data: None | str | bytes = ...,
+ tls_in_tls: typing.Literal[False] = ...,
+) -> ssl.SSLSocket: ...
+
+
+@typing.overload
+def ssl_wrap_socket(
+ sock: socket.socket,
+ keyfile: str | None = ...,
+ certfile: str | None = ...,
+ cert_reqs: int | None = ...,
+ ca_certs: str | None = ...,
+ server_hostname: str | None = ...,
+ ssl_version: int | None = ...,
+ ciphers: str | None = ...,
+ ssl_context: ssl.SSLContext | None = ...,
+ ca_cert_dir: str | None = ...,
+ key_password: str | None = ...,
+ ca_cert_data: None | str | bytes = ...,
+ tls_in_tls: bool = ...,
+) -> ssl.SSLSocket | SSLTransportType: ...
+
+
+def ssl_wrap_socket(
+ sock: socket.socket,
+ keyfile: str | None = None,
+ certfile: str | None = None,
+ cert_reqs: int | None = None,
+ ca_certs: str | None = None,
+ server_hostname: str | None = None,
+ ssl_version: int | None = None,
+ ciphers: str | None = None,
+ ssl_context: ssl.SSLContext | None = None,
+ ca_cert_dir: str | None = None,
+ key_password: str | None = None,
+ ca_cert_data: None | str | bytes = None,
+ tls_in_tls: bool = False,
+) -> ssl.SSLSocket | SSLTransportType:
+ """
+ All arguments except for server_hostname, ssl_context, tls_in_tls, ca_cert_data and
+ ca_cert_dir have the same meaning as they do when using
+ :func:`ssl.create_default_context`, :meth:`ssl.SSLContext.load_cert_chain`,
+ :meth:`ssl.SSLContext.set_ciphers` and :meth:`ssl.SSLContext.wrap_socket`.
+
+ :param server_hostname:
+ When SNI is supported, the expected hostname of the certificate
+ :param ssl_context:
+ A pre-made :class:`SSLContext` object. If none is provided, one will
+ be created using :func:`create_urllib3_context`.
+ :param ciphers:
+ A string of ciphers we wish the client to support.
+ :param ca_cert_dir:
+ A directory containing CA certificates in multiple separate files, as
+ supported by OpenSSL's -CApath flag or the capath argument to
+ SSLContext.load_verify_locations().
+ :param key_password:
+ Optional password if the keyfile is encrypted.
+ :param ca_cert_data:
+ Optional string containing CA certificates in PEM format suitable for
+ passing as the cadata parameter to SSLContext.load_verify_locations()
+ :param tls_in_tls:
+ Use SSLTransport to wrap the existing socket.
+ """
+ context = ssl_context
+ if context is None:
+ # Note: This branch of code and all the variables in it are only used in tests.
+ # We should consider deprecating and removing this code.
+ context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers)
+
+ if ca_certs or ca_cert_dir or ca_cert_data:
+ try:
+ context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data)
+ except OSError as e:
+ raise SSLError(e) from e
+
+ elif ssl_context is None and hasattr(context, "load_default_certs"):
+ # try to load OS default certs; works well on Windows.
+ context.load_default_certs()
+
+ # Attempt to detect if we get the goofy behavior of the
+ # keyfile being encrypted and OpenSSL asking for the
+ # passphrase via the terminal and instead error out.
+ if keyfile and key_password is None and _is_key_file_encrypted(keyfile):
+ raise SSLError("Client private key is encrypted, password is required")
+
+ if certfile:
+ if key_password is None:
+ context.load_cert_chain(certfile, keyfile)
+ else:
+ context.load_cert_chain(certfile, keyfile, key_password)
+
+ context.set_alpn_protocols(ALPN_PROTOCOLS)
+
+ ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls, server_hostname)
+ return ssl_sock
+
+
+def is_ipaddress(hostname: str | bytes) -> bool:
+ """Detects whether the hostname given is an IPv4 or IPv6 address.
+ Also detects IPv6 addresses with Zone IDs.
+
+ :param str hostname: Hostname to examine.
+ :return: True if the hostname is an IP address, False otherwise.
+ """
+ if isinstance(hostname, bytes):
+ # IDN A-label bytes are ASCII compatible.
+ hostname = hostname.decode("ascii")
+ return bool(_IPV4_RE.match(hostname) or _BRACELESS_IPV6_ADDRZ_RE.match(hostname))
+
+
+def _is_key_file_encrypted(key_file: str) -> bool:
+ """Detects if a key file is encrypted or not."""
+ with open(key_file) as f:
+ for line in f:
+ # Look for Proc-Type: 4,ENCRYPTED
+ if "ENCRYPTED" in line:
+ return True
+
+ return False
+
+
+def _ssl_wrap_socket_impl(
+ sock: socket.socket,
+ ssl_context: ssl.SSLContext,
+ tls_in_tls: bool,
+ server_hostname: str | None = None,
+) -> ssl.SSLSocket | SSLTransportType:
+ if tls_in_tls:
+ if not SSLTransport:
+ # Import error, ssl is not available.
+ raise ProxySchemeUnsupported(
+ "TLS in TLS requires support for the 'ssl' module"
+ )
+
+ SSLTransport._validate_ssl_context_for_tls_in_tls(ssl_context)
+ return SSLTransport(sock, ssl_context, server_hostname)
+
+ return ssl_context.wrap_socket(sock, server_hostname=server_hostname)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/ssl_match_hostname.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/ssl_match_hostname.py
new file mode 100644
index 0000000000000000000000000000000000000000..25d91000419ea4a860f511ebe669fe171b79254c
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/ssl_match_hostname.py
@@ -0,0 +1,159 @@
+"""The match_hostname() function from Python 3.5, essential when using SSL."""
+
+# Note: This file is under the PSF license as the code comes from the python
+# stdlib. http://docs.python.org/3/license.html
+# It is modified to remove commonName support.
+
+from __future__ import annotations
+
+import ipaddress
+import re
+import typing
+from ipaddress import IPv4Address, IPv6Address
+
+if typing.TYPE_CHECKING:
+ from .ssl_ import _TYPE_PEER_CERT_RET_DICT
+
+__version__ = "3.5.0.1"
+
+
+class CertificateError(ValueError):
+ pass
+
+
+def _dnsname_match(
+ dn: typing.Any, hostname: str, max_wildcards: int = 1
+) -> typing.Match[str] | None | bool:
+ """Matching according to RFC 6125, section 6.4.3
+
+ http://tools.ietf.org/html/rfc6125#section-6.4.3
+ """
+ pats = []
+ if not dn:
+ return False
+
+ # Ported from python3-syntax:
+ # leftmost, *remainder = dn.split(r'.')
+ parts = dn.split(r".")
+ leftmost = parts[0]
+ remainder = parts[1:]
+
+ wildcards = leftmost.count("*")
+ if wildcards > max_wildcards:
+ # Issue #17980: avoid denials of service by refusing more
+ # than one wildcard per fragment. A survey of established
+ # policy among SSL implementations showed it to be a
+ # reasonable choice.
+ raise CertificateError(
+ "too many wildcards in certificate DNS name: " + repr(dn)
+ )
+
+ # speed up common case w/o wildcards
+ if not wildcards:
+ return bool(dn.lower() == hostname.lower())
+
+ # RFC 6125, section 6.4.3, subitem 1.
+ # The client SHOULD NOT attempt to match a presented identifier in which
+ # the wildcard character comprises a label other than the left-most label.
+ if leftmost == "*":
+ # When '*' is a fragment by itself, it matches a non-empty dotless
+ # fragment.
+ pats.append("[^.]+")
+ elif leftmost.startswith("xn--") or hostname.startswith("xn--"):
+ # RFC 6125, section 6.4.3, subitem 3.
+ # The client SHOULD NOT attempt to match a presented identifier
+ # where the wildcard character is embedded within an A-label or
+ # U-label of an internationalized domain name.
+ pats.append(re.escape(leftmost))
+ else:
+ # Otherwise, '*' matches any dotless string, e.g. www*
+ pats.append(re.escape(leftmost).replace(r"\*", "[^.]*"))
+
+ # add the remaining fragments, ignore any wildcards
+ for frag in remainder:
+ pats.append(re.escape(frag))
+
+ pat = re.compile(r"\A" + r"\.".join(pats) + r"\Z", re.IGNORECASE)
+ return pat.match(hostname)
+
+
+def _ipaddress_match(ipname: str, host_ip: IPv4Address | IPv6Address) -> bool:
+ """Exact matching of IP addresses.
+
+ RFC 9110 section 4.3.5: "A reference identity of IP-ID contains the decoded
+ bytes of the IP address. An IP version 4 address is 4 octets, and an IP
+ version 6 address is 16 octets. [...] A reference identity of type IP-ID
+ matches if the address is identical to an iPAddress value of the
+ subjectAltName extension of the certificate."
+ """
+ # OpenSSL may add a trailing newline to a subjectAltName's IP address
+ # Divergence from upstream: ipaddress can't handle byte str
+ ip = ipaddress.ip_address(ipname.rstrip())
+ return bool(ip.packed == host_ip.packed)
+
+
+def match_hostname(
+ cert: _TYPE_PEER_CERT_RET_DICT | None,
+ hostname: str,
+ hostname_checks_common_name: bool = False,
+) -> None:
+ """Verify that *cert* (in decoded format as returned by
+ SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
+ rules are followed, but IP addresses are not accepted for *hostname*.
+
+ CertificateError is raised on failure. On success, the function
+ returns nothing.
+ """
+ if not cert:
+ raise ValueError(
+ "empty or no certificate, match_hostname needs a "
+ "SSL socket or SSL context with either "
+ "CERT_OPTIONAL or CERT_REQUIRED"
+ )
+ try:
+ # Divergence from upstream: ipaddress can't handle byte str
+ #
+ # The ipaddress module shipped with Python < 3.9 does not support
+ # scoped IPv6 addresses so we unconditionally strip the Zone IDs for
+ # now. Once we drop support for Python 3.9 we can remove this branch.
+ if "%" in hostname:
+ host_ip = ipaddress.ip_address(hostname[: hostname.rfind("%")])
+ else:
+ host_ip = ipaddress.ip_address(hostname)
+
+ except ValueError:
+ # Not an IP address (common case)
+ host_ip = None
+ dnsnames = []
+ san: tuple[tuple[str, str], ...] = cert.get("subjectAltName", ())
+ key: str
+ value: str
+ for key, value in san:
+ if key == "DNS":
+ if host_ip is None and _dnsname_match(value, hostname):
+ return
+ dnsnames.append(value)
+ elif key == "IP Address":
+ if host_ip is not None and _ipaddress_match(value, host_ip):
+ return
+ dnsnames.append(value)
+
+ # We only check 'commonName' if it's enabled and we're not verifying
+ # an IP address. IP addresses aren't valid within 'commonName'.
+ if hostname_checks_common_name and host_ip is None and not dnsnames:
+ for sub in cert.get("subject", ()):
+ for key, value in sub:
+ if key == "commonName":
+ if _dnsname_match(value, hostname):
+ return
+ dnsnames.append(value) # Defensive: for Python < 3.9.3
+
+ if len(dnsnames) > 1:
+ raise CertificateError(
+ "hostname %r "
+ "doesn't match either of %s" % (hostname, ", ".join(map(repr, dnsnames)))
+ )
+ elif len(dnsnames) == 1:
+ raise CertificateError(f"hostname {hostname!r} doesn't match {dnsnames[0]!r}")
+ else:
+ raise CertificateError("no appropriate subjectAltName fields were found")
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/ssltransport.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/ssltransport.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d59bc3bce2489c3a0aa5bcb83b737dcf33c033b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/ssltransport.py
@@ -0,0 +1,271 @@
+from __future__ import annotations
+
+import io
+import socket
+import ssl
+import typing
+
+from ..exceptions import ProxySchemeUnsupported
+
+if typing.TYPE_CHECKING:
+ from typing_extensions import Self
+
+ from .ssl_ import _TYPE_PEER_CERT_RET, _TYPE_PEER_CERT_RET_DICT
+
+
+_WriteBuffer = typing.Union[bytearray, memoryview]
+_ReturnValue = typing.TypeVar("_ReturnValue")
+
+SSL_BLOCKSIZE = 16384
+
+
+class SSLTransport:
+ """
+ The SSLTransport wraps an existing socket and establishes an SSL connection.
+
+ Contrary to Python's implementation of SSLSocket, it allows you to chain
+ multiple TLS connections together. It's particularly useful if you need to
+ implement TLS within TLS.
+
+ The class supports most of the socket API operations.
+ """
+
+ @staticmethod
+ def _validate_ssl_context_for_tls_in_tls(ssl_context: ssl.SSLContext) -> None:
+ """
+ Raises a ProxySchemeUnsupported if the provided ssl_context can't be used
+ for TLS in TLS.
+
+ The only requirement is that the ssl_context provides the 'wrap_bio'
+ methods.
+ """
+
+ if not hasattr(ssl_context, "wrap_bio"):
+ raise ProxySchemeUnsupported(
+ "TLS in TLS requires SSLContext.wrap_bio() which isn't "
+ "available on non-native SSLContext"
+ )
+
+ def __init__(
+ self,
+ socket: socket.socket,
+ ssl_context: ssl.SSLContext,
+ server_hostname: str | None = None,
+ suppress_ragged_eofs: bool = True,
+ ) -> None:
+ """
+ Create an SSLTransport around socket using the provided ssl_context.
+ """
+ self.incoming = ssl.MemoryBIO()
+ self.outgoing = ssl.MemoryBIO()
+
+ self.suppress_ragged_eofs = suppress_ragged_eofs
+ self.socket = socket
+
+ self.sslobj = ssl_context.wrap_bio(
+ self.incoming, self.outgoing, server_hostname=server_hostname
+ )
+
+ # Perform initial handshake.
+ self._ssl_io_loop(self.sslobj.do_handshake)
+
+ def __enter__(self) -> Self:
+ return self
+
+ def __exit__(self, *_: typing.Any) -> None:
+ self.close()
+
+ def fileno(self) -> int:
+ return self.socket.fileno()
+
+ def read(self, len: int = 1024, buffer: typing.Any | None = None) -> int | bytes:
+ return self._wrap_ssl_read(len, buffer)
+
+ def recv(self, buflen: int = 1024, flags: int = 0) -> int | bytes:
+ if flags != 0:
+ raise ValueError("non-zero flags not allowed in calls to recv")
+ return self._wrap_ssl_read(buflen)
+
+ def recv_into(
+ self,
+ buffer: _WriteBuffer,
+ nbytes: int | None = None,
+ flags: int = 0,
+ ) -> None | int | bytes:
+ if flags != 0:
+ raise ValueError("non-zero flags not allowed in calls to recv_into")
+ if nbytes is None:
+ nbytes = len(buffer)
+ return self.read(nbytes, buffer)
+
+ def sendall(self, data: bytes, flags: int = 0) -> None:
+ if flags != 0:
+ raise ValueError("non-zero flags not allowed in calls to sendall")
+ count = 0
+ with memoryview(data) as view, view.cast("B") as byte_view:
+ amount = len(byte_view)
+ while count < amount:
+ v = self.send(byte_view[count:])
+ count += v
+
+ def send(self, data: bytes, flags: int = 0) -> int:
+ if flags != 0:
+ raise ValueError("non-zero flags not allowed in calls to send")
+ return self._ssl_io_loop(self.sslobj.write, data)
+
+ def makefile(
+ self,
+ mode: str,
+ buffering: int | None = None,
+ *,
+ encoding: str | None = None,
+ errors: str | None = None,
+ newline: str | None = None,
+ ) -> typing.BinaryIO | typing.TextIO | socket.SocketIO:
+ """
+ Python's httpclient uses makefile and buffered io when reading HTTP
+ messages and we need to support it.
+
+ This is unfortunately a copy and paste of socket.py makefile with small
+ changes to point to the socket directly.
+ """
+ if not set(mode) <= {"r", "w", "b"}:
+ raise ValueError(f"invalid mode {mode!r} (only r, w, b allowed)")
+
+ writing = "w" in mode
+ reading = "r" in mode or not writing
+ assert reading or writing
+ binary = "b" in mode
+ rawmode = ""
+ if reading:
+ rawmode += "r"
+ if writing:
+ rawmode += "w"
+ raw = socket.SocketIO(self, rawmode) # type: ignore[arg-type]
+ self.socket._io_refs += 1 # type: ignore[attr-defined]
+ if buffering is None:
+ buffering = -1
+ if buffering < 0:
+ buffering = io.DEFAULT_BUFFER_SIZE
+ if buffering == 0:
+ if not binary:
+ raise ValueError("unbuffered streams must be binary")
+ return raw
+ buffer: typing.BinaryIO
+ if reading and writing:
+ buffer = io.BufferedRWPair(raw, raw, buffering) # type: ignore[assignment]
+ elif reading:
+ buffer = io.BufferedReader(raw, buffering)
+ else:
+ assert writing
+ buffer = io.BufferedWriter(raw, buffering)
+ if binary:
+ return buffer
+ text = io.TextIOWrapper(buffer, encoding, errors, newline)
+ text.mode = mode # type: ignore[misc]
+ return text
+
+ def unwrap(self) -> None:
+ self._ssl_io_loop(self.sslobj.unwrap)
+
+ def close(self) -> None:
+ self.socket.close()
+
+ @typing.overload
+ def getpeercert(
+ self, binary_form: typing.Literal[False] = ...
+ ) -> _TYPE_PEER_CERT_RET_DICT | None: ...
+
+ @typing.overload
+ def getpeercert(self, binary_form: typing.Literal[True]) -> bytes | None: ...
+
+ def getpeercert(self, binary_form: bool = False) -> _TYPE_PEER_CERT_RET:
+ return self.sslobj.getpeercert(binary_form) # type: ignore[return-value]
+
+ def version(self) -> str | None:
+ return self.sslobj.version()
+
+ def cipher(self) -> tuple[str, str, int] | None:
+ return self.sslobj.cipher()
+
+ def selected_alpn_protocol(self) -> str | None:
+ return self.sslobj.selected_alpn_protocol()
+
+ def shared_ciphers(self) -> list[tuple[str, str, int]] | None:
+ return self.sslobj.shared_ciphers()
+
+ def compression(self) -> str | None:
+ return self.sslobj.compression()
+
+ def settimeout(self, value: float | None) -> None:
+ self.socket.settimeout(value)
+
+ def gettimeout(self) -> float | None:
+ return self.socket.gettimeout()
+
+ def _decref_socketios(self) -> None:
+ self.socket._decref_socketios() # type: ignore[attr-defined]
+
+ def _wrap_ssl_read(self, len: int, buffer: bytearray | None = None) -> int | bytes:
+ try:
+ return self._ssl_io_loop(self.sslobj.read, len, buffer)
+ except ssl.SSLError as e:
+ if e.errno == ssl.SSL_ERROR_EOF and self.suppress_ragged_eofs:
+ return 0 # eof, return 0.
+ else:
+ raise
+
+ # func is sslobj.do_handshake or sslobj.unwrap
+ @typing.overload
+ def _ssl_io_loop(self, func: typing.Callable[[], None]) -> None: ...
+
+ # func is sslobj.write, arg1 is data
+ @typing.overload
+ def _ssl_io_loop(self, func: typing.Callable[[bytes], int], arg1: bytes) -> int: ...
+
+ # func is sslobj.read, arg1 is len, arg2 is buffer
+ @typing.overload
+ def _ssl_io_loop(
+ self,
+ func: typing.Callable[[int, bytearray | None], bytes],
+ arg1: int,
+ arg2: bytearray | None,
+ ) -> bytes: ...
+
+ def _ssl_io_loop(
+ self,
+ func: typing.Callable[..., _ReturnValue],
+ arg1: None | bytes | int = None,
+ arg2: bytearray | None = None,
+ ) -> _ReturnValue:
+ """Performs an I/O loop between incoming/outgoing and the socket."""
+ should_loop = True
+ ret = None
+
+ while should_loop:
+ errno = None
+ try:
+ if arg1 is None and arg2 is None:
+ ret = func()
+ elif arg2 is None:
+ ret = func(arg1)
+ else:
+ ret = func(arg1, arg2)
+ except ssl.SSLError as e:
+ if e.errno not in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE):
+ # WANT_READ, and WANT_WRITE are expected, others are not.
+ raise e
+ errno = e.errno
+
+ buf = self.outgoing.read()
+ self.socket.sendall(buf)
+
+ if errno is None:
+ should_loop = False
+ elif errno == ssl.SSL_ERROR_WANT_READ:
+ buf = self.socket.recv(SSL_BLOCKSIZE)
+ if buf:
+ self.incoming.write(buf)
+ else:
+ self.incoming.write_eof()
+ return typing.cast(_ReturnValue, ret)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/timeout.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/timeout.py
new file mode 100644
index 0000000000000000000000000000000000000000..4bb1be11d9cb06900dd82ecebd06aa6a7c5de916
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/timeout.py
@@ -0,0 +1,275 @@
+from __future__ import annotations
+
+import time
+import typing
+from enum import Enum
+from socket import getdefaulttimeout
+
+from ..exceptions import TimeoutStateError
+
+if typing.TYPE_CHECKING:
+ from typing import Final
+
+
+class _TYPE_DEFAULT(Enum):
+ # This value should never be passed to socket.settimeout() so for safety we use a -1.
+ # socket.settimout() raises a ValueError for negative values.
+ token = -1
+
+
+_DEFAULT_TIMEOUT: Final[_TYPE_DEFAULT] = _TYPE_DEFAULT.token
+
+_TYPE_TIMEOUT = typing.Optional[typing.Union[float, _TYPE_DEFAULT]]
+
+
+class Timeout:
+ """Timeout configuration.
+
+ Timeouts can be defined as a default for a pool:
+
+ .. code-block:: python
+
+ import urllib3
+
+ timeout = urllib3.util.Timeout(connect=2.0, read=7.0)
+
+ http = urllib3.PoolManager(timeout=timeout)
+
+ resp = http.request("GET", "https://example.com/")
+
+ print(resp.status)
+
+ Or per-request (which overrides the default for the pool):
+
+ .. code-block:: python
+
+ response = http.request("GET", "https://example.com/", timeout=Timeout(10))
+
+ Timeouts can be disabled by setting all the parameters to ``None``:
+
+ .. code-block:: python
+
+ no_timeout = Timeout(connect=None, read=None)
+ response = http.request("GET", "https://example.com/", timeout=no_timeout)
+
+
+ :param total:
+ This combines the connect and read timeouts into one; the read timeout
+ will be set to the time leftover from the connect attempt. In the
+ event that both a connect timeout and a total are specified, or a read
+ timeout and a total are specified, the shorter timeout will be applied.
+
+ Defaults to None.
+
+ :type total: int, float, or None
+
+ :param connect:
+ The maximum amount of time (in seconds) to wait for a connection
+ attempt to a server to succeed. Omitting the parameter will default the
+ connect timeout to the system default, probably `the global default
+ timeout in socket.py
+ `_.
+ None will set an infinite timeout for connection attempts.
+
+ :type connect: int, float, or None
+
+ :param read:
+ The maximum amount of time (in seconds) to wait between consecutive
+ read operations for a response from the server. Omitting the parameter
+ will default the read timeout to the system default, probably `the
+ global default timeout in socket.py
+ `_.
+ None will set an infinite timeout.
+
+ :type read: int, float, or None
+
+ .. note::
+
+ Many factors can affect the total amount of time for urllib3 to return
+ an HTTP response.
+
+ For example, Python's DNS resolver does not obey the timeout specified
+ on the socket. Other factors that can affect total request time include
+ high CPU load, high swap, the program running at a low priority level,
+ or other behaviors.
+
+ In addition, the read and total timeouts only measure the time between
+ read operations on the socket connecting the client and the server,
+ not the total amount of time for the request to return a complete
+ response. For most requests, the timeout is raised because the server
+ has not sent the first byte in the specified time. This is not always
+ the case; if a server streams one byte every fifteen seconds, a timeout
+ of 20 seconds will not trigger, even though the request will take
+ several minutes to complete.
+ """
+
+ #: A sentinel object representing the default timeout value
+ DEFAULT_TIMEOUT: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT
+
+ def __init__(
+ self,
+ total: _TYPE_TIMEOUT = None,
+ connect: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,
+ read: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,
+ ) -> None:
+ self._connect = self._validate_timeout(connect, "connect")
+ self._read = self._validate_timeout(read, "read")
+ self.total = self._validate_timeout(total, "total")
+ self._start_connect: float | None = None
+
+ def __repr__(self) -> str:
+ return f"{type(self).__name__}(connect={self._connect!r}, read={self._read!r}, total={self.total!r})"
+
+ # __str__ provided for backwards compatibility
+ __str__ = __repr__
+
+ @staticmethod
+ def resolve_default_timeout(timeout: _TYPE_TIMEOUT) -> float | None:
+ return getdefaulttimeout() if timeout is _DEFAULT_TIMEOUT else timeout
+
+ @classmethod
+ def _validate_timeout(cls, value: _TYPE_TIMEOUT, name: str) -> _TYPE_TIMEOUT:
+ """Check that a timeout attribute is valid.
+
+ :param value: The timeout value to validate
+ :param name: The name of the timeout attribute to validate. This is
+ used to specify in error messages.
+ :return: The validated and casted version of the given value.
+ :raises ValueError: If it is a numeric value less than or equal to
+ zero, or the type is not an integer, float, or None.
+ """
+ if value is None or value is _DEFAULT_TIMEOUT:
+ return value
+
+ if isinstance(value, bool):
+ raise ValueError(
+ "Timeout cannot be a boolean value. It must "
+ "be an int, float or None."
+ )
+ try:
+ float(value)
+ except (TypeError, ValueError):
+ raise ValueError(
+ "Timeout value %s was %s, but it must be an "
+ "int, float or None." % (name, value)
+ ) from None
+
+ try:
+ if value <= 0:
+ raise ValueError(
+ "Attempted to set %s timeout to %s, but the "
+ "timeout cannot be set to a value less "
+ "than or equal to 0." % (name, value)
+ )
+ except TypeError:
+ raise ValueError(
+ "Timeout value %s was %s, but it must be an "
+ "int, float or None." % (name, value)
+ ) from None
+
+ return value
+
+ @classmethod
+ def from_float(cls, timeout: _TYPE_TIMEOUT) -> Timeout:
+ """Create a new Timeout from a legacy timeout value.
+
+ The timeout value used by httplib.py sets the same timeout on the
+ connect(), and recv() socket requests. This creates a :class:`Timeout`
+ object that sets the individual timeouts to the ``timeout`` value
+ passed to this function.
+
+ :param timeout: The legacy timeout value.
+ :type timeout: integer, float, :attr:`urllib3.util.Timeout.DEFAULT_TIMEOUT`, or None
+ :return: Timeout object
+ :rtype: :class:`Timeout`
+ """
+ return Timeout(read=timeout, connect=timeout)
+
+ def clone(self) -> Timeout:
+ """Create a copy of the timeout object
+
+ Timeout properties are stored per-pool but each request needs a fresh
+ Timeout object to ensure each one has its own start/stop configured.
+
+ :return: a copy of the timeout object
+ :rtype: :class:`Timeout`
+ """
+ # We can't use copy.deepcopy because that will also create a new object
+ # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to
+ # detect the user default.
+ return Timeout(connect=self._connect, read=self._read, total=self.total)
+
+ def start_connect(self) -> float:
+ """Start the timeout clock, used during a connect() attempt
+
+ :raises urllib3.exceptions.TimeoutStateError: if you attempt
+ to start a timer that has been started already.
+ """
+ if self._start_connect is not None:
+ raise TimeoutStateError("Timeout timer has already been started.")
+ self._start_connect = time.monotonic()
+ return self._start_connect
+
+ def get_connect_duration(self) -> float:
+ """Gets the time elapsed since the call to :meth:`start_connect`.
+
+ :return: Elapsed time in seconds.
+ :rtype: float
+ :raises urllib3.exceptions.TimeoutStateError: if you attempt
+ to get duration for a timer that hasn't been started.
+ """
+ if self._start_connect is None:
+ raise TimeoutStateError(
+ "Can't get connect duration for timer that has not started."
+ )
+ return time.monotonic() - self._start_connect
+
+ @property
+ def connect_timeout(self) -> _TYPE_TIMEOUT:
+ """Get the value to use when setting a connection timeout.
+
+ This will be a positive float or integer, the value None
+ (never timeout), or the default system timeout.
+
+ :return: Connect timeout.
+ :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
+ """
+ if self.total is None:
+ return self._connect
+
+ if self._connect is None or self._connect is _DEFAULT_TIMEOUT:
+ return self.total
+
+ return min(self._connect, self.total) # type: ignore[type-var]
+
+ @property
+ def read_timeout(self) -> float | None:
+ """Get the value for the read timeout.
+
+ This assumes some time has elapsed in the connection timeout and
+ computes the read timeout appropriately.
+
+ If self.total is set, the read timeout is dependent on the amount of
+ time taken by the connect timeout. If the connection time has not been
+ established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be
+ raised.
+
+ :return: Value to use for the read timeout.
+ :rtype: int, float or None
+ :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`
+ has not yet been called on this object.
+ """
+ if (
+ self.total is not None
+ and self.total is not _DEFAULT_TIMEOUT
+ and self._read is not None
+ and self._read is not _DEFAULT_TIMEOUT
+ ):
+ # In case the connect timeout has not yet been established.
+ if self._start_connect is None:
+ return self._read
+ return max(0, min(self.total - self.get_connect_duration(), self._read))
+ elif self.total is not None and self.total is not _DEFAULT_TIMEOUT:
+ return max(0, self.total - self.get_connect_duration())
+ else:
+ return self.resolve_default_timeout(self._read)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/url.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/url.py
new file mode 100644
index 0000000000000000000000000000000000000000..db057f17be610174f30928748b5004dcbf6c501c
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/url.py
@@ -0,0 +1,469 @@
+from __future__ import annotations
+
+import re
+import typing
+
+from ..exceptions import LocationParseError
+from .util import to_str
+
+# We only want to normalize urls with an HTTP(S) scheme.
+# urllib3 infers URLs without a scheme (None) to be http.
+_NORMALIZABLE_SCHEMES = ("http", "https", None)
+
+# Almost all of these patterns were derived from the
+# 'rfc3986' module: https://github.com/python-hyper/rfc3986
+_PERCENT_RE = re.compile(r"%[a-fA-F0-9]{2}")
+_SCHEME_RE = re.compile(r"^(?:[a-zA-Z][a-zA-Z0-9+-]*:|/)")
+_URI_RE = re.compile(
+ r"^(?:([a-zA-Z][a-zA-Z0-9+.-]*):)?"
+ r"(?://([^\\/?#]*))?"
+ r"([^?#]*)"
+ r"(?:\?([^#]*))?"
+ r"(?:#(.*))?$",
+ re.UNICODE | re.DOTALL,
+)
+
+_IPV4_PAT = r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}"
+_HEX_PAT = "[0-9A-Fa-f]{1,4}"
+_LS32_PAT = "(?:{hex}:{hex}|{ipv4})".format(hex=_HEX_PAT, ipv4=_IPV4_PAT)
+_subs = {"hex": _HEX_PAT, "ls32": _LS32_PAT}
+_variations = [
+ # 6( h16 ":" ) ls32
+ "(?:%(hex)s:){6}%(ls32)s",
+ # "::" 5( h16 ":" ) ls32
+ "::(?:%(hex)s:){5}%(ls32)s",
+ # [ h16 ] "::" 4( h16 ":" ) ls32
+ "(?:%(hex)s)?::(?:%(hex)s:){4}%(ls32)s",
+ # [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32
+ "(?:(?:%(hex)s:)?%(hex)s)?::(?:%(hex)s:){3}%(ls32)s",
+ # [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32
+ "(?:(?:%(hex)s:){0,2}%(hex)s)?::(?:%(hex)s:){2}%(ls32)s",
+ # [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32
+ "(?:(?:%(hex)s:){0,3}%(hex)s)?::%(hex)s:%(ls32)s",
+ # [ *4( h16 ":" ) h16 ] "::" ls32
+ "(?:(?:%(hex)s:){0,4}%(hex)s)?::%(ls32)s",
+ # [ *5( h16 ":" ) h16 ] "::" h16
+ "(?:(?:%(hex)s:){0,5}%(hex)s)?::%(hex)s",
+ # [ *6( h16 ":" ) h16 ] "::"
+ "(?:(?:%(hex)s:){0,6}%(hex)s)?::",
+]
+
+_UNRESERVED_PAT = r"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._\-~"
+_IPV6_PAT = "(?:" + "|".join([x % _subs for x in _variations]) + ")"
+_ZONE_ID_PAT = "(?:%25|%)(?:[" + _UNRESERVED_PAT + "]|%[a-fA-F0-9]{2})+"
+_IPV6_ADDRZ_PAT = r"\[" + _IPV6_PAT + r"(?:" + _ZONE_ID_PAT + r")?\]"
+_REG_NAME_PAT = r"(?:[^\[\]%:/?#]|%[a-fA-F0-9]{2})*"
+_TARGET_RE = re.compile(r"^(/[^?#]*)(?:\?([^#]*))?(?:#.*)?$")
+
+_IPV4_RE = re.compile("^" + _IPV4_PAT + "$")
+_IPV6_RE = re.compile("^" + _IPV6_PAT + "$")
+_IPV6_ADDRZ_RE = re.compile("^" + _IPV6_ADDRZ_PAT + "$")
+_BRACELESS_IPV6_ADDRZ_RE = re.compile("^" + _IPV6_ADDRZ_PAT[2:-2] + "$")
+_ZONE_ID_RE = re.compile("(" + _ZONE_ID_PAT + r")\]$")
+
+_HOST_PORT_PAT = ("^(%s|%s|%s)(?::0*?(|0|[1-9][0-9]{0,4}))?$") % (
+ _REG_NAME_PAT,
+ _IPV4_PAT,
+ _IPV6_ADDRZ_PAT,
+)
+_HOST_PORT_RE = re.compile(_HOST_PORT_PAT, re.UNICODE | re.DOTALL)
+
+_UNRESERVED_CHARS = set(
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-~"
+)
+_SUB_DELIM_CHARS = set("!$&'()*+,;=")
+_USERINFO_CHARS = _UNRESERVED_CHARS | _SUB_DELIM_CHARS | {":"}
+_PATH_CHARS = _USERINFO_CHARS | {"@", "/"}
+_QUERY_CHARS = _FRAGMENT_CHARS = _PATH_CHARS | {"?"}
+
+
+class Url(
+ typing.NamedTuple(
+ "Url",
+ [
+ ("scheme", typing.Optional[str]),
+ ("auth", typing.Optional[str]),
+ ("host", typing.Optional[str]),
+ ("port", typing.Optional[int]),
+ ("path", typing.Optional[str]),
+ ("query", typing.Optional[str]),
+ ("fragment", typing.Optional[str]),
+ ],
+ )
+):
+ """
+ Data structure for representing an HTTP URL. Used as a return value for
+ :func:`parse_url`. Both the scheme and host are normalized as they are
+ both case-insensitive according to RFC 3986.
+ """
+
+ def __new__( # type: ignore[no-untyped-def]
+ cls,
+ scheme: str | None = None,
+ auth: str | None = None,
+ host: str | None = None,
+ port: int | None = None,
+ path: str | None = None,
+ query: str | None = None,
+ fragment: str | None = None,
+ ):
+ if path and not path.startswith("/"):
+ path = "/" + path
+ if scheme is not None:
+ scheme = scheme.lower()
+ return super().__new__(cls, scheme, auth, host, port, path, query, fragment)
+
+ @property
+ def hostname(self) -> str | None:
+ """For backwards-compatibility with urlparse. We're nice like that."""
+ return self.host
+
+ @property
+ def request_uri(self) -> str:
+ """Absolute path including the query string."""
+ uri = self.path or "/"
+
+ if self.query is not None:
+ uri += "?" + self.query
+
+ return uri
+
+ @property
+ def authority(self) -> str | None:
+ """
+ Authority component as defined in RFC 3986 3.2.
+ This includes userinfo (auth), host and port.
+
+ i.e.
+ userinfo@host:port
+ """
+ userinfo = self.auth
+ netloc = self.netloc
+ if netloc is None or userinfo is None:
+ return netloc
+ else:
+ return f"{userinfo}@{netloc}"
+
+ @property
+ def netloc(self) -> str | None:
+ """
+ Network location including host and port.
+
+ If you need the equivalent of urllib.parse's ``netloc``,
+ use the ``authority`` property instead.
+ """
+ if self.host is None:
+ return None
+ if self.port:
+ return f"{self.host}:{self.port}"
+ return self.host
+
+ @property
+ def url(self) -> str:
+ """
+ Convert self into a url
+
+ This function should more or less round-trip with :func:`.parse_url`. The
+ returned url may not be exactly the same as the url inputted to
+ :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls
+ with a blank port will have : removed).
+
+ Example:
+
+ .. code-block:: python
+
+ import urllib3
+
+ U = urllib3.util.parse_url("https://google.com/mail/")
+
+ print(U.url)
+ # "https://google.com/mail/"
+
+ print( urllib3.util.Url("https", "username:password",
+ "host.com", 80, "/path", "query", "fragment"
+ ).url
+ )
+ # "https://username:password@host.com:80/path?query#fragment"
+ """
+ scheme, auth, host, port, path, query, fragment = self
+ url = ""
+
+ # We use "is not None" we want things to happen with empty strings (or 0 port)
+ if scheme is not None:
+ url += scheme + "://"
+ if auth is not None:
+ url += auth + "@"
+ if host is not None:
+ url += host
+ if port is not None:
+ url += ":" + str(port)
+ if path is not None:
+ url += path
+ if query is not None:
+ url += "?" + query
+ if fragment is not None:
+ url += "#" + fragment
+
+ return url
+
+ def __str__(self) -> str:
+ return self.url
+
+
+@typing.overload
+def _encode_invalid_chars(
+ component: str, allowed_chars: typing.Container[str]
+) -> str: # Abstract
+ ...
+
+
+@typing.overload
+def _encode_invalid_chars(
+ component: None, allowed_chars: typing.Container[str]
+) -> None: # Abstract
+ ...
+
+
+def _encode_invalid_chars(
+ component: str | None, allowed_chars: typing.Container[str]
+) -> str | None:
+ """Percent-encodes a URI component without reapplying
+ onto an already percent-encoded component.
+ """
+ if component is None:
+ return component
+
+ component = to_str(component)
+
+ # Normalize existing percent-encoded bytes.
+ # Try to see if the component we're encoding is already percent-encoded
+ # so we can skip all '%' characters but still encode all others.
+ component, percent_encodings = _PERCENT_RE.subn(
+ lambda match: match.group(0).upper(), component
+ )
+
+ uri_bytes = component.encode("utf-8", "surrogatepass")
+ is_percent_encoded = percent_encodings == uri_bytes.count(b"%")
+ encoded_component = bytearray()
+
+ for i in range(0, len(uri_bytes)):
+ # Will return a single character bytestring
+ byte = uri_bytes[i : i + 1]
+ byte_ord = ord(byte)
+ if (is_percent_encoded and byte == b"%") or (
+ byte_ord < 128 and byte.decode() in allowed_chars
+ ):
+ encoded_component += byte
+ continue
+ encoded_component.extend(b"%" + (hex(byte_ord)[2:].encode().zfill(2).upper()))
+
+ return encoded_component.decode()
+
+
+def _remove_path_dot_segments(path: str) -> str:
+ # See http://tools.ietf.org/html/rfc3986#section-5.2.4 for pseudo-code
+ segments = path.split("/") # Turn the path into a list of segments
+ output = [] # Initialize the variable to use to store output
+
+ for segment in segments:
+ # '.' is the current directory, so ignore it, it is superfluous
+ if segment == ".":
+ continue
+ # Anything other than '..', should be appended to the output
+ if segment != "..":
+ output.append(segment)
+ # In this case segment == '..', if we can, we should pop the last
+ # element
+ elif output:
+ output.pop()
+
+ # If the path starts with '/' and the output is empty or the first string
+ # is non-empty
+ if path.startswith("/") and (not output or output[0]):
+ output.insert(0, "")
+
+ # If the path starts with '/.' or '/..' ensure we add one more empty
+ # string to add a trailing '/'
+ if path.endswith(("/.", "/..")):
+ output.append("")
+
+ return "/".join(output)
+
+
+@typing.overload
+def _normalize_host(host: None, scheme: str | None) -> None: ...
+
+
+@typing.overload
+def _normalize_host(host: str, scheme: str | None) -> str: ...
+
+
+def _normalize_host(host: str | None, scheme: str | None) -> str | None:
+ if host:
+ if scheme in _NORMALIZABLE_SCHEMES:
+ is_ipv6 = _IPV6_ADDRZ_RE.match(host)
+ if is_ipv6:
+ # IPv6 hosts of the form 'a::b%zone' are encoded in a URL as
+ # such per RFC 6874: 'a::b%25zone'. Unquote the ZoneID
+ # separator as necessary to return a valid RFC 4007 scoped IP.
+ match = _ZONE_ID_RE.search(host)
+ if match:
+ start, end = match.span(1)
+ zone_id = host[start:end]
+
+ if zone_id.startswith("%25") and zone_id != "%25":
+ zone_id = zone_id[3:]
+ else:
+ zone_id = zone_id[1:]
+ zone_id = _encode_invalid_chars(zone_id, _UNRESERVED_CHARS)
+ return f"{host[:start].lower()}%{zone_id}{host[end:]}"
+ else:
+ return host.lower()
+ elif not _IPV4_RE.match(host):
+ return to_str(
+ b".".join([_idna_encode(label) for label in host.split(".")]),
+ "ascii",
+ )
+ return host
+
+
+def _idna_encode(name: str) -> bytes:
+ if not name.isascii():
+ try:
+ import idna
+ except ImportError:
+ raise LocationParseError(
+ "Unable to parse URL without the 'idna' module"
+ ) from None
+
+ try:
+ return idna.encode(name.lower(), strict=True, std3_rules=True)
+ except idna.IDNAError:
+ raise LocationParseError(
+ f"Name '{name}' is not a valid IDNA label"
+ ) from None
+
+ return name.lower().encode("ascii")
+
+
+def _encode_target(target: str) -> str:
+ """Percent-encodes a request target so that there are no invalid characters
+
+ Pre-condition for this function is that 'target' must start with '/'.
+ If that is the case then _TARGET_RE will always produce a match.
+ """
+ match = _TARGET_RE.match(target)
+ if not match: # Defensive:
+ raise LocationParseError(f"{target!r} is not a valid request URI")
+
+ path, query = match.groups()
+ encoded_target = _encode_invalid_chars(path, _PATH_CHARS)
+ if query is not None:
+ query = _encode_invalid_chars(query, _QUERY_CHARS)
+ encoded_target += "?" + query
+ return encoded_target
+
+
+def parse_url(url: str) -> Url:
+ """
+ Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is
+ performed to parse incomplete urls. Fields not provided will be None.
+ This parser is RFC 3986 and RFC 6874 compliant.
+
+ The parser logic and helper functions are based heavily on
+ work done in the ``rfc3986`` module.
+
+ :param str url: URL to parse into a :class:`.Url` namedtuple.
+
+ Partly backwards-compatible with :mod:`urllib.parse`.
+
+ Example:
+
+ .. code-block:: python
+
+ import urllib3
+
+ print( urllib3.util.parse_url('http://google.com/mail/'))
+ # Url(scheme='http', host='google.com', port=None, path='/mail/', ...)
+
+ print( urllib3.util.parse_url('google.com:80'))
+ # Url(scheme=None, host='google.com', port=80, path=None, ...)
+
+ print( urllib3.util.parse_url('/foo?bar'))
+ # Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)
+ """
+ if not url:
+ # Empty
+ return Url()
+
+ source_url = url
+ if not _SCHEME_RE.search(url):
+ url = "//" + url
+
+ scheme: str | None
+ authority: str | None
+ auth: str | None
+ host: str | None
+ port: str | None
+ port_int: int | None
+ path: str | None
+ query: str | None
+ fragment: str | None
+
+ try:
+ scheme, authority, path, query, fragment = _URI_RE.match(url).groups() # type: ignore[union-attr]
+ normalize_uri = scheme is None or scheme.lower() in _NORMALIZABLE_SCHEMES
+
+ if scheme:
+ scheme = scheme.lower()
+
+ if authority:
+ auth, _, host_port = authority.rpartition("@")
+ auth = auth or None
+ host, port = _HOST_PORT_RE.match(host_port).groups() # type: ignore[union-attr]
+ if auth and normalize_uri:
+ auth = _encode_invalid_chars(auth, _USERINFO_CHARS)
+ if port == "":
+ port = None
+ else:
+ auth, host, port = None, None, None
+
+ if port is not None:
+ port_int = int(port)
+ if not (0 <= port_int <= 65535):
+ raise LocationParseError(url)
+ else:
+ port_int = None
+
+ host = _normalize_host(host, scheme)
+
+ if normalize_uri and path:
+ path = _remove_path_dot_segments(path)
+ path = _encode_invalid_chars(path, _PATH_CHARS)
+ if normalize_uri and query:
+ query = _encode_invalid_chars(query, _QUERY_CHARS)
+ if normalize_uri and fragment:
+ fragment = _encode_invalid_chars(fragment, _FRAGMENT_CHARS)
+
+ except (ValueError, AttributeError) as e:
+ raise LocationParseError(source_url) from e
+
+ # For the sake of backwards compatibility we put empty
+ # string values for path if there are any defined values
+ # beyond the path in the URL.
+ # TODO: Remove this when we break backwards compatibility.
+ if not path:
+ if query is not None or fragment is not None:
+ path = ""
+ else:
+ path = None
+
+ return Url(
+ scheme=scheme,
+ auth=auth,
+ host=host,
+ port=port_int,
+ path=path,
+ query=query,
+ fragment=fragment,
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/util.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..35c77e4025842f548565334a3c04cba90f9283d6
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/util.py
@@ -0,0 +1,42 @@
+from __future__ import annotations
+
+import typing
+from types import TracebackType
+
+
+def to_bytes(
+ x: str | bytes, encoding: str | None = None, errors: str | None = None
+) -> bytes:
+ if isinstance(x, bytes):
+ return x
+ elif not isinstance(x, str):
+ raise TypeError(f"not expecting type {type(x).__name__}")
+ if encoding or errors:
+ return x.encode(encoding or "utf-8", errors=errors or "strict")
+ return x.encode()
+
+
+def to_str(
+ x: str | bytes, encoding: str | None = None, errors: str | None = None
+) -> str:
+ if isinstance(x, str):
+ return x
+ elif not isinstance(x, bytes):
+ raise TypeError(f"not expecting type {type(x).__name__}")
+ if encoding or errors:
+ return x.decode(encoding or "utf-8", errors=errors or "strict")
+ return x.decode()
+
+
+def reraise(
+ tp: type[BaseException] | None,
+ value: BaseException,
+ tb: TracebackType | None = None,
+) -> typing.NoReturn:
+ try:
+ if value.__traceback__ is not tb:
+ raise value.with_traceback(tb)
+ raise value
+ finally:
+ value = None # type: ignore[assignment]
+ tb = None
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/wait.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/wait.py
new file mode 100644
index 0000000000000000000000000000000000000000..aeca0c7ad5b232eeb1ad9c43d315bd1d74eaed9a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/urllib3/util/wait.py
@@ -0,0 +1,124 @@
+from __future__ import annotations
+
+import select
+import socket
+from functools import partial
+
+__all__ = ["wait_for_read", "wait_for_write"]
+
+
+# How should we wait on sockets?
+#
+# There are two types of APIs you can use for waiting on sockets: the fancy
+# modern stateful APIs like epoll/kqueue, and the older stateless APIs like
+# select/poll. The stateful APIs are more efficient when you have a lots of
+# sockets to keep track of, because you can set them up once and then use them
+# lots of times. But we only ever want to wait on a single socket at a time
+# and don't want to keep track of state, so the stateless APIs are actually
+# more efficient. So we want to use select() or poll().
+#
+# Now, how do we choose between select() and poll()? On traditional Unixes,
+# select() has a strange calling convention that makes it slow, or fail
+# altogether, for high-numbered file descriptors. The point of poll() is to fix
+# that, so on Unixes, we prefer poll().
+#
+# On Windows, there is no poll() (or at least Python doesn't provide a wrapper
+# for it), but that's OK, because on Windows, select() doesn't have this
+# strange calling convention; plain select() works fine.
+#
+# So: on Windows we use select(), and everywhere else we use poll(). We also
+# fall back to select() in case poll() is somehow broken or missing.
+
+
+def select_wait_for_socket(
+ sock: socket.socket,
+ read: bool = False,
+ write: bool = False,
+ timeout: float | None = None,
+) -> bool:
+ if not read and not write:
+ raise RuntimeError("must specify at least one of read=True, write=True")
+ rcheck = []
+ wcheck = []
+ if read:
+ rcheck.append(sock)
+ if write:
+ wcheck.append(sock)
+ # When doing a non-blocking connect, most systems signal success by
+ # marking the socket writable. Windows, though, signals success by marked
+ # it as "exceptional". We paper over the difference by checking the write
+ # sockets for both conditions. (The stdlib selectors module does the same
+ # thing.)
+ fn = partial(select.select, rcheck, wcheck, wcheck)
+ rready, wready, xready = fn(timeout)
+ return bool(rready or wready or xready)
+
+
+def poll_wait_for_socket(
+ sock: socket.socket,
+ read: bool = False,
+ write: bool = False,
+ timeout: float | None = None,
+) -> bool:
+ if not read and not write:
+ raise RuntimeError("must specify at least one of read=True, write=True")
+ mask = 0
+ if read:
+ mask |= select.POLLIN
+ if write:
+ mask |= select.POLLOUT
+ poll_obj = select.poll()
+ poll_obj.register(sock, mask)
+
+ # For some reason, poll() takes timeout in milliseconds
+ def do_poll(t: float | None) -> list[tuple[int, int]]:
+ if t is not None:
+ t *= 1000
+ return poll_obj.poll(t)
+
+ return bool(do_poll(timeout))
+
+
+def _have_working_poll() -> bool:
+ # Apparently some systems have a select.poll that fails as soon as you try
+ # to use it, either due to strange configuration or broken monkeypatching
+ # from libraries like eventlet/greenlet.
+ try:
+ poll_obj = select.poll()
+ poll_obj.poll(0)
+ except (AttributeError, OSError):
+ return False
+ else:
+ return True
+
+
+def wait_for_socket(
+ sock: socket.socket,
+ read: bool = False,
+ write: bool = False,
+ timeout: float | None = None,
+) -> bool:
+ # We delay choosing which implementation to use until the first time we're
+ # called. We could do it at import time, but then we might make the wrong
+ # decision if someone goes wild with monkeypatching select.poll after
+ # we're imported.
+ global wait_for_socket
+ if _have_working_poll():
+ wait_for_socket = poll_wait_for_socket
+ elif hasattr(select, "select"):
+ wait_for_socket = select_wait_for_socket
+ return wait_for_socket(sock, read, write, timeout)
+
+
+def wait_for_read(sock: socket.socket, timeout: float | None = None) -> bool:
+ """Waits for reading to be available on a given socket.
+ Returns True if the socket is readable, or False if the timeout expired.
+ """
+ return wait_for_socket(sock, read=True, timeout=timeout)
+
+
+def wait_for_write(sock: socket.socket, timeout: float | None = None) -> bool:
+ """Waits for writing to be available on a given socket.
+ Returns True if the socket is readable, or False if the timeout expired.
+ """
+ return wait_for_socket(sock, write=True, timeout=timeout)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1c2e09fdcbcb01e86fa45034ce01ebe959f3862
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/__init__.py
@@ -0,0 +1,248 @@
+"""Use wandb to track machine learning work.
+
+Train and fine-tune models, manage models from experimentation to production.
+
+For guides and examples, see https://docs.wandb.ai.
+
+For scripts and interactive notebooks, see https://github.com/wandb/examples.
+
+For reference documentation, see https://docs.wandb.com/ref/python.
+"""
+from __future__ import annotations
+
+__version__ = "0.22.2"
+
+
+from wandb.errors import Error
+
+# This needs to be early as other modules call it.
+from wandb.errors.term import termsetup, termlog, termerror, termwarn
+
+# Configure the logger as early as possible for consistent behavior.
+from wandb.sdk.lib import wb_logging as _wb_logging
+_wb_logging.configure_wandb_logger()
+
+from wandb import sdk as wandb_sdk
+
+import wandb
+
+wandb.wandb_lib = wandb_sdk.lib # type: ignore
+
+init = wandb_sdk.init
+setup = wandb_sdk.setup
+attach = _attach = wandb_sdk._attach
+_sync = wandb_sdk._sync
+teardown = _teardown = wandb_sdk.teardown
+finish = wandb_sdk.finish
+join = finish
+login = wandb_sdk.login
+helper = wandb_sdk.helper
+sweep = wandb_sdk.sweep
+controller = wandb_sdk.controller
+require = wandb_sdk.require
+Artifact = wandb_sdk.Artifact
+AlertLevel = wandb_sdk.AlertLevel
+Settings = wandb_sdk.Settings
+Config = wandb_sdk.Config
+
+from wandb.apis import InternalApi, PublicApi
+from wandb.errors import CommError, UsageError
+
+_preinit = wandb.wandb_lib.preinit # type: ignore
+_lazyloader = wandb.wandb_lib.lazyloader # type: ignore
+
+from wandb.integration.torch import wandb_torch
+
+# Move this (keras.__init__ expects it at top level)
+from wandb.sdk.data_types._private import _cleanup_media_tmp_dir
+
+_cleanup_media_tmp_dir()
+
+from wandb.data_types import Graph
+from wandb.data_types import Image
+from wandb.data_types import Plotly
+
+# from wandb.data_types import Bokeh # keeping out of top level for now since Bokeh plots have poor UI
+from wandb.data_types import Video
+from wandb.data_types import Audio
+from wandb.data_types import Table
+from wandb.data_types import Html
+from wandb.data_types import box3d
+from wandb.data_types import Object3D
+from wandb.data_types import Molecule
+from wandb.data_types import Histogram
+from wandb.data_types import Classes
+from wandb.data_types import JoinedTable
+
+from wandb.wandb_agent import agent
+
+from wandb.plot import visualize, plot_table
+from wandb.integration.sagemaker import sagemaker_auth
+from wandb.sdk.internal import profiler
+from wandb.sdk.wandb_run import Run
+
+# Artifact import types
+from wandb.sdk.artifacts.artifact_ttl import ArtifactTTL
+
+# Used to make sure we don't use some code in the incorrect process context
+_IS_INTERNAL_PROCESS = False
+
+
+def _set_internal_process(disable=False):
+ global _IS_INTERNAL_PROCESS
+ if _IS_INTERNAL_PROCESS is None:
+ return
+ if disable:
+ _IS_INTERNAL_PROCESS = None
+ return
+ _IS_INTERNAL_PROCESS = True
+
+
+def _assert_is_internal_process():
+ if _IS_INTERNAL_PROCESS is None:
+ return
+ assert _IS_INTERNAL_PROCESS
+
+
+def _assert_is_user_process():
+ if _IS_INTERNAL_PROCESS is None:
+ return
+ assert not _IS_INTERNAL_PROCESS
+
+
+# globals
+Api = PublicApi
+api = InternalApi()
+run: Run | None = None
+config = _preinit.PreInitObject("wandb.config", wandb_sdk.wandb_config.Config)
+summary = _preinit.PreInitObject("wandb.summary", wandb_sdk.wandb_summary.Summary)
+log = _preinit.PreInitCallable("wandb.log", Run.log) # type: ignore
+watch = _preinit.PreInitCallable("wandb.watch", Run.watch) # type: ignore
+unwatch = _preinit.PreInitCallable("wandb.unwatch", Run.unwatch) # type: ignore
+save = _preinit.PreInitCallable("wandb.save", Run.save) # type: ignore
+restore = wandb_sdk.wandb_run.restore
+use_artifact = _preinit.PreInitCallable(
+ "wandb.use_artifact", Run.use_artifact # type: ignore
+)
+log_artifact = _preinit.PreInitCallable(
+ "wandb.log_artifact", Run.log_artifact # type: ignore
+)
+log_model = _preinit.PreInitCallable(
+ "wandb.log_model", Run.log_model # type: ignore
+)
+use_model = _preinit.PreInitCallable(
+ "wandb.use_model", Run.use_model # type: ignore
+)
+link_model = _preinit.PreInitCallable(
+ "wandb.link_model", Run.link_model # type: ignore
+)
+define_metric = _preinit.PreInitCallable(
+ "wandb.define_metric", Run.define_metric # type: ignore
+)
+
+mark_preempting = _preinit.PreInitCallable(
+ "wandb.mark_preempting", Run.mark_preempting # type: ignore
+)
+
+alert = _preinit.PreInitCallable("wandb.alert", Run.alert) # type: ignore
+
+# record of patched libraries
+patched = {"tensorboard": [], "keras": [], "gym": []} # type: ignore
+
+keras = _lazyloader.LazyLoader("wandb.keras", globals(), "wandb.integration.keras")
+sklearn = _lazyloader.LazyLoader("wandb.sklearn", globals(), "wandb.sklearn")
+tensorflow = _lazyloader.LazyLoader(
+ "wandb.tensorflow", globals(), "wandb.integration.tensorflow"
+)
+xgboost = _lazyloader.LazyLoader(
+ "wandb.xgboost", globals(), "wandb.integration.xgboost"
+)
+catboost = _lazyloader.LazyLoader(
+ "wandb.catboost", globals(), "wandb.integration.catboost"
+)
+tensorboard = _lazyloader.LazyLoader(
+ "wandb.tensorboard", globals(), "wandb.integration.tensorboard"
+)
+gym = _lazyloader.LazyLoader("wandb.gym", globals(), "wandb.integration.gym")
+lightgbm = _lazyloader.LazyLoader(
+ "wandb.lightgbm", globals(), "wandb.integration.lightgbm"
+)
+jupyter = _lazyloader.LazyLoader("wandb.jupyter", globals(), "wandb.jupyter")
+sacred = _lazyloader.LazyLoader("wandb.sacred", globals(), "wandb.integration.sacred")
+
+
+def ensure_configured():
+ global api
+ api = InternalApi()
+
+
+def set_trace():
+ import pdb # TODO: support other debuggers
+
+ # frame = sys._getframe().f_back
+ pdb.set_trace() # TODO: pass the parent stack...
+
+
+def load_ipython_extension(ipython):
+ ipython.register_magics(wandb.jupyter.WandBMagics)
+
+
+if wandb_sdk.lib.ipython.in_notebook():
+ from IPython import get_ipython # type: ignore[import-not-found]
+
+ load_ipython_extension(get_ipython())
+
+
+from .analytics import Sentry as _Sentry
+
+if "dev" in __version__:
+ import wandb.env
+ import os
+
+ # Disable error reporting in dev versions.
+ os.environ[wandb.env.ERROR_REPORTING] = os.environ.get(
+ wandb.env.ERROR_REPORTING,
+ "false",
+ )
+
+_sentry = _Sentry()
+_sentry.setup()
+
+
+__all__ = (
+ "__version__",
+ "init",
+ "finish",
+ "setup",
+ "save",
+ "sweep",
+ "controller",
+ "agent",
+ "config",
+ "log",
+ "summary",
+ "join",
+ "Api",
+ "Graph",
+ "Image",
+ "Plotly",
+ "Video",
+ "Audio",
+ "Table",
+ "Html",
+ "box3d",
+ "Object3D",
+ "Molecule",
+ "Histogram",
+ "ArtifactTTL",
+ "log_artifact",
+ "use_artifact",
+ "log_model",
+ "use_model",
+ "link_model",
+ "define_metric",
+ "watch",
+ "unwatch",
+ "plot_table",
+ "Run",
+)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/__init__.pyi b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/__init__.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..84e3445b0fc98444c2f9fab0f35695f89f6bbeca
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/__init__.pyi
@@ -0,0 +1,1233 @@
+"""Use wandb to track machine learning work.
+
+Train and fine-tune models, manage models from experimentation to production.
+
+For guides and examples, see https://docs.wandb.ai.
+
+For scripts and interactive notebooks, see https://github.com/wandb/examples.
+
+For reference documentation, see https://docs.wandb.com/ref/python.
+"""
+
+from __future__ import annotations
+
+__all__ = (
+ "__version__", # doc:exclude
+ "init",
+ "finish",
+ "setup",
+ "login",
+ "save", # doc:exclude
+ "sweep",
+ "controller",
+ "agent",
+ "config", # doc:exclude
+ "log", # doc:exclude
+ "summary", # doc:exclude
+ "Api",
+ "Graph", # doc:exclude
+ "Image",
+ "Plotly",
+ "Video",
+ "Audio",
+ "Table",
+ "Html",
+ "box3d",
+ "Object3D",
+ "Molecule",
+ "Histogram",
+ "ArtifactTTL", # doc:exclude
+ "log_artifact", # doc:exclude
+ "use_artifact", # doc:exclude
+ "log_model", # doc:exclude
+ "use_model", # doc:exclude
+ "link_model", # doc:exclude
+ "define_metric", # doc:exclude
+ "Error", # doc:exclude
+ "termsetup", # doc:exclude
+ "termlog", # doc:exclude
+ "termerror", # doc:exclude
+ "termwarn", # doc:exclude
+ "Artifact",
+ "Settings",
+ "teardown",
+ "watch", # doc:exclude
+ "unwatch", # doc:exclude
+ "plot", # doc:exclude
+ "plot_table",
+ "restore",
+ "Run",
+)
+
+import os
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Dict,
+ Iterable,
+ List,
+ Literal,
+ Optional,
+ Sequence,
+ TextIO,
+ Union,
+)
+
+import wandb.plot as plot
+from wandb.analytics import Sentry
+from wandb.apis import InternalApi
+from wandb.apis import PublicApi as Api
+from wandb.data_types import (
+ Audio,
+ Graph,
+ Histogram,
+ Html,
+ Image,
+ Molecule,
+ Object3D,
+ Plotly,
+ Table,
+ Video,
+ box3d,
+)
+from wandb.errors import Error
+from wandb.errors.term import termerror, termlog, termsetup, termwarn
+from wandb.sdk import Artifact, Settings, wandb_config, wandb_metric, wandb_summary
+from wandb.sdk.artifacts.artifact_ttl import ArtifactTTL
+from wandb.sdk.interface.interface import PolicyName
+from wandb.sdk.lib.paths import FilePathStr, StrPath
+from wandb.sdk.wandb_run import Run
+from wandb.sdk.wandb_setup import _WandbSetup
+from wandb.wandb_controller import _WandbController
+
+if TYPE_CHECKING:
+ import torch # type: ignore [import-not-found]
+
+ import wandb
+ from wandb.plot import CustomChart
+
+__version__: str = "0.22.2"
+
+run: Run | None
+config: wandb_config.Config
+summary: wandb_summary.Summary
+
+# private attributes
+_sentry: Sentry
+api: InternalApi
+patched: Dict[str, List[Callable]]
+
+def require(
+ requirement: str | Iterable[str] | None = None,
+ experiment: str | Iterable[str] | None = None,
+) -> None:
+ """Indicate which experimental features are used by the script.
+
+ This should be called before any other `wandb` functions, ideally right
+ after importing `wandb`.
+
+ Args:
+ requirement: The name of a feature to require or an iterable of
+ feature names.
+ experiment: An alias for `requirement`.
+
+ Raises:
+ wandb.errors.UnsupportedError: If a feature name is unknown.
+ """
+ ...
+
+def setup(settings: Settings | None = None) -> _WandbSetup:
+ """Prepares W&B for use in the current process and its children.
+
+ You can usually ignore this as it is implicitly called by `wandb.init()`.
+
+ When using wandb in multiple processes, calling `wandb.setup()`
+ in the parent process before starting child processes may improve
+ performance and resource utilization.
+
+ Note that `wandb.setup()` modifies `os.environ`, and it is important
+ that child processes inherit the modified environment variables.
+
+ See also `wandb.teardown()`.
+
+ Args:
+ settings: Configuration settings to apply globally. These can be
+ overridden by subsequent `wandb.init()` calls.
+
+ Example:
+ ```python
+ import multiprocessing
+
+ import wandb
+
+ def run_experiment(params):
+ with wandb.init(config=params):
+ # Run experiment
+ pass
+
+ if __name__ == "__main__":
+ # Start backend and set global config
+ wandb.setup(settings={"project": "my_project"})
+
+ # Define experiment parameters
+ experiment_params = [
+ {"learning_rate": 0.01, "epochs": 10},
+ {"learning_rate": 0.001, "epochs": 20},
+ ]
+
+ # Start multiple processes, each running a separate experiment
+ processes = []
+ for params in experiment_params:
+ p = multiprocessing.Process(target=run_experiment, args=(params,))
+ p.start()
+ processes.append(p)
+
+ # Wait for all processes to complete
+ for p in processes:
+ p.join()
+
+ # Optional: Explicitly shut down the backend
+ wandb.teardown()
+ ```
+ """
+ ...
+
+def teardown(exit_code: int | None = None) -> None:
+ """Waits for W&B to finish and frees resources.
+
+ Completes any runs that were not explicitly finished
+ using `run.finish()` and waits for all data to be uploaded.
+
+ It is recommended to call this at the end of a session
+ that used `wandb.setup()`. It is invoked automatically
+ in an `atexit` hook, but this is not reliable in certain setups
+ such as when using Python's `multiprocessing` module.
+ """
+ ...
+
+def init(
+ entity: str | None = None,
+ project: str | None = None,
+ dir: StrPath | None = None,
+ id: str | None = None,
+ name: str | None = None,
+ notes: str | None = None,
+ tags: Sequence[str] | None = None,
+ config: dict[str, Any] | str | None = None,
+ config_exclude_keys: list[str] | None = None,
+ config_include_keys: list[str] | None = None,
+ allow_val_change: bool | None = None,
+ group: str | None = None,
+ job_type: str | None = None,
+ mode: Literal["online", "offline", "disabled", "shared"] | None = None,
+ force: bool | None = None,
+ anonymous: Literal["never", "allow", "must"] | None = None,
+ reinit: (
+ bool
+ | Literal[
+ None,
+ "default",
+ "return_previous",
+ "finish_previous",
+ "create_new",
+ ]
+ ) = None,
+ resume: bool | Literal["allow", "never", "must", "auto"] | None = None,
+ resume_from: str | None = None,
+ fork_from: str | None = None,
+ save_code: bool | None = None,
+ tensorboard: bool | None = None,
+ sync_tensorboard: bool | None = None,
+ monitor_gym: bool | None = None,
+ settings: Settings | dict[str, Any] | None = None,
+) -> Run:
+ r"""Start a new run to track and log to W&B.
+
+ In an ML training pipeline, you could add `wandb.init()` to the beginning of
+ your training script as well as your evaluation script, and each piece would
+ be tracked as a run in W&B.
+
+ `wandb.init()` spawns a new background process to log data to a run, and it
+ also syncs data to https://wandb.ai by default, so you can see your results
+ in real-time. When you're done logging data, call `wandb.Run.finish()` to end the run.
+ If you don't call `run.finish()`, the run will end when your script exits.
+
+ Run IDs must not contain any of the following special characters `/ \ # ? % :`
+
+ Args:
+ entity: The username or team name the runs are logged to.
+ The entity must already exist, so ensure you create your account
+ or team in the UI before starting to log runs. If not specified, the
+ run will default your default entity. To change the default entity,
+ go to your settings and update the
+ "Default location to create new projects" under "Default team".
+ project: The name of the project under which this run will be logged.
+ If not specified, we use a heuristic to infer the project name based
+ on the system, such as checking the git root or the current program
+ file. If we can't infer the project name, the project will default to
+ `"uncategorized"`.
+ dir: The absolute path to the directory where experiment logs and
+ metadata files are stored. If not specified, this defaults
+ to the `./wandb` directory. Note that this does not affect the
+ location where artifacts are stored when calling `download()`.
+ id: A unique identifier for this run, used for resuming. It must be unique
+ within the project and cannot be reused once a run is deleted. For
+ a short descriptive name, use the `name` field,
+ or for saving hyperparameters to compare across runs, use `config`.
+ name: A short display name for this run, which appears in the UI to help
+ you identify it. By default, we generate a random two-word name
+ allowing easy cross-reference runs from table to charts. Keeping these
+ run names brief enhances readability in chart legends and tables. For
+ saving hyperparameters, we recommend using the `config` field.
+ notes: A detailed description of the run, similar to a commit message in
+ Git. Use this argument to capture any context or details that may
+ help you recall the purpose or setup of this run in the future.
+ tags: A list of tags to label this run in the UI. Tags are helpful for
+ organizing runs or adding temporary identifiers like "baseline" or
+ "production." You can easily add, remove tags, or filter by tags in
+ the UI.
+ If resuming a run, the tags provided here will replace any existing
+ tags. To add tags to a resumed run without overwriting the current
+ tags, use `run.tags += ("new_tag",)` after calling `run = wandb.init()`.
+ config: Sets `wandb.config`, a dictionary-like object for storing input
+ parameters to your run, such as model hyperparameters or data
+ preprocessing settings.
+ The config appears in the UI in an overview page, allowing you to
+ group, filter, and sort runs based on these parameters.
+ Keys should not contain periods (`.`), and values should be
+ smaller than 10 MB.
+ If a dictionary, `argparse.Namespace`, or `absl.flags.FLAGS` is
+ provided, the key-value pairs will be loaded directly into
+ `wandb.config`.
+ If a string is provided, it is interpreted as a path to a YAML file,
+ from which configuration values will be loaded into `wandb.config`.
+ config_exclude_keys: A list of specific keys to exclude from `wandb.config`.
+ config_include_keys: A list of specific keys to include in `wandb.config`.
+ allow_val_change: Controls whether config values can be modified after their
+ initial set. By default, an exception is raised if a config value is
+ overwritten. For tracking variables that change during training, such as
+ a learning rate, consider using `wandb.log()` instead. By default, this
+ is `False` in scripts and `True` in Notebook environments.
+ group: Specify a group name to organize individual runs as part of a larger
+ experiment. This is useful for cases like cross-validation or running
+ multiple jobs that train and evaluate a model on different test sets.
+ Grouping allows you to manage related runs collectively in the UI,
+ making it easy to toggle and review results as a unified experiment.
+ job_type: Specify the type of run, especially helpful when organizing runs
+ within a group as part of a larger experiment. For example, in a group,
+ you might label runs with job types such as "train" and "eval".
+ Defining job types enables you to easily filter and group similar runs
+ in the UI, facilitating direct comparisons.
+ mode: Specifies how run data is managed, with the following options:
+ - `"online"` (default): Enables live syncing with W&B when a network
+ connection is available, with real-time updates to visualizations.
+ - `"offline"`: Suitable for air-gapped or offline environments; data
+ is saved locally and can be synced later. Ensure the run folder
+ is preserved to enable future syncing.
+ - `"disabled"`: Disables all W&B functionality, making the run’s methods
+ no-ops. Typically used in testing to bypass W&B operations.
+ - `"shared"`: (This is an experimental feature). Allows multiple processes,
+ possibly on different machines, to simultaneously log to the same run.
+ In this approach you use a primary node and one or more worker nodes
+ to log data to the same run. Within the primary node you
+ initialize a run. For each worker node, initialize a run
+ using the run ID used by the primary node.
+ force: Determines if a W&B login is required to run the script. If `True`,
+ the user must be logged in to W&B; otherwise, the script will not
+ proceed. If `False` (default), the script can proceed without a login,
+ switching to offline mode if the user is not logged in.
+ anonymous: Specifies the level of control over anonymous data logging.
+ Available options are:
+ - `"never"` (default): Requires you to link your W&B account before
+ tracking the run. This prevents unintentional creation of anonymous
+ runs by ensuring each run is associated with an account.
+ - `"allow"`: Enables a logged-in user to track runs with their account,
+ but also allows someone running the script without a W&B account
+ to view the charts and data in the UI.
+ - `"must"`: Forces the run to be logged to an anonymous account, even
+ if the user is logged in.
+ reinit: Shorthand for the "reinit" setting. Determines the behavior of
+ `wandb.init()` when a run is active.
+ resume: Controls the behavior when resuming a run with the specified `id`.
+ Available options are:
+ - `"allow"`: If a run with the specified `id` exists, it will resume
+ from the last step; otherwise, a new run will be created.
+ - `"never"`: If a run with the specified `id` exists, an error will
+ be raised. If no such run is found, a new run will be created.
+ - `"must"`: If a run with the specified `id` exists, it will resume
+ from the last step. If no run is found, an error will be raised.
+ - `"auto"`: Automatically resumes the previous run if it crashed on
+ this machine; otherwise, starts a new run.
+ - `True`: Deprecated. Use `"auto"` instead.
+ - `False`: Deprecated. Use the default behavior (leaving `resume`
+ unset) to always start a new run.
+ If `resume` is set, `fork_from` and `resume_from` cannot be
+ used. When `resume` is unset, the system will always start a new run.
+ resume_from: Specifies a moment in a previous run to resume a run from,
+ using the format `{run_id}?_step={step}`. This allows users to truncate
+ the history logged to a run at an intermediate step and resume logging
+ from that step. The target run must be in the same project.
+ If an `id` argument is also provided, the `resume_from` argument will
+ take precedence.
+ `resume`, `resume_from` and `fork_from` cannot be used together, only
+ one of them can be used at a time.
+ Note that this feature is in beta and may change in the future.
+ fork_from: Specifies a point in a previous run from which to fork a new
+ run, using the format `{id}?_step={step}`. This creates a new run that
+ resumes logging from the specified step in the target run’s history.
+ The target run must be part of the current project.
+ If an `id` argument is also provided, it must be different from the
+ `fork_from` argument, an error will be raised if they are the same.
+ `resume`, `resume_from` and `fork_from` cannot be used together, only
+ one of them can be used at a time.
+ Note that this feature is in beta and may change in the future.
+ save_code: Enables saving the main script or notebook to W&B, aiding in
+ experiment reproducibility and allowing code comparisons across runs in
+ the UI. By default, this is disabled, but you can change the default to
+ enable on your settings page.
+ tensorboard: Deprecated. Use `sync_tensorboard` instead.
+ sync_tensorboard: Enables automatic syncing of W&B logs from TensorBoard
+ or TensorBoardX, saving relevant event files for viewing in
+ the W&B UI.
+ monitor_gym: Enables automatic logging of videos of the environment when
+ using OpenAI Gym.
+ settings: Specifies a dictionary or `wandb.Settings` object with advanced
+ settings for the run.
+
+ Returns:
+ A `Run` object.
+
+ Raises:
+ Error: If some unknown or internal error happened during the run
+ initialization.
+ AuthenticationError: If the user failed to provide valid credentials.
+ CommError: If there was a problem communicating with the WandB server.
+ UsageError: If the user provided invalid arguments.
+ KeyboardInterrupt: If user interrupts the run.
+
+ Examples:
+ `wandb.init()` returns a `Run` object. Use the run object to log data,
+ save artifacts, and manage the run lifecycle.
+
+ ```python
+ import wandb
+
+ config = {"lr": 0.01, "batch_size": 32}
+ with wandb.init(config=config) as run:
+ # Log accuracy and loss to the run
+ acc = 0.95 # Example accuracy
+ loss = 0.05 # Example loss
+ run.log({"accuracy": acc, "loss": loss})
+ ```
+ """
+ ...
+
+def finish(
+ exit_code: int | None = None,
+ quiet: bool | None = None,
+) -> None:
+ """Finish a run and upload any remaining data.
+
+ Marks the completion of a W&B run and ensures all data is synced to the server.
+ The run's final state is determined by its exit conditions and sync status.
+
+ Run States:
+ - Running: Active run that is logging data and/or sending heartbeats.
+ - Crashed: Run that stopped sending heartbeats unexpectedly.
+ - Finished: Run completed successfully (`exit_code=0`) with all data synced.
+ - Failed: Run completed with errors (`exit_code!=0`).
+
+ Args:
+ exit_code: Integer indicating the run's exit status. Use 0 for success,
+ any other value marks the run as failed.
+ quiet: Deprecated. Configure logging verbosity using `wandb.Settings(quiet=...)`.
+ """
+ ...
+
+def login(
+ anonymous: Optional[Literal["must", "allow", "never"]] = None,
+ key: Optional[str] = None,
+ relogin: Optional[bool] = None,
+ host: Optional[str] = None,
+ force: Optional[bool] = None,
+ timeout: Optional[int] = None,
+ verify: bool = False,
+ referrer: Optional[str] = None,
+) -> bool:
+ """Set up W&B login credentials.
+
+ By default, this will only store credentials locally without
+ verifying them with the W&B server. To verify credentials, pass
+ `verify=True`.
+
+ Args:
+ anonymous: Set to "must", "allow", or "never".
+ If set to "must", always log a user in anonymously. If set to
+ "allow", only create an anonymous user if the user
+ isn't already logged in. If set to "never", never log a
+ user anonymously. Default set to "never". Defaults to `None`.
+ key: The API key to use.
+ relogin: If true, will re-prompt for API key.
+ host: The host to connect to.
+ force: If true, will force a relogin.
+ timeout: Number of seconds to wait for user input.
+ verify: Verify the credentials with the W&B server.
+ referrer: The referrer to use in the URL login request.
+
+
+ Returns:
+ bool: If `key` is configured.
+
+ Raises:
+ AuthenticationError: If `api_key` fails verification with the server.
+ UsageError: If `api_key` cannot be configured and no tty.
+ """
+ ...
+
+def log(
+ data: dict[str, Any],
+ step: int | None = None,
+ commit: bool | None = None,
+) -> None:
+ """Upload run data.
+
+ Use `log` to log data from runs, such as scalars, images, video,
+ histograms, plots, and tables. See [Log objects and media](https://docs.wandb.ai/guides/track/log) for
+ code snippets, best practices, and more.
+
+ Basic usage:
+
+ ```python
+ import wandb
+
+ with wandb.init() as run:
+ run.log({"train-loss": 0.5, "accuracy": 0.9})
+ ```
+
+ The previous code snippet saves the loss and accuracy to the run's
+ history and updates the summary values for these metrics.
+
+ Visualize logged data in a workspace at [wandb.ai](https://wandb.ai),
+ or locally on a [self-hosted instance](https://docs.wandb.ai/guides/hosting)
+ of the W&B app, or export data to visualize and explore locally, such as in a
+ Jupyter notebook, with the [Public API](https://docs.wandb.ai/guides/track/public-api-guide).
+
+ Logged values don't have to be scalars. You can log any
+ [W&B supported Data Type](https://docs.wandb.ai/ref/python/data-types/)
+ such as images, audio, video, and more. For example, you can use
+ `wandb.Table` to log structured data. See
+ [Log tables, visualize and query data](https://docs.wandb.ai/guides/models/tables/tables-walkthrough)
+ tutorial for more details.
+
+ W&B organizes metrics with a forward slash (`/`) in their name
+ into sections named using the text before the final slash. For example,
+ the following results in two sections named "train" and "validate":
+
+ ```python
+ with wandb.init() as run:
+ # Log metrics in the "train" section.
+ run.log(
+ {
+ "train/accuracy": 0.9,
+ "train/loss": 30,
+ "validate/accuracy": 0.8,
+ "validate/loss": 20,
+ }
+ )
+ ```
+
+ Only one level of nesting is supported; `run.log({"a/b/c": 1})`
+ produces a section named "a/b".
+
+ `run.log()` is not intended to be called more than a few times per second.
+ For optimal performance, limit your logging to once every N iterations,
+ or collect data over multiple iterations and log it in a single step.
+
+ By default, each call to `log` creates a new "step".
+ The step must always increase, and it is not possible to log
+ to a previous step. You can use any metric as the X axis in charts.
+ See [Custom log axes](https://docs.wandb.ai/guides/track/log/customize-logging-axes/)
+ for more details.
+
+ In many cases, it is better to treat the W&B step like
+ you'd treat a timestamp rather than a training step.
+
+ ```python
+ with wandb.init() as run:
+ # Example: log an "epoch" metric for use as an X axis.
+ run.log({"epoch": 40, "train-loss": 0.5})
+ ```
+
+ It is possible to use multiple `wandb.Run.log()` invocations to log to
+ the same step with the `step` and `commit` parameters.
+ The following are all equivalent:
+
+ ```python
+ with wandb.init() as run:
+ # Normal usage:
+ run.log({"train-loss": 0.5, "accuracy": 0.8})
+ run.log({"train-loss": 0.4, "accuracy": 0.9})
+
+ # Implicit step without auto-incrementing:
+ run.log({"train-loss": 0.5}, commit=False)
+ run.log({"accuracy": 0.8})
+ run.log({"train-loss": 0.4}, commit=False)
+ run.log({"accuracy": 0.9})
+
+ # Explicit step:
+ run.log({"train-loss": 0.5}, step=current_step)
+ run.log({"accuracy": 0.8}, step=current_step)
+ current_step += 1
+ run.log({"train-loss": 0.4}, step=current_step)
+ run.log({"accuracy": 0.9}, step=current_step)
+ ```
+
+ Args:
+ data: A `dict` with `str` keys and values that are serializable
+ Python objects including: `int`, `float` and `string`;
+ any of the `wandb.data_types`; lists, tuples and NumPy arrays
+ of serializable Python objects; other `dict`s of this
+ structure.
+ step: The step number to log. If `None`, then an implicit
+ auto-incrementing step is used. See the notes in
+ the description.
+ commit: If true, finalize and upload the step. If false, then
+ accumulate data for the step. See the notes in the description.
+ If `step` is `None`, then the default is `commit=True`;
+ otherwise, the default is `commit=False`.
+
+ Examples:
+ For more and more detailed examples, see
+ [our guides to logging](https://docs.wandb.com/guides/track/log).
+
+ Basic usage
+
+ ```python
+ import wandb
+
+ with wandb.init() as run:
+ run.log({"train-loss": 0.5, "accuracy": 0.9
+ ```
+
+ Incremental logging
+
+ ```python
+ import wandb
+
+ with wandb.init() as run:
+ run.log({"loss": 0.2}, commit=False)
+ # Somewhere else when I'm ready to report this step:
+ run.log({"accuracy": 0.8})
+ ```
+
+ Histogram
+
+ ```python
+ import numpy as np
+ import wandb
+
+ # sample gradients at random from normal distribution
+ gradients = np.random.randn(100, 100)
+ with wandb.init() as run:
+ run.log({"gradients": wandb.Histogram(gradients)})
+ ```
+
+ Image from NumPy
+
+ ```python
+ import numpy as np
+ import wandb
+
+ with wandb.init() as run:
+ examples = []
+ for i in range(3):
+ pixels = np.random.randint(low=0, high=256, size=(100, 100, 3))
+ image = wandb.Image(pixels, caption=f"random field {i}")
+ examples.append(image)
+ run.log({"examples": examples})
+ ```
+
+ Image from PIL
+
+ ```python
+ import numpy as np
+ from PIL import Image as PILImage
+ import wandb
+
+ with wandb.init() as run:
+ examples = []
+ for i in range(3):
+ pixels = np.random.randint(
+ low=0,
+ high=256,
+ size=(100, 100, 3),
+ dtype=np.uint8,
+ )
+ pil_image = PILImage.fromarray(pixels, mode="RGB")
+ image = wandb.Image(pil_image, caption=f"random field {i}")
+ examples.append(image)
+ run.log({"examples": examples})
+ ```
+
+ Video from NumPy
+
+ ```python
+ import numpy as np
+ import wandb
+
+ with wandb.init() as run:
+ # axes are (time, channel, height, width)
+ frames = np.random.randint(
+ low=0,
+ high=256,
+ size=(10, 3, 100, 100),
+ dtype=np.uint8,
+ )
+ run.log({"video": wandb.Video(frames, fps=4)})
+ ```
+
+ Matplotlib plot
+
+ ```python
+ from matplotlib import pyplot as plt
+ import numpy as np
+ import wandb
+
+ with wandb.init() as run:
+ fig, ax = plt.subplots()
+ x = np.linspace(0, 10)
+ y = x * x
+ ax.plot(x, y) # plot y = x^2
+ run.log({"chart": fig})
+ ```
+
+ PR Curve
+
+ ```python
+ import wandb
+
+ with wandb.init() as run:
+ run.log({"pr": wandb.plot.pr_curve(y_test, y_probas, labels)})
+ ```
+
+ 3D Object
+
+ ```python
+ import wandb
+
+ with wandb.init() as run:
+ run.log(
+ {
+ "generated_samples": [
+ wandb.Object3D(open("sample.obj")),
+ wandb.Object3D(open("sample.gltf")),
+ wandb.Object3D(open("sample.glb")),
+ ]
+ }
+ )
+ ```
+
+ Raises:
+ wandb.Error: If called before `wandb.init()`.
+ ValueError: If invalid data is passed.
+ """
+ ...
+
+def save(
+ glob_str: str | os.PathLike,
+ base_path: str | os.PathLike | None = None,
+ policy: PolicyName = "live",
+) -> bool | list[str]:
+ """Sync one or more files to W&B.
+
+ Relative paths are relative to the current working directory.
+
+ A Unix glob, such as "myfiles/*", is expanded at the time `save` is
+ called regardless of the `policy`. In particular, new files are not
+ picked up automatically.
+
+ A `base_path` may be provided to control the directory structure of
+ uploaded files. It should be a prefix of `glob_str`, and the directory
+ structure beneath it is preserved.
+
+ When given an absolute path or glob and no `base_path`, one
+ directory level is preserved as in the example above.
+
+ Files are automatically deduplicated: calling `save()` multiple times
+ on the same file without modifications will not re-upload it.
+
+ Args:
+ glob_str: A relative or absolute path or Unix glob.
+ base_path: A path to use to infer a directory structure; see examples.
+ policy: One of `live`, `now`, or `end`.
+ - live: upload the file as it changes, overwriting the previous version
+ - now: upload the file once now
+ - end: upload file when the run ends
+
+ Returns:
+ Paths to the symlinks created for the matched files.
+
+ For historical reasons, this may return a boolean in legacy code.
+
+ ```python
+ import wandb
+
+ run = wandb.init()
+
+ run.save("these/are/myfiles/*")
+ # => Saves files in a "these/are/myfiles/" folder in the run.
+
+ run.save("these/are/myfiles/*", base_path="these")
+ # => Saves files in an "are/myfiles/" folder in the run.
+
+ run.save("/Users/username/Documents/run123/*.txt")
+ # => Saves files in a "run123/" folder in the run. See note below.
+
+ run.save("/Users/username/Documents/run123/*.txt", base_path="/Users")
+ # => Saves files in a "username/Documents/run123/" folder in the run.
+
+ run.save("files/*/saveme.txt")
+ # => Saves each "saveme.txt" file in an appropriate subdirectory
+ # of "files/".
+
+ # Explicitly finish the run since a context manager is not used.
+ run.finish()
+ ```
+ """
+ ...
+
+def sweep(
+ sweep: Union[dict, Callable],
+ entity: Optional[str] = None,
+ project: Optional[str] = None,
+ prior_runs: Optional[List[str]] = None,
+) -> str:
+ """Initialize a hyperparameter sweep.
+
+ Search for hyperparameters that optimizes a cost function
+ of a machine learning model by testing various combinations.
+
+ Make note the unique identifier, `sweep_id`, that is returned.
+ At a later step provide the `sweep_id` to a sweep agent.
+
+ See [Sweep configuration structure](https://docs.wandb.ai/guides/sweeps/define-sweep-configuration)
+ for information on how to define your sweep.
+
+ Args:
+ sweep: The configuration of a hyperparameter search.
+ (or configuration generator).
+ If you provide a callable, ensure that the callable does
+ not take arguments and that it returns a dictionary that
+ conforms to the W&B sweep config spec.
+ entity: The username or team name where you want to send W&B
+ runs created by the sweep to. Ensure that the entity you
+ specify already exists. If you don't specify an entity,
+ the run will be sent to your default entity,
+ which is usually your username.
+ project: The name of the project where W&B runs created from
+ the sweep are sent to. If the project is not specified, the
+ run is sent to a project labeled 'Uncategorized'.
+ prior_runs: The run IDs of existing runs to add to this sweep.
+
+ Returns:
+ str: A unique identifier for the sweep.
+ """
+ ...
+
+def controller(
+ sweep_id_or_config: Optional[Union[str, Dict]] = None,
+ entity: Optional[str] = None,
+ project: Optional[str] = None,
+) -> _WandbController:
+ """Public sweep controller constructor.
+
+ Examples:
+ ```python
+ import wandb
+
+ tuner = wandb.controller(...)
+ print(tuner.sweep_config)
+ print(tuner.sweep_id)
+ tuner.configure_search(...)
+ tuner.configure_stopping(...)
+ ```
+ """
+ ...
+
+def agent(
+ sweep_id: str,
+ function: Optional[Callable] = None,
+ entity: Optional[str] = None,
+ project: Optional[str] = None,
+ count: Optional[int] = None,
+) -> None:
+ """Start one or more sweep agents.
+
+ The sweep agent uses the `sweep_id` to know which sweep it
+ is a part of, what function to execute, and (optionally) how
+ many agents to run.
+
+ Args:
+ sweep_id: The unique identifier for a sweep. A sweep ID
+ is generated by W&B CLI or Python SDK.
+ function: A function to call instead of the "program"
+ specified in the sweep config.
+ entity: The username or team name where you want to send W&B
+ runs created by the sweep to. Ensure that the entity you
+ specify already exists. If you don't specify an entity,
+ the run will be sent to your default entity,
+ which is usually your username.
+ project: The name of the project where W&B runs created from
+ the sweep are sent to. If the project is not specified, the
+ run is sent to a project labeled "Uncategorized".
+ count: The number of sweep config trials to try.
+ """
+ ...
+
+def define_metric(
+ name: str,
+ step_metric: str | wandb_metric.Metric | None = None,
+ step_sync: bool | None = None,
+ hidden: bool | None = None,
+ summary: str | None = None,
+ goal: str | None = None,
+ overwrite: bool | None = None,
+) -> wandb_metric.Metric:
+ """Customize metrics logged with `wandb.Run.log()`.
+
+ Args:
+ name: The name of the metric to customize.
+ step_metric: The name of another metric to serve as the X-axis
+ for this metric in automatically generated charts.
+ step_sync: Automatically insert the last value of step_metric into
+ `wandb.Run.log()` if it is not provided explicitly. Defaults to True
+ if step_metric is specified.
+ hidden: Hide this metric from automatic plots.
+ summary: Specify aggregate metrics added to summary.
+ Supported aggregations include "min", "max", "mean", "last",
+ "first", "best", "copy" and "none". "none" prevents a summary
+ from being generated. "best" is used together with the goal
+ parameter, "best" is deprecated and should not be used, use
+ "min" or "max" instead. "copy" is deprecated and should not be
+ used.
+ goal: Specify how to interpret the "best" summary type.
+ Supported options are "minimize" and "maximize". "goal" is
+ deprecated and should not be used, use "min" or "max" instead.
+ overwrite: If false, then this call is merged with previous
+ `define_metric` calls for the same metric by using their
+ values for any unspecified parameters. If true, then
+ unspecified parameters overwrite values specified by
+ previous calls.
+
+ Returns:
+ An object that represents this call but can otherwise be discarded.
+ """
+ ...
+
+def log_artifact(
+ artifact_or_path: Artifact | StrPath,
+ name: str | None = None,
+ type: str | None = None,
+ aliases: list[str] | None = None,
+ tags: list[str] | None = None,
+) -> Artifact:
+ """Declare an artifact as an output of a run.
+
+ Args:
+ artifact_or_path: (str or Artifact) A path to the contents of this artifact,
+ can be in the following forms:
+ - `/local/directory`
+ - `/local/directory/file.txt`
+ - `s3://bucket/path`
+ You can also pass an Artifact object created by calling
+ `wandb.Artifact`.
+ name: (str, optional) An artifact name. Valid names can be in the following forms:
+ - name:version
+ - name:alias
+ - digest
+ This will default to the basename of the path prepended with the current
+ run id if not specified.
+ type: (str) The type of artifact to log, examples include `dataset`, `model`
+ aliases: (list, optional) Aliases to apply to this artifact,
+ defaults to `["latest"]`
+ tags: (list, optional) Tags to apply to this artifact, if any.
+
+ Returns:
+ An `Artifact` object.
+ """
+ ...
+
+def use_artifact(
+ artifact_or_name: str | Artifact,
+ type: str | None = None,
+ aliases: list[str] | None = None,
+ use_as: str | None = None,
+) -> Artifact:
+ """Declare an artifact as an input to a run.
+
+ Call `download` or `file` on the returned object to get the contents locally.
+
+ Args:
+ artifact_or_name: The name of the artifact to use. May be prefixed
+ with the name of the project the artifact was logged to
+ ("" or "/"). If no
+ entity is specified in the name, the Run or API setting's entity is used.
+ Valid names can be in the following forms
+ - name:version
+ - name:alias
+ type: The type of artifact to use.
+ aliases: Aliases to apply to this artifact
+ use_as: This argument is deprecated and does nothing.
+
+ Returns:
+ An `Artifact` object.
+
+ Examples:
+ ```python
+ import wandb
+
+ run = wandb.init(project="")
+
+ # Use an artifact by name and alias
+ artifact_a = run.use_artifact(artifact_or_name=":")
+
+ # Use an artifact by name and version
+ artifact_b = run.use_artifact(artifact_or_name=":v")
+
+ # Use an artifact by entity/project/name:alias
+ artifact_c = run.use_artifact(artifact_or_name="//:")
+
+ # Use an artifact by entity/project/name:version
+ artifact_d = run.use_artifact(
+ artifact_or_name="//:v"
+ )
+
+ # Explicitly finish the run since a context manager is not used.
+ run.finish()
+ ```
+ """
+ ...
+
+def log_model(
+ path: StrPath,
+ name: str | None = None,
+ aliases: list[str] | None = None,
+) -> None:
+ """Logs a model artifact containing the contents inside the 'path' to a run and marks it as an output to this run.
+
+ The name of model artifact can only contain alphanumeric characters,
+ underscores, and hyphens.
+
+ Args:
+ path: (str) A path to the contents of this model,
+ can be in the following forms:
+ - `/local/directory`
+ - `/local/directory/file.txt`
+ - `s3://bucket/path`
+ name: A name to assign to the model artifact that
+ the file contents will be added to. This will default to the
+ basename of the path prepended with the current run id if
+ not specified.
+ aliases: Aliases to apply to the created model artifact,
+ defaults to `["latest"]`
+
+ Raises:
+ ValueError: If name has invalid special characters.
+
+ Returns:
+ None
+ """
+ ...
+
+def use_model(name: str) -> FilePathStr:
+ """Download the files logged in a model artifact 'name'.
+
+ Args:
+ name: A model artifact name. 'name' must match the name of an existing logged
+ model artifact. May be prefixed with `entity/project/`. Valid names
+ can be in the following forms
+ - model_artifact_name:version
+ - model_artifact_name:alias
+
+ Returns:
+ path (str): Path to downloaded model artifact file(s).
+
+ Raises:
+ AssertionError: If model artifact 'name' is of a type that does
+ not contain the substring 'model'.
+ """
+ ...
+
+def link_model(
+ path: StrPath,
+ registered_model_name: str,
+ name: str | None = None,
+ aliases: list[str] | None = None,
+) -> Artifact | None:
+ """Log a model artifact version and link it to a registered model in the model registry.
+
+ Linked model versions are visible in the UI for the specified registered model.
+
+ This method will:
+ - Check if 'name' model artifact has been logged. If so, use the artifact version that matches the files
+ located at 'path' or log a new version. Otherwise log files under 'path' as a new model artifact, 'name'
+ of type 'model'.
+ - Check if registered model with name 'registered_model_name' exists in the 'model-registry' project.
+ If not, create a new registered model with name 'registered_model_name'.
+ - Link version of model artifact 'name' to registered model, 'registered_model_name'.
+ - Attach aliases from 'aliases' list to the newly linked model artifact version.
+
+ Args:
+ path: (str) A path to the contents of this model, can be in the
+ following forms:
+ - `/local/directory`
+ - `/local/directory/file.txt`
+ - `s3://bucket/path`
+ registered_model_name: The name of the registered model that the
+ model is to be linked to. A registered model is a collection of
+ model versions linked to the model registry, typically
+ representing a team's specific ML Task. The entity that this
+ registered model belongs to will be derived from the run.
+ name: The name of the model artifact that files in 'path' will be
+ logged to. This will default to the basename of the path
+ prepended with the current run id if not specified.
+ aliases: Aliases that will only be applied on this linked artifact
+ inside the registered model. The alias "latest" will always be
+ applied to the latest version of an artifact that is linked.
+
+ Raises:
+ AssertionError: If registered_model_name is a path or
+ if model artifact 'name' is of a type that does not contain
+ the substring 'model'.
+ ValueError: If name has invalid special characters.
+
+ Returns:
+ The linked artifact if linking was successful, otherwise `None`.
+ """
+ ...
+
+def plot_table(
+ vega_spec_name: str,
+ data_table: wandb.Table,
+ fields: dict[str, Any],
+ string_fields: dict[str, Any] | None = None,
+ split_table: bool = False,
+) -> CustomChart:
+ """Creates a custom charts using a Vega-Lite specification and a `wandb.Table`.
+
+ This function creates a custom chart based on a Vega-Lite specification and
+ a data table represented by a `wandb.Table` object. The specification needs
+ to be predefined and stored in the W&B backend. The function returns a custom
+ chart object that can be logged to W&B using `wandb.Run.log()`.
+
+ Args:
+ vega_spec_name: The name or identifier of the Vega-Lite spec
+ that defines the visualization structure.
+ data_table: A `wandb.Table` object containing the data to be
+ visualized.
+ fields: A mapping between the fields in the Vega-Lite spec and the
+ corresponding columns in the data table to be visualized.
+ string_fields: A dictionary for providing values for any string constants
+ required by the custom visualization.
+ split_table: Whether the table should be split into a separate section
+ in the W&B UI. If `True`, the table will be displayed in a section named
+ "Custom Chart Tables". Default is `False`.
+
+ Returns:
+ CustomChart: A custom chart object that can be logged to W&B. To log the
+ chart, pass the chart object as argument to `wandb.Run.log()`.
+
+ Raises:
+ wandb.Error: If `data_table` is not a `wandb.Table` object.
+
+ Example:
+ ```python
+ # Create a custom chart using a Vega-Lite spec and the data table.
+ import wandb
+
+ data = [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]]
+ table = wandb.Table(data=data, columns=["x", "y"])
+ fields = {"x": "x", "y": "y", "title": "MY TITLE"}
+
+ with wandb.init() as run:
+ # Training code goes here
+
+ # Create a custom title with `string_fields`.
+ my_custom_chart = wandb.plot_table(
+ vega_spec_name="wandb/line/v0",
+ data_table=table,
+ fields=fields,
+ string_fields={"title": "Title"},
+ )
+
+ run.log({"custom_chart": my_custom_chart})
+ ```
+ """
+ ...
+
+def watch(
+ models: torch.nn.Module | Sequence[torch.nn.Module],
+ criterion: torch.F | None = None,
+ log: Literal["gradients", "parameters", "all"] | None = "gradients",
+ log_freq: int = 1000,
+ idx: int | None = None,
+ log_graph: bool = False,
+) -> None:
+ """Hook into given PyTorch model to monitor gradients and the model's computational graph.
+
+ This function can track parameters, gradients, or both during training.
+
+ Args:
+ models: A single model or a sequence of models to be monitored.
+ criterion: The loss function being optimized (optional).
+ log: Specifies whether to log "gradients", "parameters", or "all".
+ Set to None to disable logging. (default="gradients").
+ log_freq: Frequency (in batches) to log gradients and parameters. (default=1000)
+ idx: Index used when tracking multiple models with `wandb.watch`. (default=None)
+ log_graph: Whether to log the model's computational graph. (default=False)
+
+ Raises:
+ ValueError:
+ If `wandb.init()` has not been called or if any of the models are not instances
+ of `torch.nn.Module`.
+ """
+ ...
+
+def unwatch(
+ models: torch.nn.Module | Sequence[torch.nn.Module] | None = None,
+) -> None:
+ """Remove pytorch model topology, gradient and parameter hooks.
+
+ Args:
+ models: Optional list of pytorch models that have had watch called on them.
+ """
+ ...
+
+def restore(
+ name: str,
+ run_path: str | None = None,
+ replace: bool = False,
+ root: str | None = None,
+) -> None | TextIO:
+ """Download the specified file from cloud storage.
+
+ File is placed into the current directory or run directory.
+ By default, will only download the file if it doesn't already exist.
+
+ Args:
+ name: The name of the file.
+ run_path: Optional path to a run to pull files from, i.e. `username/project_name/run_id`
+ if wandb.init has not been called, this is required.
+ replace: Whether to download the file even if it already exists locally
+ root: The directory to download the file to. Defaults to the current
+ directory or the run directory if wandb.init was called.
+
+ Returns:
+ None if it can't find the file, otherwise a file object open for reading.
+
+ Raises:
+ CommError: If W&B can't connect to the W&B backend.
+ ValueError: If the file is not found or can't find run_path.
+ """
+ ...
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/__main__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e32b1ef386cb475c83b09fb527a9621a7370847a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/__main__.py
@@ -0,0 +1,3 @@
+from wandb.cli import cli
+
+cli.cli(prog_name="python -m wandb")
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_analytics.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_analytics.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff102fffde9f805b00c8c55d663159989d40f455
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_analytics.py
@@ -0,0 +1,65 @@
+from __future__ import annotations
+
+from contextvars import ContextVar
+from dataclasses import dataclass, field
+from functools import wraps
+from typing import Callable, Final, TypeVar
+from uuid import UUID, uuid4
+
+from typing_extensions import ParamSpec
+
+from wandb._strutils import nameof
+
+P = ParamSpec("P")
+R = TypeVar("R")
+
+# Header keys for tracking the calling function
+X_WANDB_PYTHON_FUNC: Final[str] = "X-Wandb-Python-Func"
+X_WANDB_PYTHON_CALL_ID: Final[str] = "X-Wandb-Python-Call-Id"
+
+
+@dataclass(frozen=True)
+class TrackedFuncInfo:
+ func: str
+ """The fully qualified namespace of the tracked function."""
+
+ call_id: UUID = field(default_factory=uuid4)
+ """A unique identifier assigned to each invocation."""
+
+ def to_headers(self) -> dict[str, str]:
+ return {
+ X_WANDB_PYTHON_FUNC: self.func,
+ X_WANDB_PYTHON_CALL_ID: str(self.call_id),
+ }
+
+
+_current_func: ContextVar[TrackedFuncInfo] = ContextVar("_current_func")
+"""An internal, threadsafe context variable to hold the current function being tracked."""
+
+
+def tracked(func: Callable[P, R]) -> Callable[P, R]:
+ """A decorator to inject the calling function name into any GraphQL request headers.
+
+ If a tracked function calls another tracked function, only the outermost function in
+ the call stack will be tracked.
+ """
+ func_namespace = f"{func.__module__}.{nameof(func)}"
+
+ @wraps(func)
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
+ # Don't override the current tracked function if it's already set
+ if tracked_func():
+ return func(*args, **kwargs)
+
+ token = _current_func.set(TrackedFuncInfo(func=func_namespace))
+ try:
+ return func(*args, **kwargs)
+ finally:
+ _current_func.reset(token)
+
+ return wrapper
+
+
+def tracked_func() -> TrackedFuncInfo | None:
+ """Returns info on the current tracked function, if any, otherwise None."""
+ return _current_func.get(None)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_iterutils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_iterutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..0401cb4b8ba1302bc51ac0f7329f08eae516877d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_iterutils.py
@@ -0,0 +1,73 @@
+from __future__ import annotations
+
+from collections.abc import Hashable
+from typing import TYPE_CHECKING, Any, Iterable, TypeVar, Union, overload
+
+if TYPE_CHECKING:
+ T = TypeVar("T")
+ HashableT = TypeVar("HashableT", bound=Hashable)
+ ClassInfo = Union[type[T], tuple[type[T], ...]]
+
+
+@overload
+def always_list(obj: Iterable[T], base_type: ClassInfo = ...) -> list[T]: ...
+@overload
+def always_list(obj: T, base_type: ClassInfo = ...) -> list[T]: ...
+def always_list(obj: Any, base_type: Any = (str, bytes)) -> list[T]:
+ """Return a guaranteed list of objects from a single instance OR iterable of such objects.
+
+ By default, assume the returned list should have string-like elements (i.e. `str`/`bytes`).
+
+ Adapted from `more_itertools.always_iterable`, but simplified for internal use. See:
+ https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.always_iterable
+ """
+ return [obj] if isinstance(obj, base_type) else list(obj)
+
+
+def unique_list(iterable: Iterable[HashableT]) -> list[HashableT]:
+ """Return a deduplicated list of items from the given iterable, preserving order."""
+ # Trick for O(1) uniqueness check that maintains order
+ return list(dict.fromkeys(iterable))
+
+
+def one(
+ iterable: Iterable[T],
+ too_short: type[Exception] | Exception | None = None,
+ too_long: type[Exception] | Exception | None = None,
+) -> T:
+ """Return the only item in the iterable.
+
+ Note:
+ This is intended **only** as an internal helper/convenience function,
+ and its implementation is directly adapted from `more_itertools.one`.
+ Users needing similar functionality are strongly encouraged to use
+ that library instead:
+ https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.one
+
+ Args:
+ iterable: The iterable to get the only item from.
+ too_short: Custom exception to raise if the iterable has no items.
+ too_long: Custom exception to raise if the iterable has multiple items.
+
+ Raises:
+ ValueError or `too_short`: If the iterable has no items.
+ ValueError or `too_long`: If the iterable has multiple items.
+ """
+ # For a general iterable, avoid inadvertently iterating through all values,
+ # which may be costly or impossible (e.g. if infinite). Only check that:
+
+ # ... the first item exists
+ it = iter(iterable)
+ try:
+ obj = next(it)
+ except StopIteration:
+ raise (too_short or ValueError("Expected 1 item in iterable, got 0")) from None
+
+ # ...the second item doesn't
+ try:
+ _ = next(it)
+ except StopIteration:
+ return obj
+ raise (
+ too_long or ValueError("Expected 1 item in iterable, got multiple")
+ ) from None
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_pydantic/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_pydantic/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f14b54312ab3afb51993532c1d077fdfc317dd2a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_pydantic/__init__.py
@@ -0,0 +1,30 @@
+"""Internal utilities for working with pydantic."""
+
+__all__ = [
+ "IS_PYDANTIC_V2",
+ "CompatBaseModel",
+ "JsonableModel",
+ "GQLBase",
+ "Typename",
+ "GQLId",
+ "AliasChoices",
+ "computed_field",
+ "field_validator",
+ "model_validator",
+ "pydantic_isinstance",
+ "to_camel",
+ "to_json",
+ "from_json",
+ "gql_typename",
+]
+
+from .base import CompatBaseModel, GQLBase, JsonableModel
+from .field_types import GQLId, Typename
+from .utils import IS_PYDANTIC_V2, from_json, gql_typename, pydantic_isinstance, to_json
+from .v1_compat import (
+ AliasChoices,
+ computed_field,
+ field_validator,
+ model_validator,
+ to_camel,
+)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_pydantic/base.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_pydantic/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..816ba3f6dbb0af7b93f04d726f42fa585d22def9
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_pydantic/base.py
@@ -0,0 +1,108 @@
+"""Base classes and other customizations for generated pydantic types."""
+
+from __future__ import annotations
+
+from abc import ABC
+from typing import TYPE_CHECKING, Any, Callable, ClassVar, Literal
+
+from pydantic import BaseModel, ConfigDict
+from typing_extensions import TypedDict, Unpack, override
+
+from .v1_compat import PydanticCompatMixin
+
+if TYPE_CHECKING:
+ from pydantic.main import IncEx
+
+
+class ModelDumpKwargs(TypedDict, total=False):
+ """Shared keyword arguments for `BaseModel.model_{dump,dump_json}`."""
+
+ include: IncEx | None
+ exclude: IncEx | None
+ context: dict[str, Any] | None
+ by_alias: bool | None
+ exclude_unset: bool
+ exclude_defaults: bool
+ exclude_none: bool
+ round_trip: bool
+ warnings: bool | Literal["none", "warn", "error"]
+ fallback: Callable[[Any], Any] | None
+ serialize_as_any: bool
+
+
+# ---------------------------------------------------------------------------
+# Base models and mixin classes.
+#
+# Extra info is provided for devs in inline comments, NOT docstrings. This
+# prevents it from showing up in generated docs for subclasses.
+
+
+# FOR INTERNAL USE ONLY: v1-compatible drop-in replacement for `pydantic.BaseModel`.
+# If pydantic v2 is detected, this is just `pydantic.BaseModel`.
+#
+# Deliberately inherits ALL default configuration from `pydantic.BaseModel`.
+class CompatBaseModel(PydanticCompatMixin, BaseModel):
+ __doc__ = None # Prevent subclasses from inheriting the BaseModel docstring
+
+
+class JsonableModel(CompatBaseModel, ABC):
+ # Base class with sensible default behavior for classes that need to convert to/from JSON.
+ #
+ # Automatically parse/serialize "raw" API data (e.g. automatically convert to/from camelCase keys):
+ # - `.model_{dump,dump_json}()` should return "JSON-ready" dicts or JSON strings
+ # - `.model_{validate,validate_json}()` should accept "JSON-ready" dicts or JSON strings
+ #
+ # Ensure round-trip serialization <-> deserialization between:
+ # - `model_dump()` <-> `model_validate()`
+ # - `model_dump_json()` <-> `model_validate_json()`
+ #
+ # These behaviors are useful for models that need to predictably handle e.g. GraphQL request/response data.
+
+ model_config = ConfigDict(
+ # ---------------------------------------------------------------------------
+ # Discouraged in v2.11+, deprecated in v3. Kept here for compatibility.
+ populate_by_name=True,
+ # ---------------------------------------------------------------------------
+ # Introduced in v2.11, ignored in earlier versions
+ validate_by_name=True,
+ validate_by_alias=True,
+ serialize_by_alias=True,
+ # ---------------------------------------------------------------------------
+ validate_assignment=True,
+ use_attribute_docstrings=True,
+ from_attributes=True,
+ )
+
+ # Custom defaults keyword args for `JsonableModel.model_{dump,dump_json}`:
+ # - by_alias: Convert keys to JSON-ready names and objects to JSON-ready dicts.
+ # - round_trip: Ensure round-trippable result
+ __DUMP_DEFAULTS: ClassVar[ModelDumpKwargs] = dict(by_alias=True, round_trip=True)
+
+ @override
+ def model_dump(
+ self,
+ *,
+ mode: Literal["json", "python"] | str = "json", # NOTE: changed default
+ **kwargs: Unpack[ModelDumpKwargs],
+ ) -> dict[str, Any]:
+ kwargs = {**self.__DUMP_DEFAULTS, **kwargs} # allows overrides, if needed
+ return super().model_dump(mode=mode, **kwargs)
+
+ @override
+ def model_dump_json(
+ self,
+ *,
+ indent: int | None = None,
+ **kwargs: Unpack[ModelDumpKwargs],
+ ) -> str:
+ kwargs = {**self.__DUMP_DEFAULTS, **kwargs} # allows overrides, if needed
+ return super().model_dump_json(indent=indent, **kwargs)
+
+
+# Base class for all GraphQL-generated types.
+class GQLBase(JsonableModel, ABC):
+ model_config = ConfigDict(
+ validate_default=True,
+ revalidate_instances="always",
+ protected_namespaces=(), # Some GraphQL fields may begin with "model_"
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_pydantic/field_types.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_pydantic/field_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..5cd06d11736cba84b61474544536784b469e9628
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_pydantic/field_types.py
@@ -0,0 +1,29 @@
+"""Reusable field types and annotations for pydantic fields."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, TypeVar
+
+from pydantic import Field, StrictStr
+from typing_extensions import Annotated
+
+from .utils import IS_PYDANTIC_V2
+
+T = TypeVar("T")
+
+
+#: GraphQL `__typename` fields
+Typename = Annotated[T, Field(repr=False, frozen=True, alias="__typename")]
+
+
+if IS_PYDANTIC_V2 or TYPE_CHECKING:
+ GQLId = Annotated[StrictStr, Field(repr=False, frozen=True)]
+
+else:
+ # FIXME: Find a way to fix this for pydantic v1, which doesn't like when
+ # `Field(...)` used in the field assignment AND `Annotated[...]`.
+ # This is a problem for codegen, which can currently output e.g.
+ #
+ # class MyModel(GQLBase):
+ # my_id: GQLId = Field(alias="myID")
+ GQLId = StrictStr # type: ignore[misc]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_pydantic/utils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_pydantic/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..0418c5e8b03da7eba5477fbde2d1f8e193986950
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_pydantic/utils.py
@@ -0,0 +1,80 @@
+"""Internal utilities for working with Pydantic types and data."""
+
+from __future__ import annotations
+
+import json
+import sys
+from contextlib import suppress
+from typing import Any, Type
+
+import pydantic
+from pydantic import BaseModel, ValidationError
+from typing_extensions import TypeAlias
+
+PYTHON_VERSION = sys.version_info
+
+pydantic_major, *_ = pydantic.VERSION.split(".")
+IS_PYDANTIC_V2: bool = int(pydantic_major) >= 2
+
+
+BaseModelType: TypeAlias = Type[BaseModel]
+
+
+def gql_typename(cls: type[BaseModel]) -> str:
+ """Get the GraphQL typename for a Pydantic model."""
+ if (field := cls.model_fields.get("typename__")) and (typename := field.default):
+ return typename
+ raise TypeError(f"Cannot extract GraphQL typename from: {cls.__qualname__!r}.")
+
+
+if IS_PYDANTIC_V2:
+ import pydantic_core # pydantic_core is only installed by pydantic v2
+
+ def from_json(s: str) -> Any:
+ """Quickly deserialize a JSON string to a Python object."""
+ return pydantic_core.from_json(s)
+
+ def to_json(v: Any) -> str:
+ """Quickly serialize a (possibly Pydantic) object to a JSON string."""
+ return pydantic_core.to_json(v, by_alias=True, round_trip=True).decode("utf-8")
+
+ def pydantic_isinstance(
+ v: Any, classinfo: BaseModelType | tuple[BaseModelType, ...]
+ ) -> bool:
+ """Return True if the object could be parsed into the given Pydantic type.
+
+ This is like a more lenient version of `isinstance()` for use with Pydantic.
+ In Pydantic v2, should be fast since the underlying implementation is in Rust,
+ and it may be preferable over `try:...except ValidationError:...`.
+
+ See: https://docs.pydantic.dev/latest/api/pydantic_core/#pydantic_core.SchemaValidator.isinstance_python
+ """
+ if isinstance(classinfo, tuple):
+ return any(
+ cls.__pydantic_validator__.isinstance_python(v) for cls in classinfo
+ )
+ cls = classinfo
+ return cls.__pydantic_validator__.isinstance_python(v)
+
+else:
+ # Pydantic v1 fallback implementations.
+ # These may be noticeably slower, but their primary goal is to ensure
+ # compatibility with Pydantic v1 so long as we need to support it.
+
+ from pydantic.json import pydantic_encoder # Only valid in pydantic v1
+
+ def from_json(s: str) -> Any:
+ return json.loads(s)
+
+ def to_json(v: Any) -> str:
+ return json.dumps(v, default=pydantic_encoder)
+
+ def pydantic_isinstance(
+ v: Any, classinfo: BaseModelType | tuple[BaseModelType, ...]
+ ) -> bool:
+ classes = classinfo if isinstance(classinfo, tuple) else (classinfo,)
+ for cls in classes:
+ with suppress(ValidationError):
+ cls.model_validate(v)
+ return True
+ return False
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_pydantic/v1_compat.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_pydantic/v1_compat.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ca9a11ae47777f47343c117c7e1f1d2e243dbd3
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_pydantic/v1_compat.py
@@ -0,0 +1,301 @@
+"""Provides partial support for compatibility with Pydantic v1."""
+
+from __future__ import annotations
+
+import json
+from functools import lru_cache
+from inspect import signature
+from operator import attrgetter
+from typing import TYPE_CHECKING, Any, Callable, ClassVar, Literal, overload
+
+import pydantic
+
+from .utils import IS_PYDANTIC_V2, to_json
+
+if TYPE_CHECKING:
+ from typing import Protocol
+
+ class V1Model(Protocol):
+ # ------------------------------------------------------------------------------
+ # NOTE: These aren't part of the original v1 BaseModel spec, but were added as
+ # internal helpers and are (re-)declared here to satisfy mypy checks.
+ @classmethod
+ def _dump_json_vals(cls, values: dict, by_alias: bool) -> dict: ...
+
+ # ------------------------------------------------------------------------------
+ # These methods are part of the original v1 BaseModel spec.
+
+ __config__: ClassVar[type]
+ __fields__: ClassVar[dict[str, Any]]
+ __fields_set__: set[str]
+
+ @classmethod
+ def update_forward_refs(cls, *args: Any, **kwargs: Any) -> None: ...
+ @classmethod
+ def construct(cls, *args: Any, **kwargs: Any) -> V1Model: ...
+ @classmethod
+ def parse_obj(cls, *args: Any, **kwargs: Any) -> V1Model: ...
+ @classmethod
+ def parse_raw(cls, *args: Any, **kwargs: Any) -> V1Model: ...
+
+ def dict(self, **kwargs: Any) -> dict[str, Any]: ...
+ def json(self, **kwargs: Any) -> str: ...
+ def copy(self, **kwargs: Any) -> V1Model: ...
+
+
+# Maps {v2 -> v1} model config keys that were renamed in v2.
+# See: https://docs.pydantic.dev/latest/migration/#changes-to-config
+_V1_CONFIG_KEYS = {
+ "populate_by_name": "allow_population_by_field_name",
+ "str_to_lower": "anystr_lower",
+ "str_strip_whitespace": "anystr_strip_whitespace",
+ "str_to_upper": "anystr_upper",
+ "ignored_types": "keep_untouched",
+ "str_max_length": "max_anystr_length",
+ "str_min_length": "min_anystr_length",
+ "from_attributes": "orm_mode",
+ "json_schema_extra": "schema_extra",
+ "validate_default": "validate_all",
+}
+
+
+def convert_v2_config(v2_config: dict[str, Any]) -> dict[str, Any]:
+ """Internal helper: Return a copy of the v2 ConfigDict with renamed v1 keys."""
+ return {
+ # Convert v2 config keys to v1 keys
+ **{_V1_CONFIG_KEYS.get(k, k): v for k, v in v2_config.items()},
+ # This is a v1-only config key. In v2, it no longer exists and is effectively always True.
+ "underscore_attrs_are_private": True,
+ }
+
+
+@lru_cache(maxsize=None) # Reduce repeat introspection via `signature()`
+def allowed_arg_names(func: Callable) -> set[str]:
+ """Internal helper: Return the names of args accepted by the given function."""
+ return set(signature(func).parameters)
+
+
+# Pydantic BaseModels are defined with a custom metaclass, but its namespace
+# has changed between pydantic versions.
+#
+# In v1, it can be imported as `from pydantic.main import ModelMetaclass`
+# In v2, it's defined in an internal module so we avoid directly importing it.
+PydanticModelMetaclass: type = type(pydantic.BaseModel)
+
+
+class V1MixinMetaclass(PydanticModelMetaclass):
+ def __new__(
+ cls,
+ name: str,
+ bases: tuple[type, ...],
+ namespace: dict[str, Any],
+ **kwargs: Any,
+ ):
+ # In the class definition, convert the model config, if any:
+ # class MyModel(BaseModel): # BEFORE (v2)
+ # model_config = ConfigDict(populate_by_name=True)
+ #
+ # class MyModel(BaseModel): # AFTER (v1)
+ # class Config:
+ # allow_population_by_field_name = True
+ if config_dict := namespace.pop("model_config", None):
+ namespace["Config"] = type("Config", (), convert_v2_config(config_dict))
+ return super().__new__(cls, name, bases, namespace, **kwargs)
+
+ @property
+ def model_fields(self) -> dict[str, Any]:
+ return self.__fields__ # type: ignore[deprecated]
+
+
+# Mixin to ensure compatibility of Pydantic models if Pydantic v1 is detected.
+# These are "best effort" implementations and cannot guarantee complete
+# compatibility in v1 environments.
+#
+# Whenever possible, users should strongly prefer upgrading to Pydantic v2 to
+# ensure full compatibility.
+class V1Mixin(metaclass=V1MixinMetaclass):
+ # Internal compat helpers
+ @classmethod
+ def _dump_json_vals(cls, values: dict[str, Any], by_alias: bool) -> dict[str, Any]:
+ """Reserialize values from `Json`-typed fields after dumping the model to dict."""
+ # Get the expected keys (after `.model_dump()`) for `Json`-typed fields.
+ # Note: In v1, `Json` fields have `ModelField.parse_json == True`
+ json_fields = (f for f in cls.__fields__.values() if f.parse_json) # type: ignore[deprecated]
+ get_key = attrgetter("alias" if by_alias else "name")
+ json_field_keys = set(map(get_key, json_fields))
+
+ return {
+ # Only serialize `Json` fields with non-null values.
+ k: to_json(v) if ((v is not None) and (k in json_field_keys)) else v
+ for k, v in values.items()
+ }
+
+ # ------------------------------------------------------------------------------
+ @classmethod
+ def __try_update_forward_refs__(cls: type[V1Model], **localns: Any) -> None:
+ if hasattr(sup := super(), "__try_update_forward_refs__"):
+ sup.__try_update_forward_refs__(**localns)
+
+ @classmethod
+ def model_rebuild(cls, *args: Any, **kwargs: Any) -> None:
+ return cls.update_forward_refs(*args, **kwargs)
+
+ @classmethod
+ def model_construct(cls, *args: Any, **kwargs: Any) -> V1Model:
+ return cls.construct(*args, **kwargs)
+
+ @classmethod
+ def model_validate(cls, *args: Any, **kwargs: Any) -> V1Model:
+ return cls.parse_obj(*args, **kwargs)
+
+ @classmethod
+ def model_validate_json(cls, *args: Any, **kwargs: Any) -> V1Model:
+ return cls.parse_raw(*args, **kwargs)
+
+ def model_dump(self: V1Model, **kwargs: Any) -> dict[str, Any]:
+ # Pass only kwargs that are allowed in the V1 method.
+ allowed_keys = allowed_arg_names(self.dict) & kwargs.keys()
+ dict_ = self.dict(**{k: kwargs[k] for k in allowed_keys})
+
+ # Ugly hack: Try to serialize `Json` fields correctly when `round_trip=True` in pydantic v1
+ if kwargs.get("round_trip", False):
+ by_alias: bool = kwargs.get("by_alias", False)
+ return self._dump_json_vals(dict_, by_alias=by_alias)
+
+ return dict_
+
+ def model_dump_json(self: V1Model, **kwargs: Any) -> str:
+ # Pass only kwargs that are allowed in the V1 method.
+ allowed_keys = allowed_arg_names(self.json) & kwargs.keys()
+ json_ = self.json(**{k: kwargs[k] for k in allowed_keys})
+
+ # Ugly hack: Try to serialize `Json` fields correctly when `round_trip=True` in pydantic v1
+ if kwargs.get("round_trip", False):
+ by_alias: bool = kwargs.get("by_alias", False)
+ dict_ = json.loads(json_)
+ return json.dumps(self._dump_json_vals(dict_, by_alias=by_alias))
+
+ return json_
+
+ def model_copy(self: V1Model, **kwargs: Any) -> V1Model:
+ # Pass only kwargs that are allowed in the V1 method.
+ allowed_keys = allowed_arg_names(self.copy) & kwargs.keys()
+ return self.copy(**{k: kwargs[k] for k in allowed_keys})
+
+ @property
+ def model_fields_set(self: V1Model) -> set[str]:
+ return self.__fields_set__
+
+
+# Placeholder. Pydantic v2 is already compatible with itself, so no need for extra mixins.
+class V2Mixin:
+ pass
+
+
+# Pick the mixin type based on the detected Pydantic version.
+PydanticCompatMixin: type = V2Mixin if IS_PYDANTIC_V2 else V1Mixin
+
+
+# ----------------------------------------------------------------------------
+# Decorators and other pydantic helpers
+# ----------------------------------------------------------------------------
+if IS_PYDANTIC_V2:
+ from pydantic import alias_generators
+
+ # https://docs.pydantic.dev/latest/api/config/#pydantic.alias_generators.to_camel
+ to_camel = alias_generators.to_camel # e.g. "foo_bar" -> "fooBar"
+
+ # https://docs.pydantic.dev/latest/api/functional_validators/#pydantic.functional_validators.field_validator
+ field_validator = pydantic.field_validator
+
+ # https://docs.pydantic.dev/latest/api/functional_validators/#pydantic.functional_validators.model_validator
+ model_validator = pydantic.model_validator
+
+ # https://docs.pydantic.dev/latest/api/fields/#pydantic.fields.computed_field
+ computed_field = pydantic.computed_field
+
+ # https://docs.pydantic.dev/latest/api/aliases/#pydantic.aliases.AliasChoices
+ AliasChoices = pydantic.AliasChoices
+
+else:
+ from pydantic.utils import to_lower_camel
+
+ V2ValidatorMode = Literal["before", "after", "wrap", "plain"]
+
+ # NOTE:
+ # - `to_lower_camel` in v1 is the equivalent of `to_camel` in v2 (i.e. to lowerCamelCase)
+ # - `to_camel` in v1 is the equivalent of `to_pascal` in v2 (i.e. to UpperCamelCase)
+ to_camel = to_lower_camel
+
+ # Lets us use `@field_validator` from v2, while calling `@validator` from v1 if needed.
+ def field_validator(
+ *fields: str,
+ mode: V2ValidatorMode = "after",
+ check_fields: bool | None = None,
+ **_: Any,
+ ) -> Callable:
+ return pydantic.validator( # type: ignore[deprecated]
+ *fields,
+ pre=(mode == "before"),
+ always=True,
+ check_fields=bool(check_fields),
+ allow_reuse=True,
+ )
+
+ # Lets us use `@model_validator` from v2, while calling `@root_validator` from v1 if needed.
+ def model_validator(*, mode: V2ValidatorMode, **_: Any) -> Callable:
+ if mode == "after":
+
+ def _decorator(v2_method: Callable) -> Any:
+ # Patch the behavior for `@model_validator(mode="after")` in v1.
+ #
+ # This is necessarily complicated because:
+ # - `@model_validator(mode="after")` always decorates an instance method in v2,
+ # i.e. the decorated function has `self` as the first arg.
+ # - `@root_validator(pre=False)` always decorates a classmethod in v1,
+ # i.e. the decorated function has `cls` as the first arg.
+
+ def v1_method(
+ cls: type[V1Model], values: dict[str, Any]
+ ) -> dict[str, Any]:
+ # values should already be validated in an "after" validator, so use `construct()`
+ # to instantiate without (re-)validating.
+ v_self = v2_method(cls.construct(**values))
+
+ # Pydantic v1 expects the validator to return a dict of {field_name -> value}
+ return {f: getattr(v_self, f) for f in v_self.__fields__}
+
+ return pydantic.root_validator(pre=False, allow_reuse=True)( # type: ignore[call-overload]
+ classmethod(v1_method)
+ )
+
+ return _decorator
+ else:
+ return pydantic.root_validator(pre=(mode == "before"), allow_reuse=True) # type: ignore[call-overload]
+
+ @overload # type: ignore[no-redef]
+ def computed_field(func: Callable | property, /) -> property: ...
+ @overload
+ def computed_field(
+ func: None, /, **_: Any
+ ) -> Callable[[Callable | property], property]: ...
+
+ def computed_field(
+ func: Callable | property | None = None, /, **_: Any
+ ) -> property | Callable[[Callable | property], property]:
+ """Compatibility wrapper for Pydantic v2's `computed_field` in v1."""
+
+ def always_property(f: Callable | property) -> property:
+ # Convert the method to a property only if needed
+ return f if isinstance(f, property) else property(f)
+
+ # Handle both decorator styles
+ return always_property if (func is None) else always_property(func)
+
+ class AliasChoices: # type: ignore [no-redef]
+ """Placeholder class for Pydantic v2's AliasChoices for partial v1 compatibility."""
+
+ aliases: list[str]
+
+ def __init__(self, *aliases: str):
+ self.aliases = list(aliases)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_strutils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_strutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4e9b97d4b4f6585b0dd79a212d4b52988051c4c
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/_strutils.py
@@ -0,0 +1,40 @@
+from __future__ import annotations
+
+from typing import Any
+
+
+def removeprefix(s: str, prefix: str) -> str:
+ """Removes a prefix from a string.
+
+ This roughly backports the built-in `str.removeprefix` function from Python 3.9+.
+ Once Python 3.8 support is dropped, just replace this with `str.removeprefix`.
+ """
+ return s[len(prefix) :] if s.startswith(prefix) else s
+
+
+def removesuffix(s: str, suffix: str) -> str:
+ """Removes a suffix from a string.
+
+ This roughly backports the built-in `str.removesuffix` function from Python 3.9+.
+ Once Python 3.8 support is dropped, just replace this with `str.removesuffix`.
+ """
+ return s[: -len(suffix)] if s.endswith(suffix) else s
+
+
+def ensureprefix(s: str, prefix: str) -> str:
+ """Ensures the string has the given prefix prepended."""
+ return s if s.startswith(prefix) else f"{prefix}{s}"
+
+
+def ensuresuffix(s: str, suffix: str) -> str:
+ """Ensures the string has the given suffix appended."""
+ return s if s.endswith(suffix) else f"{s}{suffix}"
+
+
+def nameof(obj: Any, full: bool = True) -> str:
+ """Internal convenience helper that returns the object's `__name__` or `__qualname__`.
+
+ If `full` is True, attempt to return the object's `__qualname__` attribute,
+ falling back on the `__name__` attribute.
+ """
+ return getattr(obj, "__qualname__", obj.__name__) if full else obj.__name__
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/agents/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/agents/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/agents/pyagent.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/agents/pyagent.py
new file mode 100644
index 0000000000000000000000000000000000000000..f9483f6a0b20c2dd4703a3fa7df45fc5eeb6310d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/agents/pyagent.py
@@ -0,0 +1,386 @@
+"""Agent - Agent object.
+
+Manage wandb agent.
+
+"""
+
+import ctypes
+import logging
+import os
+import queue
+import socket
+import sys
+import threading
+import time
+import traceback
+
+import wandb
+from wandb.apis import InternalApi
+from wandb.sdk.launch.sweeps import utils as sweep_utils
+
+logger = logging.getLogger(__name__)
+
+
+def _terminate_thread(thread):
+ if not thread.is_alive():
+ return
+ if hasattr(thread, "_terminated"):
+ return
+ thread._terminated = True
+ tid = getattr(thread, "_thread_id", None)
+ if tid is None:
+ for k, v in threading._active.items():
+ if v is thread:
+ tid = k
+ if tid is None:
+ # This should never happen
+ return
+ logger.debug(f"Terminating thread: {tid}")
+ res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
+ ctypes.c_long(tid), ctypes.py_object(Exception)
+ )
+ if res == 0:
+ # This should never happen
+ return
+ elif res != 1:
+ # Revert
+ logger.debug(f"Termination failed for thread {tid}")
+ ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None)
+
+
+class Job:
+ def __init__(self, command):
+ self.command = command
+ job_type = command.get("type")
+ self.type = job_type
+ self.run_id = command.get("run_id")
+ self.config = command.get("args")
+
+ def __repr__(self):
+ if self.type == "run":
+ return f"Job({self.run_id},{self.config})"
+ elif self.type == "stop":
+ return f"stop({self.run_id})"
+ else:
+ return "exit"
+
+
+class RunStatus:
+ QUEUED = "QUEUED"
+ RUNNING = "RUNNING"
+ STOPPED = "STOPPED"
+ ERRORED = "ERRORED"
+ DONE = "DONE"
+
+
+class Agent:
+ FLAPPING_MAX_SECONDS = 60
+ FLAPPING_MAX_FAILURES = 3
+ MAX_INITIAL_FAILURES = 5
+
+ def __init__(
+ self, sweep_id=None, project=None, entity=None, function=None, count=None
+ ):
+ self._sweep_path = sweep_id
+ self._sweep_id = None
+ self._project = project
+ self._entity = entity
+ self._function = function
+ self._count = count
+ # glob_config = os.path.expanduser('~/.config/wandb/settings')
+ # loc_config = 'wandb/settings'
+ # files = (glob_config, loc_config)
+ self._api = InternalApi()
+ self._agent_id = None
+ self._max_initial_failures = wandb.env.get_agent_max_initial_failures(
+ self.MAX_INITIAL_FAILURES
+ )
+ # if the directory to log to is not set, set it
+ if os.environ.get(wandb.env.DIR) is None:
+ os.environ[wandb.env.DIR] = os.path.abspath(os.getcwd())
+
+ def _init(self):
+ # These are not in constructor so that Agent instance can be rerun
+ self._run_threads = {}
+ self._run_status = {}
+ self._queue = queue.Queue()
+ self._exit_flag = False
+ self._exceptions = {}
+ self._start_time = time.time()
+
+ def _register(self):
+ logger.debug("Agent._register()")
+ agent = self._api.register_agent(socket.gethostname(), sweep_id=self._sweep_id)
+ self._agent_id = agent["id"]
+ logger.debug(f"agent_id = {self._agent_id}")
+
+ def _setup(self):
+ logger.debug("Agent._setup()")
+ self._init()
+ parts = dict(entity=self._entity, project=self._project, name=self._sweep_path)
+ err = sweep_utils.parse_sweep_id(parts)
+ if err:
+ wandb.termerror(err)
+ return
+ entity = parts.get("entity") or self._entity
+ project = parts.get("project") or self._project
+ sweep_id = parts.get("name") or self._sweep_id
+ if sweep_id:
+ os.environ[wandb.env.SWEEP_ID] = sweep_id
+ if entity:
+ wandb.env.set_entity(entity)
+ if project:
+ wandb.env.set_project(project)
+ if sweep_id:
+ self._sweep_id = sweep_id
+ self._register()
+
+ def _stop_run(self, run_id):
+ logger.debug(f"Stopping run {run_id}.")
+ self._run_status[run_id] = RunStatus.STOPPED
+ thread = self._run_threads.get(run_id)
+ if thread:
+ _terminate_thread(thread)
+
+ def _stop_all_runs(self):
+ logger.debug("Stopping all runs.")
+ for run in list(self._run_threads.keys()):
+ self._stop_run(run)
+
+ def _exit(self):
+ self._stop_all_runs()
+ self._exit_flag = True
+ # _terminate_thread(self._main_thread)
+
+ def _heartbeat(self):
+ while True:
+ if self._exit_flag:
+ return
+ # if not self._main_thread.is_alive():
+ # return
+ run_status = {
+ run: True
+ for run, status in self._run_status.items()
+ if status in (RunStatus.QUEUED, RunStatus.RUNNING)
+ }
+ commands = self._api.agent_heartbeat(self._agent_id, {}, run_status)
+ if commands:
+ job = Job(commands[0])
+ logger.debug(f"Job received: {job}")
+ if job.type in ["run", "resume"]:
+ self._queue.put(job)
+ self._run_status[job.run_id] = RunStatus.QUEUED
+ elif job.type == "stop":
+ self._stop_run(job.run_id)
+ elif job.type == "exit":
+ self._exit()
+ return
+ time.sleep(5)
+
+ def _run_jobs_from_queue(self):
+ global _INSTANCES
+ _INSTANCES += 1
+ try:
+ waiting = False
+ count = 0
+ while True:
+ if self._exit_flag:
+ return
+ try:
+ try:
+ job = self._queue.get(timeout=5)
+ if self._exit_flag:
+ logger.debug("Exiting main loop due to exit flag.")
+ wandb.termlog("Sweep Agent: Exiting.")
+ return
+ except queue.Empty:
+ if not waiting:
+ logger.debug("Paused.")
+ wandb.termlog("Sweep Agent: Waiting for job.")
+ waiting = True
+ time.sleep(5)
+ if self._exit_flag:
+ logger.debug("Exiting main loop due to exit flag.")
+ wandb.termlog("Sweep Agent: Exiting.")
+ return
+ continue
+ if waiting:
+ logger.debug("Resumed.")
+ wandb.termlog("Job received.")
+ waiting = False
+ count += 1
+ run_id = job.run_id
+ if self._run_status[run_id] == RunStatus.STOPPED:
+ continue
+ logger.debug(f"Spawning new thread for run {run_id}.")
+ thread = threading.Thread(target=self._run_job, args=(job,))
+ self._run_threads[run_id] = thread
+ thread.start()
+ self._run_status[run_id] = RunStatus.RUNNING
+ thread.join()
+ logger.debug(f"Thread joined for run {run_id}.")
+ if self._run_status[run_id] == RunStatus.RUNNING:
+ self._run_status[run_id] = RunStatus.DONE
+ elif self._run_status[run_id] == RunStatus.ERRORED:
+ exc = self._exceptions[run_id]
+ # Extract to reduce a decision point to avoid ruff c901
+ log_str, term_str = _get_exception_logger_and_term_strs(exc)
+ logger.error(f"Run {run_id} errored:\n{log_str}")
+ wandb.termerror(f"Run {run_id} errored:{term_str}")
+ if os.getenv(wandb.env.AGENT_DISABLE_FLAPPING) == "true":
+ self._exit_flag = True
+ return
+ elif (
+ time.time() - self._start_time < self.FLAPPING_MAX_SECONDS
+ ) and (len(self._exceptions) >= self.FLAPPING_MAX_FAILURES):
+ msg = f"Detected {self.FLAPPING_MAX_FAILURES} failed runs in the first {self.FLAPPING_MAX_SECONDS} seconds, killing sweep."
+ logger.error(msg)
+ wandb.termerror(msg)
+ wandb.termlog(
+ "To disable this check set WANDB_AGENT_DISABLE_FLAPPING=true"
+ )
+ self._exit_flag = True
+ return
+ if (
+ self._max_initial_failures < len(self._exceptions)
+ and len(self._exceptions) >= count
+ ):
+ msg = f"Detected {self._max_initial_failures} failed runs in a row at start, killing sweep."
+ logger.error(msg)
+ wandb.termerror(msg)
+ wandb.termlog(
+ "To change this value set WANDB_AGENT_MAX_INITIAL_FAILURES=val"
+ )
+ self._exit_flag = True
+ return
+ if self._count and self._count == count:
+ logger.debug("Exiting main loop because max count reached.")
+ self._exit_flag = True
+ return
+ except KeyboardInterrupt:
+ logger.debug("Ctrl + C detected. Stopping sweep.")
+ wandb.termlog("Ctrl + C detected. Stopping sweep.")
+ self._exit()
+ return
+ except Exception:
+ if self._exit_flag:
+ logger.debug("Exiting main loop due to exit flag.")
+ wandb.termlog("Sweep Agent: Killed.")
+ return
+ else:
+ raise
+ finally:
+ _INSTANCES -= 1
+
+ def _run_job(self, job):
+ try:
+ run_id = job.run_id
+
+ config_file = os.path.join(
+ "wandb", "sweep-" + self._sweep_id, "config-" + run_id + ".yaml"
+ )
+ os.environ[wandb.env.RUN_ID] = run_id
+ base_dir = os.environ.get(wandb.env.DIR, "")
+ sweep_param_path = os.path.join(base_dir, config_file)
+ os.environ[wandb.env.SWEEP_PARAM_PATH] = sweep_param_path
+ wandb.wandb_lib.config_util.save_config_file_from_dict(
+ sweep_param_path, job.config
+ )
+ os.environ[wandb.env.SWEEP_ID] = self._sweep_id
+ wandb.teardown()
+
+ wandb.termlog(f"Agent Starting Run: {run_id} with config:")
+ for k, v in job.config.items():
+ wandb.termlog("\t{}: {}".format(k, v["value"]))
+
+ try:
+ self._function()
+ except KeyboardInterrupt:
+ raise
+ except Exception as e:
+ # Log the run's exceptions directly to stderr to match CLI case, and wrap so we
+ # can identify it as coming from the job later later. This will get automatically
+ # logged by console_capture.py. Exception handler below will also handle exceptions
+ # in setup code.
+ exc_repr = _format_exception_traceback(e)
+ print(exc_repr, file=sys.stderr) # noqa: T201
+ raise _JobError(f"Run threw exception: {str(e)}") from e
+ wandb.finish()
+ except KeyboardInterrupt:
+ raise
+ except Exception as e:
+ wandb.finish(exit_code=1)
+ if self._run_status[run_id] == RunStatus.RUNNING:
+ self._run_status[run_id] = RunStatus.ERRORED
+ self._exceptions[run_id] = e
+ finally:
+ # clean up the environment changes made
+ os.environ.pop(wandb.env.RUN_ID, None)
+ os.environ.pop(wandb.env.SWEEP_ID, None)
+ os.environ.pop(wandb.env.SWEEP_PARAM_PATH, None)
+
+ def run(self):
+ logger.info(
+ f"Starting sweep agent: entity={self._entity}, project={self._project}, count={self._count}"
+ )
+ self._setup()
+ # self._main_thread = threading.Thread(target=self._run_jobs_from_queue)
+ self._heartbeat_thread = threading.Thread(target=self._heartbeat)
+ self._heartbeat_thread.daemon = True
+ # self._main_thread.start()
+ self._heartbeat_thread.start()
+ # self._main_thread.join()
+ self._run_jobs_from_queue()
+
+
+def pyagent(sweep_id, function, entity=None, project=None, count=None):
+ """Generic agent entrypoint, used for CLI or jupyter.
+
+ Args:
+ sweep_id (dict): Sweep ID generated by CLI or sweep API
+ function (func, optional): A function to call instead of the "program"
+ entity (str, optional): W&B Entity
+ project (str, optional): W&B Project
+ count (int, optional): the number of trials to run.
+ """
+ if not callable(function):
+ raise TypeError("function parameter must be callable!")
+ agent = Agent(
+ sweep_id,
+ function=function,
+ entity=entity,
+ project=project,
+ count=count,
+ )
+ agent.run()
+
+
+def _format_exception_traceback(exc):
+ return "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
+
+
+class _JobError(Exception):
+ """Exception raised when a job fails during execution."""
+
+ pass
+
+
+def _get_exception_logger_and_term_strs(exc):
+ if isinstance(exc, _JobError) and exc.__cause__:
+ # If it's a JobException, get the original exception for display
+ job_exc = exc.__cause__
+ log_str = _format_exception_traceback(job_exc)
+ # Don't long full stacktrace to terminal again because we already
+ # printed it to stderr.
+ term_str = " " + str(job_exc)
+ else:
+ log_str = _format_exception_traceback(exc)
+ term_str = "\n" + log_str
+ return log_str, term_str
+
+
+_INSTANCES = 0
+
+
+def is_running():
+ return bool(_INSTANCES)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/analytics/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/analytics/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab265f84acb6b30517cca1a08e24ccdfd90c50e8
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/analytics/__init__.py
@@ -0,0 +1,3 @@
+__all__ = ("Sentry",)
+
+from .sentry import Sentry
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/analytics/sentry.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/analytics/sentry.py
new file mode 100644
index 0000000000000000000000000000000000000000..25ad286f47e598cf42ffdaccad9b91fa6b362ea3
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/analytics/sentry.py
@@ -0,0 +1,267 @@
+from __future__ import annotations
+
+__all__ = ("Sentry",)
+
+
+import atexit
+import functools
+import os
+import pathlib
+import sys
+from types import TracebackType
+from typing import TYPE_CHECKING, Any, Callable, Literal
+from urllib.parse import quote
+
+import sentry_sdk # type: ignore
+import sentry_sdk.scope # type: ignore
+import sentry_sdk.utils # type: ignore
+from typing_extensions import Never
+
+import wandb
+import wandb.env
+import wandb.util
+
+if TYPE_CHECKING:
+ import wandb.sdk.internal.settings_static
+
+SENTRY_DEFAULT_DSN = (
+ "https://2592b1968ea94cca9b5ef5e348e094a7@o151352.ingest.sentry.io/4504800232407040"
+)
+
+SessionStatus = Literal["ok", "exited", "crashed", "abnormal"]
+
+
+def _safe_noop(func: Callable) -> Callable:
+ """Decorator to ensure that Sentry methods do nothing if disabled and don't raise."""
+
+ @functools.wraps(func)
+ def wrapper(self: type[Sentry], *args: Any, **kwargs: Any) -> Any:
+ if self._disabled:
+ return None
+ try:
+ return func(self, *args, **kwargs)
+ except Exception as e:
+ # do not call self.exception here to avoid infinite recursion
+ if func.__name__ != "exception":
+ self.exception(f"Error in {func.__name__}: {e}")
+ return None
+
+ return wrapper
+
+
+class Sentry:
+ _disabled: bool
+
+ def __init__(self) -> None:
+ self._disabled = not wandb.env.error_reporting_enabled()
+ self._sent_messages: set = set()
+
+ self.dsn = os.environ.get(wandb.env.SENTRY_DSN, SENTRY_DEFAULT_DSN)
+
+ self.scope: sentry_sdk.scope.Scope | None = None
+
+ # ensure we always end the Sentry session
+ atexit.register(self.end_session)
+
+ @property
+ def environment(self) -> str:
+ """Return the environment we're running in."""
+ # check if we're in a git repo
+ is_git = pathlib.Path(__file__).parent.parent.parent.joinpath(".git").exists()
+
+ # these match the environments for gorilla
+ return "development" if is_git else "production"
+
+ @_safe_noop
+ def setup(self) -> None:
+ """Setup Sentry SDK.
+
+ We use lower-level APIs (i.e., not sentry_sdk.init) here
+ to avoid the possibility of interfering with the user's
+ own Sentry SDK setup.
+ """
+ client = sentry_sdk.Client(
+ dsn=self.dsn,
+ default_integrations=False,
+ environment=self.environment,
+ release=wandb.__version__,
+ )
+ self.scope = sentry_sdk.get_global_scope().fork()
+ self.scope.clear()
+ self.scope.set_client(client)
+
+ @_safe_noop
+ def message(
+ self,
+ message: str,
+ repeat: bool = True,
+ level: str = "info",
+ ) -> str | None:
+ """Send a message to Sentry."""
+ if not repeat and message in self._sent_messages:
+ return None
+ self._sent_messages.add(message)
+ with sentry_sdk.scope.use_isolation_scope(self.scope): # type: ignore
+ return sentry_sdk.capture_message(message, level=level) # type: ignore
+
+ @_safe_noop
+ def exception(
+ self,
+ exc: str
+ | BaseException
+ | tuple[
+ type[BaseException] | None,
+ BaseException | None,
+ TracebackType | None,
+ ]
+ | None,
+ handled: bool = False,
+ status: SessionStatus | None = None,
+ ) -> str | None:
+ """Log an exception to Sentry."""
+ if isinstance(exc, str):
+ exc_info = sentry_sdk.utils.exc_info_from_error(Exception(exc))
+ elif isinstance(exc, BaseException):
+ exc_info = sentry_sdk.utils.exc_info_from_error(exc)
+ else:
+ exc_info = sys.exc_info()
+
+ event, _ = sentry_sdk.utils.event_from_exception(
+ exc_info,
+ client_options=self.scope.get_client().options, # type: ignore
+ mechanism={"type": "generic", "handled": handled},
+ )
+ event_id = None
+ try:
+ with sentry_sdk.scope.use_isolation_scope(self.scope): # type: ignore
+ event_id = sentry_sdk.capture_event(event) # type: ignore
+ except Exception:
+ pass
+
+ # if the status is not explicitly set, we'll set it to "crashed" if the exception
+ # was unhandled, or "errored" if it was handled
+ status = status or ("crashed" if not handled else "errored") # type: ignore
+ self.mark_session(status=status)
+
+ client = self.scope.get_client() # type: ignore
+ if client is not None:
+ client.flush()
+
+ return event_id
+
+ def reraise(self, exc: Any) -> Never:
+ """Re-raise an exception after logging it to Sentry.
+
+ Use this for top-level exceptions when you want the user to see the traceback.
+
+ Must be called from within an exception handler.
+ """
+ self.exception(exc)
+ # this will messily add this "reraise" function to the stack trace,
+ # but hopefully it's not too bad
+ raise exc.with_traceback(sys.exc_info()[2])
+
+ @_safe_noop
+ def start_session(self) -> None:
+ """Start a new session."""
+ assert self.scope is not None
+ # get the current client and scope
+ session = self.scope._session
+
+ # if there's no session, start one
+ if session is None:
+ self.scope.start_session()
+
+ @_safe_noop
+ def end_session(self) -> None:
+ """End the current session."""
+ assert self.scope is not None
+ # get the current client and scope
+ client = self.scope.get_client()
+ session = self.scope._session
+
+ if session is not None and client is not None:
+ self.scope.end_session()
+ client.flush()
+
+ @_safe_noop
+ def mark_session(self, status: SessionStatus | None = None) -> None:
+ """Mark the current session with a status."""
+ assert self.scope is not None
+ session = self.scope._session
+
+ if session is not None:
+ session.update(status=status)
+
+ @_safe_noop
+ def configure_scope(
+ self,
+ tags: dict[str, Any] | None = None,
+ process_context: str | None = None,
+ ) -> None:
+ """Configure the Sentry scope for the current thread.
+
+ This function should be called at the beginning of every thread that
+ will send events to Sentry. It sets the tags that will be applied to
+ all events sent from this thread. It also tries to start a session
+ if one doesn't already exist for this thread.
+ """
+ assert self.scope is not None
+ settings_tags = (
+ "entity",
+ "project",
+ "run_id",
+ "run_url",
+ "sweep_url",
+ "sweep_id",
+ "deployment",
+ "launch",
+ "_platform",
+ )
+
+ # set context
+ if process_context:
+ self.scope.set_tag("process_context", process_context)
+
+ # apply settings tags
+ if tags is None:
+ return None
+
+ for tag in settings_tags:
+ val = tags.get(tag, None)
+ if val not in (None, ""):
+ self.scope.set_tag(tag, val)
+
+ if tags.get("_colab", None):
+ python_runtime = "colab"
+ elif tags.get("_jupyter", None):
+ python_runtime = "jupyter"
+ elif tags.get("_ipython", None):
+ python_runtime = "ipython"
+ else:
+ python_runtime = "python"
+ self.scope.set_tag("python_runtime", python_runtime)
+
+ # Construct run_url and sweep_url given run_id and sweep_id
+ for obj in ("run", "sweep"):
+ obj_id, obj_url = f"{obj}_id", f"{obj}_url"
+ if tags.get(obj_url, None):
+ continue
+
+ try:
+ app_url = wandb.util.app_url(tags["base_url"]) # type: ignore
+ entity, project = (quote(tags[k]) for k in ("entity", "project")) # type: ignore
+ self.scope.set_tag(
+ obj_url,
+ f"{app_url}/{entity}/{project}/{obj}s/{tags[obj_id]}",
+ )
+ except Exception:
+ pass
+
+ email = tags.get("email")
+ if email:
+ self.scope.user = {"email": email}
+
+ # todo: add back the option to pass general tags see: c645f625d1c1a3db4a6b0e2aa8e924fee101904c (wandb/util.py)
+
+ self.start_session()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..059860a60a73baec0a4466fd3c1bc6a88ad6cac2
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/__init__.py
@@ -0,0 +1,50 @@
+"""api."""
+
+from __future__ import annotations
+
+from typing import Callable
+
+import requests
+from urllib3.exceptions import InsecureRequestWarning
+
+import wandb
+from wandb import env, util
+
+
+def _disable_ssl() -> Callable[[], None]:
+ # Because third party libraries may also use requests, we monkey patch it globally
+ # and turn off urllib3 warnings instead printing a global warning to the user.
+ wandb.termwarn(
+ "Disabling SSL verification. Connections to this server are not verified and may be insecure!"
+ )
+
+ requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
+ old_merge_environment_settings = requests.Session.merge_environment_settings
+
+ def merge_environment_settings(self, url, proxies, stream, verify, cert):
+ settings = old_merge_environment_settings(
+ self, url, proxies, stream, verify, cert
+ )
+ settings["verify"] = False
+ return settings
+
+ requests.Session.merge_environment_settings = merge_environment_settings
+
+ def reset():
+ requests.Session.merge_environment_settings = old_merge_environment_settings
+
+ return reset
+
+
+if env.ssl_disabled():
+ _disable_ssl()
+
+
+reset_path = util.vendor_setup()
+
+from .internal import Api as InternalApi # noqa
+from .public import Api as PublicApi # noqa
+
+reset_path()
+
+__all__ = ["InternalApi", "PublicApi"]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/attrs.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/attrs.py
new file mode 100644
index 0000000000000000000000000000000000000000..61956d98b68144b4ea483e8e9476d4814686b565
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/attrs.py
@@ -0,0 +1,52 @@
+from __future__ import annotations
+
+from typing import Any, MutableMapping
+
+import wandb
+
+from ..sdk.lib import ipython
+
+
+class Attrs:
+ def __init__(self, attrs: MutableMapping[str, Any]):
+ self._attrs = attrs
+
+ def snake_to_camel(self, string):
+ camel = "".join([i.title() for i in string.split("_")])
+ return camel[0].lower() + camel[1:]
+
+ def display(self, height=420, hidden=False) -> bool:
+ """Display this object in jupyter."""
+ if wandb.run and wandb.run._settings.silent:
+ return False
+
+ if not ipython.in_jupyter():
+ return False
+
+ html = self.to_html(height, hidden)
+ if html is None:
+ wandb.termwarn("This object does not support `.display()`")
+ return False
+
+ try:
+ from IPython import display
+ except ImportError:
+ wandb.termwarn(".display() only works in jupyter environments")
+ return False
+
+ display.display(display.HTML(html))
+ return True
+
+ def to_html(self, *args, **kwargs):
+ return None
+
+ def __getattr__(self, name):
+ key = self.snake_to_camel(name)
+ if key == "user":
+ raise AttributeError
+ if key in self._attrs.keys():
+ return self._attrs[key]
+ elif name in self._attrs.keys():
+ return self._attrs[name]
+ else:
+ raise AttributeError(f"{repr(self)!r} object has no attribute {name!r}")
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/importers/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/importers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0266b9f204d4a5487c5d66a6d2487c3670055082
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/importers/__init__.py
@@ -0,0 +1 @@
+from .internals.util import Namespace
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/importers/internals/internal.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/importers/internals/internal.py
new file mode 100644
index 0000000000000000000000000000000000000000..10bf67ba20255deb63980e60500105b4b327b41b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/importers/internals/internal.py
@@ -0,0 +1,375 @@
+import json
+import logging
+import math
+import os
+import queue
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Dict, Iterable, Optional
+
+import numpy as np
+from tenacity import retry, stop_after_attempt, wait_random_exponential
+
+from wandb import Artifact
+from wandb.proto import wandb_internal_pb2 as pb
+from wandb.proto import wandb_telemetry_pb2 as telem_pb
+from wandb.sdk.interface.interface import file_policy_to_enum
+from wandb.sdk.interface.interface_queue import InterfaceQueue
+from wandb.sdk.internal import context
+from wandb.sdk.internal.sender import SendManager
+from wandb.sdk.internal.settings_static import SettingsStatic
+from wandb.util import coalesce, recursive_cast_dictlike_to_dict
+
+from .protocols import ImporterRun
+
+ROOT_DIR = "./wandb-importer"
+
+
+logger = logging.getLogger(__name__)
+logger.setLevel(logging.INFO)
+
+if os.getenv("WANDB_IMPORTER_ENABLE_RICH_LOGGING"):
+ from rich.logging import RichHandler
+
+ logger.addHandler(RichHandler(rich_tracebacks=True, tracebacks_show_locals=True))
+else:
+ console_handler = logging.StreamHandler()
+ console_handler.setLevel(logging.INFO)
+
+ formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
+ console_handler.setFormatter(formatter)
+
+ logger.addHandler(console_handler)
+
+
+exp_retry = retry(
+ wait=wait_random_exponential(multiplier=1, max=10), stop=stop_after_attempt(3)
+)
+
+
+class AlternateSendManager(SendManager):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self._send_artifact = exp_retry(self._send_artifact)
+
+
+@dataclass(frozen=True)
+class SendManagerConfig:
+ """Configure which parts of SendManager tooling to use."""
+
+ use_artifacts: bool = False
+ log_artifacts: bool = False
+ metadata: bool = False
+ files: bool = False
+ media: bool = False
+ code: bool = False
+ history: bool = False
+ summary: bool = False
+ terminal_output: bool = False
+
+
+@dataclass
+class RecordMaker:
+ run: ImporterRun
+ interface: InterfaceQueue = InterfaceQueue()
+
+ @property
+ def run_dir(self) -> str:
+ p = Path(f"{ROOT_DIR}/{self.run.run_id()}/wandb")
+ p.mkdir(parents=True, exist_ok=True)
+ return f"{ROOT_DIR}/{self.run.run_id()}"
+
+ def make_artifacts_only_records(
+ self,
+ artifacts: Optional[Iterable[Artifact]] = None,
+ used_artifacts: Optional[Iterable[Artifact]] = None,
+ ) -> Iterable[pb.Record]:
+ """Only make records required to upload artifacts.
+
+ Escape hatch for adding extra artifacts to a run.
+ """
+ yield self._make_run_record()
+
+ if used_artifacts:
+ for art in used_artifacts:
+ yield self._make_artifact_record(art, use_artifact=True)
+
+ if artifacts:
+ for art in artifacts:
+ yield self._make_artifact_record(art)
+
+ def make_records(
+ self,
+ config: SendManagerConfig,
+ ) -> Iterable[pb.Record]:
+ """Make all the records that constitute a run."""
+ yield self._make_run_record()
+ yield self._make_telem_record()
+
+ include_artifacts = config.log_artifacts or config.use_artifacts
+ yield self._make_files_record(
+ include_artifacts, config.files, config.media, config.code
+ )
+
+ if config.use_artifacts:
+ if (used_artifacts := self.run.used_artifacts()) is not None:
+ for artifact in used_artifacts:
+ yield self._make_artifact_record(artifact, use_artifact=True)
+
+ if config.log_artifacts:
+ if (artifacts := self.run.artifacts()) is not None:
+ for artifact in artifacts:
+ yield self._make_artifact_record(artifact)
+
+ if config.history:
+ yield from self._make_history_records()
+
+ if config.summary:
+ yield self._make_summary_record()
+
+ if config.terminal_output:
+ if (lines := self.run.logs()) is not None:
+ for line in lines:
+ yield self._make_output_record(line)
+
+ def _make_run_record(self) -> pb.Record:
+ run = pb.RunRecord()
+ run.run_id = self.run.run_id()
+ run.entity = self.run.entity()
+ run.project = self.run.project()
+ run.display_name = coalesce(self.run.display_name())
+ run.notes = coalesce(self.run.notes(), "")
+ run.tags.extend(coalesce(self.run.tags(), []))
+ run.start_time.FromMilliseconds(self.run.start_time())
+
+ host = self.run.host()
+ if host is not None:
+ run.host = host
+
+ runtime = self.run.runtime()
+ if runtime is not None:
+ run.runtime = runtime
+
+ run_group = self.run.run_group()
+ if run_group is not None:
+ run.run_group = run_group
+
+ config = self.run.config()
+ if "_wandb" not in config:
+ config["_wandb"] = {}
+
+ # how do I get this automatically?
+ config["_wandb"]["code_path"] = self.run.code_path()
+ config["_wandb"]["python_version"] = self.run.python_version()
+ config["_wandb"]["cli_version"] = self.run.cli_version()
+
+ self.interface._make_config(
+ data=config,
+ obj=run.config,
+ ) # is there a better way?
+ return self.interface._make_record(run=run)
+
+ def _make_output_record(self, line) -> pb.Record:
+ output_raw = pb.OutputRawRecord()
+ output_raw.output_type = pb.OutputRawRecord.OutputType.STDOUT
+ output_raw.line = line
+ return self.interface._make_record(output_raw=output_raw)
+
+ def _make_summary_record(self) -> pb.Record:
+ d: dict = {
+ **self.run.summary(),
+ "_runtime": self.run.runtime(), # quirk of runtime -- it has to be here!
+ # '_timestamp': self.run.start_time()/1000,
+ }
+ d = recursive_cast_dictlike_to_dict(d)
+ summary = self.interface._make_summary_from_dict(d)
+ return self.interface._make_record(summary=summary)
+
+ def _make_history_records(self) -> Iterable[pb.Record]:
+ for metrics in self.run.metrics():
+ history = pb.HistoryRecord()
+ for k, v in metrics.items():
+ item = history.item.add()
+ item.key = k
+ # There seems to be some conversion issue to breaks when we try to re-upload.
+ # np.NaN gets converted to float("nan"), which is not expected by our system.
+ # If this cast to string (!) is not done, the row will be dropped.
+ if (isinstance(v, float) and math.isnan(v)) or v == "NaN":
+ v = np.NaN
+
+ if isinstance(v, bytes):
+ # it's a json string encoded as bytes
+ v = v.decode("utf-8")
+ else:
+ v = json.dumps(v)
+
+ item.value_json = v
+ rec = self.interface._make_record(history=history)
+ yield rec
+
+ def _make_files_record(
+ self, artifacts: bool, files: bool, media: bool, code: bool
+ ) -> pb.Record:
+ run_files = self.run.files()
+ metadata_fname = f"{self.run_dir}/files/wandb-metadata.json"
+ if not files or run_files is None:
+ # We'll always need a metadata file even if there are no other files to upload
+ metadata_fname = self._make_metadata_file()
+ run_files = [(metadata_fname, "end")]
+ files_record = pb.FilesRecord()
+ for path, policy in run_files:
+ if not artifacts and path.startswith("artifact/"):
+ continue
+ if not media and path.startswith("media/"):
+ continue
+ if not code and path.startswith("code/"):
+ continue
+
+ # DirWatcher requires the path to start with media/ instead of the full path
+ if "media" in path:
+ p = Path(path)
+ path = str(p.relative_to(f"{self.run_dir}/files"))
+ f = files_record.files.add()
+ f.path = path
+ f.policy = file_policy_to_enum(policy)
+
+ return self.interface._make_record(files=files_record)
+
+ def _make_artifact_record(
+ self, artifact: Artifact, use_artifact=False
+ ) -> pb.Record:
+ proto = self.interface._make_artifact(artifact)
+ proto.run_id = str(self.run.run_id())
+ proto.project = str(self.run.project())
+ proto.entity = str(self.run.entity())
+ proto.user_created = use_artifact
+ proto.use_after_commit = use_artifact
+ proto.finalize = True
+
+ aliases = artifact._aliases
+ aliases += ["latest", "imported"]
+
+ for alias in aliases:
+ proto.aliases.append(alias)
+ return self.interface._make_record(artifact=proto)
+
+ def _make_telem_record(self) -> pb.Record:
+ telem = telem_pb.TelemetryRecord()
+
+ feature = telem_pb.Feature()
+ feature.importer_mlflow = True
+ telem.feature.CopyFrom(feature)
+
+ cli_version = self.run.cli_version()
+ if cli_version:
+ telem.cli_version = cli_version
+
+ python_version = self.run.python_version()
+ if python_version:
+ telem.python_version = python_version
+
+ return self.interface._make_record(telemetry=telem)
+
+ def _make_metadata_file(self) -> str:
+ missing_text = "This data was not captured"
+ files_dir = f"{self.run_dir}/files"
+ os.makedirs(files_dir, exist_ok=True)
+
+ d = {}
+ d["os"] = coalesce(self.run.os_version(), missing_text)
+ d["python"] = coalesce(self.run.python_version(), missing_text)
+ d["program"] = coalesce(self.run.program(), missing_text)
+ d["cuda"] = coalesce(self.run.cuda_version(), missing_text)
+ d["host"] = coalesce(self.run.host(), missing_text)
+ d["username"] = coalesce(self.run.username(), missing_text)
+ d["executable"] = coalesce(self.run.executable(), missing_text)
+
+ gpus_used = self.run.gpus_used()
+ if gpus_used is not None:
+ d["gpu_devices"] = json.dumps(gpus_used)
+ d["gpu_count"] = json.dumps(len(gpus_used))
+
+ cpus_used = self.run.cpus_used()
+ if cpus_used is not None:
+ d["cpu_count"] = json.dumps(self.run.cpus_used())
+
+ mem_used = self.run.memory_used()
+ if mem_used is not None:
+ d["memory"] = json.dumps({"total": self.run.memory_used()})
+
+ fname = f"{files_dir}/wandb-metadata.json"
+ with open(fname, "w") as f:
+ f.write(json.dumps(d))
+ return fname
+
+
+def _make_settings(
+ root_dir: str, settings_override: Optional[Dict[str, Any]] = None
+) -> SettingsStatic:
+ _settings_override = coalesce(settings_override, {})
+
+ return SettingsStatic(
+ {
+ "x_files_dir": os.path.join(root_dir, "files"),
+ "root_dir": root_dir,
+ "resume": "never",
+ "program": None,
+ "ignore_globs": [],
+ "disable_job_creation": True,
+ "x_start_time": 0,
+ "x_sync": True,
+ "x_live_policy_rate_limit": 15, # matches dir_watcher
+ "x_live_policy_wait_time": 600, # matches dir_watcher
+ "x_file_stream_timeout_seconds": 60,
+ **_settings_override,
+ }
+ )
+
+
+def send_run(
+ run: ImporterRun,
+ *,
+ extra_arts: Optional[Iterable[Artifact]] = None,
+ extra_used_arts: Optional[Iterable[Artifact]] = None,
+ config: Optional[SendManagerConfig] = None,
+ overrides: Optional[Dict[str, Any]] = None,
+ settings_override: Optional[Dict[str, Any]] = None,
+) -> None:
+ if config is None:
+ config = SendManagerConfig()
+
+ # does this need to be here for pmap?
+ if overrides:
+ for k, v in overrides.items():
+ # `lambda: v` won't work!
+ # https://stackoverflow.com/questions/10802002/why-deepcopy-doesnt-create-new-references-to-lambda-function
+ setattr(run, k, lambda v=v: v)
+
+ rm = RecordMaker(run)
+ root_dir = rm.run_dir
+
+ settings = _make_settings(root_dir, settings_override)
+ sm_record_q = queue.Queue()
+ # wm_record_q = queue.Queue()
+ result_q = queue.Queue()
+ interface = InterfaceQueue(record_q=sm_record_q)
+ context_keeper = context.ContextKeeper()
+ sm = AlternateSendManager(
+ settings, sm_record_q, result_q, interface, context_keeper
+ )
+
+ if extra_arts or extra_used_arts:
+ records = rm.make_artifacts_only_records(extra_arts, extra_used_arts)
+ else:
+ records = rm.make_records(config)
+
+ for r in records:
+ logger.debug(f"Sending {r=}")
+ # In a future update, it might be good to write to a transaction log and have
+ # incremental uploads only send the missing records.
+ # wm.write(r)
+
+ sm.send(r)
+
+ sm.finish()
+ # wm.finish()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/importers/internals/protocols.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/importers/internals/protocols.py
new file mode 100644
index 0000000000000000000000000000000000000000..87d42e99175ce5d23db6e375a8cfcaa66568722a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/importers/internals/protocols.py
@@ -0,0 +1,103 @@
+import logging
+from typing import (
+ Any,
+ Dict,
+ Iterable,
+ List,
+ Literal,
+ Optional,
+ Protocol,
+ Tuple,
+ runtime_checkable,
+)
+
+from wandb.sdk.artifacts.artifact import Artifact
+
+logger = logging.getLogger("import_logger")
+
+PathStr = str
+Policy = Literal["now", "end", "live"]
+
+
+@runtime_checkable
+class ImporterRun(Protocol):
+ def run_id(self) -> str: ... # pragma: no cover
+
+ def entity(self) -> str: ... # pragma: no cover
+
+ def project(self) -> str: ... # pragma: no cover
+
+ def config(self) -> Dict[str, Any]: ... # pragma: no cover
+
+ def summary(self) -> Dict[str, float]: ... # pragma: no cover
+
+ def metrics(self) -> Iterable[Dict[str, float]]:
+ """Metrics for the run.
+
+ We expect metrics in this shape:
+
+ [
+ {'metric1': 1, 'metric2': 1, '_step': 0},
+ {'metric1': 2, 'metric2': 4, '_step': 1},
+ {'metric1': 3, 'metric2': 9, '_step': 2},
+ ...
+ ]
+
+ You can also submit metrics in this shape:
+ [
+ {'metric1': 1, '_step': 0},
+ {'metric2': 1, '_step': 0},
+ {'metric1': 2, '_step': 1},
+ {'metric2': 4, '_step': 1},
+ ...
+ ]
+ """
+ ... # pragma: no cover
+
+ def run_group(self) -> Optional[str]: ... # pragma: no cover
+
+ def job_type(self) -> Optional[str]: ... # pragma: no cover
+
+ def display_name(self) -> str: ... # pragma: no cover
+
+ def notes(self) -> Optional[str]: ... # pragma: no cover
+
+ def tags(self) -> Optional[List[str]]: ... # pragma: no cover
+
+ def artifacts(self) -> Optional[Iterable[Artifact]]: ... # pragma: no cover
+
+ def used_artifacts(self) -> Optional[Iterable[Artifact]]: ... # pragma: no cover
+
+ def os_version(self) -> Optional[str]: ... # pragma: no cover
+
+ def python_version(self) -> Optional[str]: ... # pragma: no cover
+
+ def cuda_version(self) -> Optional[str]: ... # pragma: no cover
+
+ def program(self) -> Optional[str]: ... # pragma: no cover
+
+ def host(self) -> Optional[str]: ... # pragma: no cover
+
+ def username(self) -> Optional[str]: ... # pragma: no cover
+
+ def executable(self) -> Optional[str]: ... # pragma: no cover
+
+ def gpus_used(self) -> Optional[str]: ... # pragma: no cover
+
+ def cpus_used(self) -> Optional[int]: ... # pragma: no cover
+
+ def memory_used(self) -> Optional[int]: ... # pragma: no cover
+
+ def runtime(self) -> Optional[int]: ... # pragma: no cover
+
+ def start_time(self) -> Optional[int]: ... # pragma: no cover
+
+ def code_path(self) -> Optional[str]: ... # pragma: no cover
+
+ def cli_version(self) -> Optional[str]: ... # pragma: no cover
+
+ def files(
+ self,
+ ) -> Optional[Iterable[Tuple[PathStr, Policy]]]: ... # pragma: no cover
+
+ def logs(self) -> Optional[Iterable[str]]: ... # pragma: no cover
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/importers/internals/util.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/importers/internals/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..d77585f42e35c26ddc2607620e30888e8b007286
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/importers/internals/util.py
@@ -0,0 +1,78 @@
+import logging
+import sys
+import traceback
+from concurrent.futures import ThreadPoolExecutor, as_completed
+from dataclasses import dataclass
+from typing import Iterable, Optional
+
+
+@dataclass(frozen=True)
+class Namespace:
+ """Configure an alternate entity/project at the dst server your data will end up in."""
+
+ entity: str
+ project: str
+
+ @classmethod
+ def from_path(cls, path: str):
+ entity, project = path.split("/")
+ return cls(entity, project)
+
+ @property
+ def path(self):
+ return f"{self.entity}/{self.project}"
+
+ @property
+ def send_manager_overrides(self):
+ overrides = {}
+ if self.entity:
+ overrides["entity"] = self.entity
+ if self.project:
+ overrides["project"] = self.project
+ return overrides
+
+
+logger = logging.getLogger("import_logger")
+
+
+def parallelize(
+ func,
+ iterable: Iterable,
+ *args,
+ max_workers: Optional[int] = None,
+ raise_on_error: bool = False,
+ **kwargs,
+):
+ def safe_func(*args, **kwargs):
+ try:
+ return func(*args, **kwargs)
+ except Exception as e:
+ _, _, exc_traceback = sys.exc_info()
+ traceback_details = traceback.extract_tb(exc_traceback)
+ filename = traceback_details[-1].filename
+ lineno = traceback_details[-1].lineno
+ logger.debug(
+ f"Exception: {func=} {args=} {kwargs=} {e=} {filename=} {lineno=}. {traceback_details=}"
+ )
+ if raise_on_error:
+ raise
+
+ results = []
+ with ThreadPoolExecutor(max_workers) as exc:
+ futures = {exc.submit(safe_func, x, *args, **kwargs): x for x in iterable}
+ for future in as_completed(futures):
+ results.append(future.result())
+ return results
+
+
+def for_each(
+ func, iterable: Iterable, parallel: bool = True, max_workers: Optional[int] = None
+):
+ if parallel:
+ return parallelize(
+ func,
+ iterable,
+ max_workers=max_workers,
+ )
+
+ return [func(x) for x in iterable]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/importers/mlflow.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/importers/mlflow.py
new file mode 100644
index 0000000000000000000000000000000000000000..1aa5e018bcd9c0f1d1d41eb40413f28d7035a498
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/importers/mlflow.py
@@ -0,0 +1,254 @@
+import itertools
+import logging
+import re
+from collections import defaultdict
+from typing import Any, Dict, Iterable, List, Optional, Tuple
+
+import mlflow
+from packaging.version import Version # type: ignore
+
+import wandb
+from wandb import Artifact
+
+from .internals import internal
+from .internals.util import Namespace, for_each
+
+mlflow_version = Version(mlflow.__version__)
+
+logger = logging.getLogger("import_logger")
+
+
+class MlflowRun:
+ def __init__(self, run, mlflow_client):
+ self.run = run
+ self.mlflow_client: mlflow.MlflowClient = mlflow_client
+
+ def run_id(self) -> str:
+ return self.run.info.run_id
+
+ def entity(self) -> str:
+ return self.run.info.user_id
+
+ def project(self) -> str:
+ return "imported-from-mlflow"
+
+ def config(self) -> Dict[str, Any]:
+ conf = self.run.data.params
+
+ # Add tags here since mlflow supports very long tag names but we only support up to 64 chars
+ tags = {
+ k: v for k, v in self.run.data.tags.items() if not k.startswith("mlflow.")
+ }
+ return {**conf, "imported_mlflow_tags": tags}
+
+ def summary(self) -> Dict[str, float]:
+ return self.run.data.metrics
+
+ def metrics(self) -> Iterable[Dict[str, float]]:
+ d: Dict[int, Dict[str, float]] = defaultdict(dict)
+ for k in self.run.data.metrics.keys():
+ metric = self.mlflow_client.get_metric_history(self.run.info.run_id, k)
+ for item in metric:
+ d[item.step][item.key] = item.value
+
+ for k, v in d.items():
+ yield {"_step": k, **v}
+
+ def run_group(self) -> Optional[str]:
+ # this is nesting? Parent at `run.info.tags.get("mlflow.parentRunId")`
+ return f"Experiment {self.run.info.experiment_id}"
+
+ def job_type(self) -> Optional[str]:
+ # Is this the right approach?
+ return f"User {self.run.info.user_id}"
+
+ def display_name(self) -> str:
+ if mlflow_version < Version("1.30.0"):
+ return self.run.data.tags["mlflow.runName"]
+ return self.run.info.run_name
+
+ def notes(self) -> Optional[str]:
+ return self.run.data.tags.get("mlflow.note.content")
+
+ def tags(self) -> Optional[List[str]]:
+ ...
+
+ # W&B tags are different than mlflow tags.
+ # The full mlflow tags are added to config under key `imported_mlflow_tags` instead
+
+ def artifacts(self) -> Optional[Iterable[Artifact]]: # type: ignore
+ if mlflow_version < Version("2.0.0"):
+ dir_path = self.mlflow_client.download_artifacts(
+ run_id=self.run.info.run_id,
+ path="",
+ )
+ else:
+ dir_path = mlflow.artifacts.download_artifacts(run_id=self.run.info.run_id)
+
+ # Since mlflow doesn't have extra metadata about the artifacts,
+ # we just lump them all together into a single wandb.Artifact
+ artifact_name = self._handle_incompatible_strings(self.display_name())
+ art = wandb.Artifact(artifact_name, "imported-artifacts")
+ art.add_dir(dir_path)
+
+ return [art]
+
+ def used_artifacts(self) -> Optional[Iterable[Artifact]]: # type: ignore
+ ... # pragma: no cover
+
+ def os_version(self) -> Optional[str]: ... # pragma: no cover
+
+ def python_version(self) -> Optional[str]: ... # pragma: no cover
+
+ def cuda_version(self) -> Optional[str]: ... # pragma: no cover
+
+ def program(self) -> Optional[str]: ... # pragma: no cover
+
+ def host(self) -> Optional[str]: ... # pragma: no cover
+
+ def username(self) -> Optional[str]: ... # pragma: no cover
+
+ def executable(self) -> Optional[str]: ... # pragma: no cover
+
+ def gpus_used(self) -> Optional[str]: ... # pragma: no cover
+
+ def cpus_used(self) -> Optional[int]: # can we get the model?
+ ... # pragma: no cover
+
+ def memory_used(self) -> Optional[int]: ... # pragma: no cover
+
+ def runtime(self) -> Optional[int]:
+ end_time = (
+ self.run.info.end_time // 1000
+ if self.run.info.end_time is not None
+ else self.start_time()
+ )
+ return end_time - self.start_time()
+
+ def start_time(self) -> Optional[int]:
+ return self.run.info.start_time // 1000
+
+ def code_path(self) -> Optional[str]: ... # pragma: no cover
+
+ def cli_version(self) -> Optional[str]: ... # pragma: no cover
+
+ def files(self) -> Optional[Iterable[Tuple[str, str]]]: ... # pragma: no cover
+
+ def logs(self) -> Optional[Iterable[str]]: ... # pragma: no cover
+
+ @staticmethod
+ def _handle_incompatible_strings(s: str) -> str:
+ valid_chars = r"[^a-zA-Z0-9_\-\.]"
+ replacement = "__"
+
+ return re.sub(valid_chars, replacement, s)
+
+
+class MlflowImporter:
+ def __init__(
+ self,
+ dst_base_url: str,
+ dst_api_key: str,
+ mlflow_tracking_uri: str,
+ mlflow_registry_uri: Optional[str] = None,
+ *,
+ custom_api_kwargs: Optional[Dict[str, Any]] = None,
+ ) -> None:
+ self.dst_base_url = dst_base_url
+ self.dst_api_key = dst_api_key
+
+ if custom_api_kwargs is None:
+ custom_api_kwargs = {"timeout": 600}
+
+ self.dst_api = wandb.Api(
+ api_key=dst_api_key,
+ overrides={"base_url": dst_base_url},
+ **custom_api_kwargs,
+ )
+ self.mlflow_tracking_uri = mlflow_tracking_uri
+ mlflow.set_tracking_uri(self.mlflow_tracking_uri)
+
+ if mlflow_registry_uri:
+ mlflow.set_registry_uri(mlflow_registry_uri)
+
+ self.mlflow_client = mlflow.tracking.MlflowClient(mlflow_tracking_uri)
+
+ def __repr__(self):
+ return f""
+
+ def collect_runs(self, *, limit: Optional[int] = None) -> Iterable[MlflowRun]:
+ if mlflow_version < Version("1.28.0"):
+ experiments = self.mlflow_client.list_experiments()
+ else:
+ experiments = self.mlflow_client.search_experiments()
+
+ def _runs():
+ for exp in experiments:
+ for run in self.mlflow_client.search_runs(exp.experiment_id):
+ yield MlflowRun(run, self.mlflow_client)
+
+ runs = itertools.islice(_runs(), limit)
+ yield from runs
+
+ def _import_run(
+ self,
+ run: MlflowRun,
+ *,
+ artifacts: bool = True,
+ namespace: Optional[Namespace] = None,
+ config: Optional[internal.SendManagerConfig] = None,
+ ) -> None:
+ if namespace is None:
+ namespace = Namespace(run.entity(), run.project())
+
+ if config is None:
+ config = internal.SendManagerConfig(
+ metadata=True,
+ files=True,
+ media=True,
+ code=True,
+ history=True,
+ summary=True,
+ terminal_output=True,
+ )
+
+ settings_override = {
+ "api_key": self.dst_api_key,
+ "base_url": self.dst_base_url,
+ "resume": "allow",
+ "resumed": True,
+ }
+
+ mlflow.set_tracking_uri(self.mlflow_tracking_uri)
+ internal.send_run(
+ run,
+ overrides=namespace.send_manager_overrides,
+ settings_override=settings_override,
+ config=config,
+ )
+
+ # in mlflow, the artifacts come with the runs, so import them together
+ if artifacts:
+ arts = list(run.artifacts())
+ logger.debug(f"Importing history artifacts, {run=}")
+ internal.send_run(
+ run,
+ extra_arts=arts,
+ overrides=namespace.send_manager_overrides,
+ settings_override=settings_override,
+ config=internal.SendManagerConfig(log_artifacts=True),
+ )
+
+ def import_runs(
+ self,
+ runs: Iterable[MlflowRun],
+ *,
+ artifacts: bool = True,
+ namespace: Optional[Namespace] = None,
+ parallel: bool = True,
+ max_workers: Optional[int] = None,
+ ) -> None:
+ def _import_run_wrapped(run):
+ self._import_run(run, namespace=namespace, artifacts=artifacts)
+
+ for_each(_import_run_wrapped, runs, parallel=parallel, max_workers=max_workers)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/importers/validation.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/importers/validation.py
new file mode 100644
index 0000000000000000000000000000000000000000..219c40285935b6681c819c2c6de006252a806aa7
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/importers/validation.py
@@ -0,0 +1,108 @@
+import filecmp
+import logging
+import os
+
+import requests
+
+import wandb
+
+logger = logging.getLogger(__name__)
+logger.setLevel(logging.INFO)
+
+
+def _compare_artifact_manifests(
+ src_art: wandb.Artifact, dst_art: wandb.Artifact
+) -> list:
+ problems = []
+ if isinstance(dst_art, wandb.CommError):
+ return ["commError"]
+
+ if src_art.digest != dst_art.digest:
+ problems.append(f"digest mismatch {src_art.digest=}, {dst_art.digest=}")
+
+ for name, src_entry in src_art.manifest.entries.items():
+ dst_entry = dst_art.manifest.entries.get(name)
+ if dst_entry is None:
+ problems.append(f"missing manifest entry {name=}, {src_entry=}")
+ continue
+
+ for attr in ["path", "digest", "size"]:
+ if getattr(src_entry, attr) != getattr(dst_entry, attr):
+ problems.append(
+ f"manifest entry mismatch {attr=}, {getattr(src_entry, attr)=}, {getattr(dst_entry, attr)=}"
+ )
+
+ return problems
+
+
+def _compare_artifact_dirs(src_dir, dst_dir) -> list:
+ def compare(src_dir, dst_dir):
+ comparison = filecmp.dircmp(src_dir, dst_dir)
+ differences = {
+ "left_only": comparison.left_only,
+ "right_only": comparison.right_only,
+ "diff_files": comparison.diff_files,
+ "subdir_differences": {},
+ }
+
+ # Recursively find differences in subdirectories
+ for subdir in comparison.subdirs:
+ subdir_src = os.path.join(src_dir, subdir)
+ subdir_dst = os.path.join(dst_dir, subdir)
+ subdir_differences = compare(subdir_src, subdir_dst)
+ # If there are differences, add them to the result
+ if subdir_differences and any(subdir_differences.values()):
+ differences["subdir_differences"][subdir] = subdir_differences
+
+ if all(not diff for diff in differences.values()):
+ return None
+
+ return differences
+
+ return compare(src_dir, dst_dir)
+
+
+def _check_entries_are_downloadable(art):
+ entries = _collect_entries(art)
+ for entry in entries:
+ if not _check_entry_is_downloable(entry):
+ return False
+ return True
+
+
+def _collect_entries(art):
+ has_next_page = True
+ cursor = None
+ entries = []
+ while has_next_page:
+ attrs = art._fetch_file_urls(cursor)
+ has_next_page = attrs["pageInfo"]["hasNextPage"]
+ cursor = attrs["pageInfo"]["endCursor"]
+ for edge in attrs["edges"]:
+ name = edge["node"]["name"]
+ entry = art.get_entry(name)
+ entry._download_url = edge["node"]["directUrl"]
+ entries.append(entry)
+ return entries
+
+
+def _check_entry_is_downloable(entry):
+ url = entry._download_url
+ expected_size = entry.size
+
+ try:
+ resp = requests.head(url, allow_redirects=True)
+ except Exception:
+ logger.exception(f"Problem validating {entry=}")
+ return False
+
+ if resp.status_code != 200:
+ return False
+
+ actual_size = resp.headers.get("content-length", -1)
+ actual_size = int(actual_size)
+
+ if expected_size == actual_size:
+ return True
+
+ return False
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/importers/wandb.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/importers/wandb.py
new file mode 100644
index 0000000000000000000000000000000000000000..b325668295a1d245c1af01ed5a0ab3a997796b65
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/importers/wandb.py
@@ -0,0 +1,1608 @@
+"""Tooling for the W&B Importer."""
+
+import itertools
+import json
+import logging
+import numbers
+import os
+import re
+import shutil
+from dataclasses import dataclass, field
+from datetime import datetime as dt
+from pathlib import Path
+from typing import Any, Dict, Iterable, Iterator, List, Optional, Tuple
+from unittest.mock import patch
+
+import filelock
+import polars as pl
+import requests
+import urllib3
+import wandb_workspaces.reports.v1 as wr
+import yaml
+from wandb_gql import gql
+from wandb_workspaces.reports.v1 import Report
+
+import wandb
+from wandb.apis.public import ArtifactCollection, Run
+from wandb.apis.public.files import File
+from wandb.util import coalesce, remove_keys_with_none_values
+
+from . import validation
+from .internals import internal
+from .internals.protocols import PathStr, Policy
+from .internals.util import Namespace, for_each
+
+Artifact = wandb.Artifact
+Api = wandb.Api
+Project = wandb.apis.public.Project
+
+ARTIFACT_ERRORS_FNAME = "artifact_errors.jsonl"
+ARTIFACT_SUCCESSES_FNAME = "artifact_successes.jsonl"
+RUN_ERRORS_FNAME = "run_errors.jsonl"
+RUN_SUCCESSES_FNAME = "run_successes.jsonl"
+
+ART_SEQUENCE_DUMMY_PLACEHOLDER = "__ART_SEQUENCE_DUMMY_PLACEHOLDER__"
+RUN_DUMMY_PLACEHOLDER = "__RUN_DUMMY_PLACEHOLDER__"
+ART_DUMMY_PLACEHOLDER_PATH = "__importer_temp__"
+ART_DUMMY_PLACEHOLDER_TYPE = "__temp__"
+
+SRC_ART_PATH = "./artifacts/src"
+DST_ART_PATH = "./artifacts/dst"
+
+
+logger = logging.getLogger(__name__)
+logger.setLevel(logging.INFO)
+
+if os.getenv("WANDB_IMPORTER_ENABLE_RICH_LOGGING"):
+ from rich.logging import RichHandler
+
+ logger.addHandler(RichHandler(rich_tracebacks=True, tracebacks_show_locals=True))
+else:
+ console_handler = logging.StreamHandler()
+ console_handler.setLevel(logging.INFO)
+
+ formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
+ console_handler.setFormatter(formatter)
+
+ logger.addHandler(console_handler)
+
+
+@dataclass
+class ArtifactSequence:
+ artifacts: Iterable[wandb.Artifact]
+ entity: str
+ project: str
+ type_: str
+ name: str
+
+ def __iter__(self) -> Iterator:
+ return iter(self.artifacts)
+
+ def __repr__(self) -> str:
+ return f"ArtifactSequence({self.identifier})"
+
+ @property
+ def identifier(self) -> str:
+ return "/".join([self.entity, self.project, self.type_, self.name])
+
+ @classmethod
+ def from_collection(cls, collection: ArtifactCollection):
+ arts = collection.artifacts()
+ arts = sorted(arts, key=lambda a: int(a.version.lstrip("v")))
+ return ArtifactSequence(
+ arts,
+ collection.entity,
+ collection.project,
+ collection.type,
+ collection.name,
+ )
+
+
+class WandbRun:
+ def __init__(
+ self,
+ run: Run,
+ *,
+ src_base_url: str,
+ src_api_key: str,
+ dst_base_url: str,
+ dst_api_key: str,
+ ) -> None:
+ self.run = run
+ self.api = wandb.Api(
+ api_key=src_api_key,
+ overrides={"base_url": src_base_url},
+ )
+ self.dst_api = wandb.Api(
+ api_key=dst_api_key,
+ overrides={"base_url": dst_base_url},
+ )
+
+ # For caching
+ self._files: Optional[Iterable[Tuple[str, str]]] = None
+ self._artifacts: Optional[Iterable[Artifact]] = None
+ self._used_artifacts: Optional[Iterable[Artifact]] = None
+ self._parquet_history_paths: Optional[Iterable[str]] = None
+
+ def __repr__(self) -> str:
+ s = os.path.join(self.entity(), self.project(), self.run_id())
+ return f"WandbRun({s})"
+
+ def run_id(self) -> str:
+ return self.run.id
+
+ def entity(self) -> str:
+ return self.run.entity
+
+ def project(self) -> str:
+ return self.run.project
+
+ def config(self) -> Dict[str, Any]:
+ return self.run.config
+
+ def summary(self) -> Dict[str, float]:
+ s = self.run.summary
+ return s
+
+ def metrics(self) -> Iterable[Dict[str, float]]:
+ if self._parquet_history_paths is None:
+ self._parquet_history_paths = list(self._get_parquet_history_paths())
+
+ if self._parquet_history_paths:
+ rows = self._get_rows_from_parquet_history_paths()
+ else:
+ logger.warning(
+ "No parquet files detected; using scan history (this may not be reliable)"
+ )
+ rows = self.run.scan_history()
+
+ for row in rows:
+ row = remove_keys_with_none_values(row)
+ yield row
+
+ def run_group(self) -> Optional[str]:
+ return self.run.group
+
+ def job_type(self) -> Optional[str]:
+ return self.run.job_type
+
+ def display_name(self) -> str:
+ return self.run.display_name
+
+ def notes(self) -> Optional[str]:
+ # Notes includes the previous notes and serves as a catch-all for things we missed or can't add back
+ previous_link = f"Imported from: {self.run.url}"
+ previous_author = f"Author: {self.run.user.username}"
+
+ header = [previous_link, previous_author]
+ previous_notes = self.run.notes or ""
+
+ return "\n".join(header) + "\n---\n" + previous_notes
+
+ def tags(self) -> Optional[List[str]]:
+ return self.run.tags
+
+ def artifacts(self) -> Optional[Iterable[Artifact]]:
+ if self._artifacts is None:
+ _artifacts = []
+ for art in self.run.logged_artifacts():
+ a = _clone_art(art)
+ _artifacts.append(a)
+ self._artifacts = _artifacts
+
+ yield from self._artifacts
+
+ def used_artifacts(self) -> Optional[Iterable[Artifact]]:
+ if self._used_artifacts is None:
+ _used_artifacts = []
+ for art in self.run.used_artifacts():
+ a = _clone_art(art)
+ _used_artifacts.append(a)
+ self._used_artifacts = _used_artifacts
+
+ yield from self._used_artifacts
+
+ def os_version(self) -> Optional[str]: ... # pragma: no cover
+
+ def python_version(self) -> Optional[str]:
+ return self._metadata_file().get("python")
+
+ def cuda_version(self) -> Optional[str]: ... # pragma: no cover
+
+ def program(self) -> Optional[str]: ... # pragma: no cover
+
+ def host(self) -> Optional[str]:
+ return self._metadata_file().get("host")
+
+ def username(self) -> Optional[str]: ... # pragma: no cover
+
+ def executable(self) -> Optional[str]: ... # pragma: no cover
+
+ def gpus_used(self) -> Optional[str]: ... # pragma: no cover
+
+ def cpus_used(self) -> Optional[int]: # can we get the model?
+ ... # pragma: no cover
+
+ def memory_used(self) -> Optional[int]: ... # pragma: no cover
+
+ def runtime(self) -> Optional[int]:
+ wandb_runtime = self.run.summary.get("_wandb", {}).get("runtime")
+ base_runtime = self.run.summary.get("_runtime")
+
+ if (t := coalesce(wandb_runtime, base_runtime)) is None:
+ return t
+ return int(t)
+
+ def start_time(self) -> Optional[int]:
+ t = dt.fromisoformat(self.run.created_at).timestamp() * 1000
+ return int(t)
+
+ def code_path(self) -> Optional[str]:
+ path = self._metadata_file().get("codePath", "")
+ return f"code/{path}"
+
+ def cli_version(self) -> Optional[str]:
+ return self._config_file().get("_wandb", {}).get("value", {}).get("cli_version")
+
+ def files(self) -> Optional[Iterable[Tuple[PathStr, Policy]]]:
+ if self._files is None:
+ files_dir = f"{internal.ROOT_DIR}/{self.run_id()}/files"
+ _files = []
+ for f in self.run.files():
+ f: File
+ # These optimizations are intended to avoid rate limiting when importing many runs in parallel
+ # Don't carry over empty files
+ if f.size == 0:
+ continue
+ # Skip deadlist to avoid overloading S3
+ if "wandb_manifest.json.deadlist" in f.name:
+ continue
+
+ result = f.download(files_dir, exist_ok=True, api=self.api)
+ file_and_policy = (result.name, "end")
+ _files.append(file_and_policy)
+ self._files = _files
+
+ yield from self._files
+
+ def logs(self) -> Optional[Iterable[str]]:
+ log_files = self._find_all_in_files_regex(r"^.*output\.log$")
+ for path in log_files:
+ with open(path) as f:
+ yield from f.readlines()
+
+ def _metadata_file(self) -> Dict[str, Any]:
+ if (fname := self._find_in_files("wandb-metadata.json")) is None:
+ return {}
+
+ with open(fname) as f:
+ return json.loads(f.read())
+
+ def _config_file(self) -> Dict[str, Any]:
+ if (fname := self._find_in_files("config.yaml")) is None:
+ return {}
+
+ with open(fname) as f:
+ return yaml.safe_load(f) or {}
+
+ def _get_rows_from_parquet_history_paths(self) -> Iterable[Dict[str, Any]]:
+ # Unfortunately, it's not feasible to validate non-parquet history
+ if not (paths := self._get_parquet_history_paths()):
+ yield {}
+ return
+
+ # Collect and merge parquet history
+ dfs = [
+ pl.read_parquet(p) for path in paths for p in Path(path).glob("*.parquet")
+ ]
+ if "_step" in (df := _merge_dfs(dfs)):
+ df = df.with_columns(pl.col("_step").cast(pl.Int64))
+ yield from df.iter_rows(named=True)
+
+ def _get_parquet_history_paths(self) -> Iterable[str]:
+ if self._parquet_history_paths is None:
+ paths = []
+ # self.artifacts() returns a copy of the artifacts; use this to get raw
+ for art in self.run.logged_artifacts():
+ if art.type != "wandb-history":
+ continue
+ if (
+ path := _download_art(art, root=f"{SRC_ART_PATH}/{art.name}")
+ ) is None:
+ continue
+ paths.append(path)
+ self._parquet_history_paths = paths
+
+ yield from self._parquet_history_paths
+
+ def _find_in_files(self, name: str) -> Optional[str]:
+ if files := self.files():
+ for path, _ in files:
+ if name in path:
+ return path
+ return None
+
+ def _find_all_in_files_regex(self, regex: str) -> Iterable[str]:
+ if files := self.files():
+ for path, _ in files:
+ if re.match(regex, path):
+ yield path
+
+
+class WandbImporter:
+ """Transfers runs, reports, and artifact sequences between W&B instances."""
+
+ def __init__(
+ self,
+ src_base_url: str,
+ src_api_key: str,
+ dst_base_url: str,
+ dst_api_key: str,
+ *,
+ custom_api_kwargs: Optional[Dict[str, Any]] = None,
+ ) -> None:
+ self.src_base_url = src_base_url
+ self.src_api_key = src_api_key
+ self.dst_base_url = dst_base_url
+ self.dst_api_key = dst_api_key
+
+ if custom_api_kwargs is None:
+ custom_api_kwargs = {"timeout": 600}
+
+ self.src_api = wandb.Api(
+ api_key=src_api_key,
+ overrides={"base_url": src_base_url},
+ **custom_api_kwargs,
+ )
+ self.dst_api = wandb.Api(
+ api_key=dst_api_key,
+ overrides={"base_url": dst_base_url},
+ **custom_api_kwargs,
+ )
+
+ self.run_api_kwargs = {
+ "src_base_url": src_base_url,
+ "src_api_key": src_api_key,
+ "dst_base_url": dst_base_url,
+ "dst_api_key": dst_api_key,
+ }
+
+ def __repr__(self):
+ return f"" # pragma: no cover
+
+ def _import_run(
+ self,
+ run: WandbRun,
+ *,
+ namespace: Optional[Namespace] = None,
+ config: Optional[internal.SendManagerConfig] = None,
+ ) -> None:
+ """Import one WandbRun.
+
+ Use `namespace` to specify alternate settings like where the run should be uploaded
+ """
+ if namespace is None:
+ namespace = Namespace(run.entity(), run.project())
+
+ if config is None:
+ config = internal.SendManagerConfig(
+ metadata=True,
+ files=True,
+ media=True,
+ code=True,
+ history=True,
+ summary=True,
+ terminal_output=True,
+ )
+
+ settings_override = {
+ "api_key": self.dst_api_key,
+ "base_url": self.dst_base_url,
+ "resume": "true",
+ "resumed": True,
+ }
+
+ # Send run with base config
+ logger.debug(f"Importing run, {run=}")
+ internal.send_run(
+ run,
+ overrides=namespace.send_manager_overrides,
+ settings_override=settings_override,
+ config=config,
+ )
+
+ if config.history:
+ # Send run again with history artifacts in case config history=True, artifacts=False
+ # The history artifact must come with the actual history data
+
+ logger.debug(f"Collecting history artifacts, {run=}")
+ history_arts = []
+ for art in run.run.logged_artifacts():
+ if art.type != "wandb-history":
+ continue
+ logger.debug(f"Collecting history artifact {art.name=}")
+ new_art = _clone_art(art)
+ history_arts.append(new_art)
+
+ logger.debug(f"Importing history artifacts, {run=}")
+ internal.send_run(
+ run,
+ extra_arts=history_arts,
+ overrides=namespace.send_manager_overrides,
+ settings_override=settings_override,
+ config=config,
+ )
+
+ def _delete_collection_in_dst(
+ self,
+ seq: ArtifactSequence,
+ namespace: Optional[Namespace] = None,
+ ):
+ """Deletes the equivalent artifact collection in destination.
+
+ Intended to clear the destination when an uploaded artifact does not pass validation.
+ """
+ entity = coalesce(namespace.entity, seq.entity)
+ project = coalesce(namespace.project, seq.project)
+ art_type = f"{entity}/{project}/{seq.type_}"
+ art_name = seq.name
+
+ logger.info(
+ f"Deleting collection {entity=}, {project=}, {art_type=}, {art_name=}"
+ )
+ try:
+ dst_collection = self.dst_api.artifact_collection(art_type, art_name)
+ except (wandb.CommError, ValueError):
+ logger.warning(f"Collection doesn't exist {art_type=}, {art_name=}")
+ return
+
+ try:
+ dst_collection.delete()
+ except (wandb.CommError, ValueError) as e:
+ logger.warning(
+ f"Collection can't be deleted, {art_type=}, {art_name=}, {e=}"
+ )
+ return
+
+ def _import_artifact_sequence(
+ self,
+ seq: ArtifactSequence,
+ *,
+ namespace: Optional[Namespace] = None,
+ ) -> None:
+ """Import one artifact sequence.
+
+ Use `namespace` to specify alternate settings like where the artifact sequence should be uploaded
+ """
+ if not seq.artifacts:
+ # The artifact sequence has no versions. This usually means all artifacts versions were deleted intentionally,
+ # but it can also happen if the sequence represents run history and that run was deleted.
+ logger.warning(f"Artifact {seq=} has no artifacts, skipping.")
+ return
+
+ if namespace is None:
+ namespace = Namespace(seq.entity, seq.project)
+
+ settings_override = {
+ "api_key": self.dst_api_key,
+ "base_url": self.dst_base_url,
+ "resume": "true",
+ "resumed": True,
+ }
+
+ send_manager_config = internal.SendManagerConfig(log_artifacts=True)
+
+ # Delete any existing artifact sequence, otherwise versions will be out of order
+ # Unfortunately, you can't delete only part of the sequence because versions are "remembered" even after deletion
+ self._delete_collection_in_dst(seq, namespace)
+
+ # Get a placeholder run for dummy artifacts we'll upload later
+ art = seq.artifacts[0]
+ run_or_dummy: Optional[Run] = _get_run_or_dummy_from_art(art, self.src_api)
+
+ # Each `group_of_artifacts` is either:
+ # 1. A single "real" artifact in a list; or
+ # 2. A list of dummy artifacts that are uploaded together.
+ # This guarantees the real artifacts have the correct version numbers while allowing for parallel upload of dummies.
+ groups_of_artifacts = list(_make_groups_of_artifacts(seq))
+ for i, group in enumerate(groups_of_artifacts, 1):
+ art = group[0]
+ if art.description == ART_SEQUENCE_DUMMY_PLACEHOLDER:
+ run = WandbRun(run_or_dummy, **self.run_api_kwargs)
+ else:
+ try:
+ wandb_run = art.logged_by()
+ except ValueError:
+ # The run used to exist but has since been deleted
+ # wandb_run = None
+ pass
+
+ # Could be logged by None (rare) or ValueError
+ if wandb_run is None:
+ logger.warning(
+ f"Run for {art.name=} does not exist (deleted?), using {run_or_dummy=}"
+ )
+ wandb_run = run_or_dummy
+
+ new_art = _clone_art(art)
+ group = [new_art]
+ run = WandbRun(wandb_run, **self.run_api_kwargs)
+
+ logger.info(
+ f"Uploading partial artifact {seq=}, {i}/{len(groups_of_artifacts)}"
+ )
+ internal.send_run(
+ run,
+ extra_arts=group,
+ overrides=namespace.send_manager_overrides,
+ settings_override=settings_override,
+ config=send_manager_config,
+ )
+ logger.info(f"Finished uploading {seq=}")
+
+ # query it back and remove placeholders
+ self._remove_placeholders(seq)
+
+ def _remove_placeholders(self, seq: ArtifactSequence) -> None:
+ try:
+ retry_arts_func = internal.exp_retry(self._dst_api.artifacts)
+ dst_arts = list(retry_arts_func(seq.type_, seq.name))
+ except wandb.CommError:
+ logger.warning(
+ f"{seq=} does not exist in dst. Has it already been deleted?"
+ )
+ return
+ except TypeError:
+ logger.exception("Problem getting dst versions (try again later).")
+ return
+
+ for art in dst_arts:
+ if art.description != ART_SEQUENCE_DUMMY_PLACEHOLDER:
+ continue
+ if art.type in ("wandb-history", "job"):
+ continue
+
+ try:
+ art.delete(delete_aliases=True)
+ except wandb.CommError as e:
+ if "cannot delete system managed artifact" in str(e):
+ logger.warning("Cannot delete system managed artifact")
+ else:
+ raise
+
+ def _get_dst_art(
+ self, src_art: Run, entity: Optional[str] = None, project: Optional[str] = None
+ ) -> Artifact:
+ entity = coalesce(entity, src_art.entity)
+ project = coalesce(project, src_art.project)
+ name = src_art.name
+
+ return self.dst_api._artifact(f"{entity}/{project}/{name}")
+
+ def _get_run_problems(
+ self, src_run: Run, dst_run: Run, force_retry: bool = False
+ ) -> List[dict]:
+ problems = []
+
+ if force_retry:
+ problems.append("__force_retry__")
+
+ if non_matching_metadata := self._compare_run_metadata(src_run, dst_run):
+ problems.append("metadata:" + str(non_matching_metadata))
+
+ if non_matching_summary := self._compare_run_summary(src_run, dst_run):
+ problems.append("summary:" + str(non_matching_summary))
+
+ # TODO: Compare files?
+
+ return problems
+
+ def _compare_run_metadata(self, src_run: Run, dst_run: Run) -> dict:
+ fname = "wandb-metadata.json"
+ # problems = {}
+
+ src_f = src_run.file(fname)
+ if src_f.size == 0:
+ # the src was corrupted so no comparisons here will ever work
+ return {}
+
+ dst_f = dst_run.file(fname)
+ try:
+ contents = wandb.util.download_file_into_memory(
+ dst_f.url, self.dst_api.api_key
+ )
+ except urllib3.exceptions.ReadTimeoutError:
+ return {"Error checking": "Timeout"}
+ except requests.HTTPError as e:
+ if e.response.status_code == 404:
+ return {"Bad upload": f"File not found: {fname}"}
+ return {"http problem": f"{fname}: ({e})"}
+
+ dst_meta = wandb.wandb_sdk.lib.json_util.loads(contents)
+
+ non_matching = {}
+ if src_run.metadata:
+ for k, src_v in src_run.metadata.items():
+ if k not in dst_meta:
+ non_matching[k] = {"src": src_v, "dst": "KEY NOT FOUND"}
+ continue
+ dst_v = dst_meta[k]
+ if src_v != dst_v:
+ non_matching[k] = {"src": src_v, "dst": dst_v}
+
+ return non_matching
+
+ def _compare_run_summary(self, src_run: Run, dst_run: Run) -> dict:
+ non_matching = {}
+ for k, src_v in src_run.summary.items():
+ # These won't match between systems and that's ok
+ if isinstance(src_v, str) and src_v.startswith("wandb-client-artifact://"):
+ continue
+ if k in ("_wandb", "_runtime"):
+ continue
+
+ src_v = _recursive_cast_to_dict(src_v)
+
+ dst_v = dst_run.summary.get(k)
+ dst_v = _recursive_cast_to_dict(dst_v)
+
+ if isinstance(src_v, dict) and isinstance(dst_v, dict):
+ for kk, sv in src_v.items():
+ # These won't match between systems and that's ok
+ if isinstance(sv, str) and sv.startswith(
+ "wandb-client-artifact://"
+ ):
+ continue
+ dv = dst_v.get(kk)
+ if not _almost_equal(sv, dv):
+ non_matching[f"{k}-{kk}"] = {"src": sv, "dst": dv}
+ else:
+ if not _almost_equal(src_v, dst_v):
+ non_matching[k] = {"src": src_v, "dst": dst_v}
+
+ return non_matching
+
+ def _collect_failed_artifact_sequences(self) -> Iterable[ArtifactSequence]:
+ if (df := _read_ndjson(ARTIFACT_ERRORS_FNAME)) is None:
+ logger.debug(f"{ARTIFACT_ERRORS_FNAME=} is empty, returning nothing")
+ return
+
+ unique_failed_sequences = df[
+ ["src_entity", "src_project", "name", "type"]
+ ].unique()
+
+ for row in unique_failed_sequences.iter_rows(named=True):
+ entity = row["src_entity"]
+ project = row["src_project"]
+ name = row["name"]
+ _type = row["type"]
+
+ art_name = f"{entity}/{project}/{name}"
+ arts = self.src_api.artifacts(_type, art_name)
+ arts = sorted(arts, key=lambda a: int(a.version.lstrip("v")))
+ arts = sorted(arts, key=lambda a: a.type)
+
+ yield ArtifactSequence(arts, entity, project, _type, name)
+
+ def _cleanup_dummy_runs(
+ self,
+ *,
+ namespaces: Optional[Iterable[Namespace]] = None,
+ api: Optional[Api] = None,
+ remapping: Optional[Dict[Namespace, Namespace]] = None,
+ ) -> None:
+ api = coalesce(api, self.dst_api)
+ namespaces = coalesce(namespaces, self._all_namespaces())
+
+ for ns in namespaces:
+ if remapping and ns in remapping:
+ ns = remapping[ns]
+
+ logger.debug(f"Cleaning up, {ns=}")
+ try:
+ runs = list(
+ api.runs(ns.path, filters={"displayName": RUN_DUMMY_PLACEHOLDER})
+ )
+ except ValueError as e:
+ if "Could not find project" in str(e):
+ logger.exception("Could not find project, does it exist?")
+ continue
+
+ for run in runs:
+ logger.debug(f"Deleting dummy {run=}")
+ run.delete(delete_artifacts=False)
+
+ def _import_report(
+ self, report: Report, *, namespace: Optional[Namespace] = None
+ ) -> None:
+ """Import one wandb.Report.
+
+ Use `namespace` to specify alternate settings like where the report should be uploaded
+ """
+ if namespace is None:
+ namespace = Namespace(report.entity, report.project)
+
+ entity = coalesce(namespace.entity, report.entity)
+ project = coalesce(namespace.project, report.project)
+ name = report.name
+ title = report.title
+ description = report.description
+
+ api = self.dst_api
+
+ # We shouldn't need to upsert the project for every report
+ logger.debug(f"Upserting {entity=}/{project=}")
+ try:
+ api.create_project(project, entity)
+ except requests.exceptions.HTTPError as e:
+ if e.response.status_code != 409:
+ logger.warning(f"Issue upserting {entity=}/{project=}, {e=}")
+
+ logger.debug(f"Upserting report {entity=}, {project=}, {name=}, {title=}")
+ api.client.execute(
+ wr.report.UPSERT_VIEW,
+ variable_values={
+ "id": None, # Is there any benefit for this to be the same as default report?
+ "name": name,
+ "entityName": entity,
+ "projectName": project,
+ "description": description,
+ "displayName": title,
+ "type": "runs",
+ "spec": json.dumps(report.spec),
+ },
+ )
+
+ def _use_artifact_sequence(
+ self,
+ sequence: ArtifactSequence,
+ *,
+ namespace: Optional[Namespace] = None,
+ ):
+ if namespace is None:
+ namespace = Namespace(sequence.entity, sequence.project)
+
+ settings_override = {
+ "api_key": self.dst_api_key,
+ "base_url": self.dst_base_url,
+ "resume": "true",
+ "resumed": True,
+ }
+ logger.debug(f"Using artifact sequence with {settings_override=}, {namespace=}")
+
+ send_manager_config = internal.SendManagerConfig(use_artifacts=True)
+
+ for art in sequence:
+ if (used_by := art.used_by()) is None:
+ continue
+
+ for wandb_run in used_by:
+ run = WandbRun(wandb_run, **self.run_api_kwargs)
+
+ internal.send_run(
+ run,
+ overrides=namespace.send_manager_overrides,
+ settings_override=settings_override,
+ config=send_manager_config,
+ )
+
+ def import_runs(
+ self,
+ *,
+ namespaces: Optional[Iterable[Namespace]] = None,
+ remapping: Optional[Dict[Namespace, Namespace]] = None,
+ parallel: bool = True,
+ incremental: bool = True,
+ max_workers: Optional[int] = None,
+ limit: Optional[int] = None,
+ metadata: bool = True,
+ files: bool = True,
+ media: bool = True,
+ code: bool = True,
+ history: bool = True,
+ summary: bool = True,
+ terminal_output: bool = True,
+ ):
+ logger.info("START: Import runs")
+
+ logger.info("Setting up for import")
+ _create_files_if_not_exists()
+ _clear_fname(RUN_ERRORS_FNAME)
+
+ logger.info("Collecting runs")
+ runs = list(self._collect_runs(namespaces=namespaces, limit=limit))
+
+ logger.info(f"Validating runs, {len(runs)=}")
+ self._validate_runs(
+ runs,
+ skip_previously_validated=incremental,
+ remapping=remapping,
+ )
+
+ logger.info("Collecting failed runs")
+ runs = list(self._collect_failed_runs())
+
+ logger.info(f"Importing runs, {len(runs)=}")
+
+ def _import_run_wrapped(run):
+ namespace = Namespace(run.entity(), run.project())
+ if remapping is not None and namespace in remapping:
+ namespace = remapping[namespace]
+
+ config = internal.SendManagerConfig(
+ metadata=metadata,
+ files=files,
+ media=media,
+ code=code,
+ history=history,
+ summary=summary,
+ terminal_output=terminal_output,
+ )
+
+ logger.debug(f"Importing {run=}, {namespace=}, {config=}")
+ self._import_run(run, namespace=namespace, config=config)
+ logger.debug(f"Finished importing {run=}, {namespace=}, {config=}")
+
+ for_each(_import_run_wrapped, runs, max_workers=max_workers, parallel=parallel)
+ logger.info("END: Importing runs")
+
+ def import_reports(
+ self,
+ *,
+ namespaces: Optional[Iterable[Namespace]] = None,
+ limit: Optional[int] = None,
+ remapping: Optional[Dict[Namespace, Namespace]] = None,
+ ):
+ logger.info("START: Importing reports")
+
+ logger.info("Collecting reports")
+ reports = self._collect_reports(namespaces=namespaces, limit=limit)
+
+ logger.info("Importing reports")
+
+ def _import_report_wrapped(report):
+ namespace = Namespace(report.entity, report.project)
+ if remapping is not None and namespace in remapping:
+ namespace = remapping[namespace]
+
+ logger.debug(f"Importing {report=}, {namespace=}")
+ self._import_report(report, namespace=namespace)
+ logger.debug(f"Finished importing {report=}, {namespace=}")
+
+ for_each(_import_report_wrapped, reports)
+
+ logger.info("END: Importing reports")
+
+ def import_artifact_sequences(
+ self,
+ *,
+ namespaces: Optional[Iterable[Namespace]] = None,
+ incremental: bool = True,
+ max_workers: Optional[int] = None,
+ remapping: Optional[Dict[Namespace, Namespace]] = None,
+ ):
+ """Import all artifact sequences from `namespaces`.
+
+ Note: There is a known bug with the AWS backend where artifacts > 2048MB will fail to upload. This seems to be related to multipart uploads, but we don't have a fix yet.
+ """
+ logger.info("START: Importing artifact sequences")
+ _clear_fname(ARTIFACT_ERRORS_FNAME)
+
+ logger.info("Collecting artifact sequences")
+ seqs = list(self._collect_artifact_sequences(namespaces=namespaces))
+
+ logger.info("Validating artifact sequences")
+ self._validate_artifact_sequences(
+ seqs,
+ incremental=incremental,
+ remapping=remapping,
+ )
+
+ logger.info("Collecting failed artifact sequences")
+ seqs = list(self._collect_failed_artifact_sequences())
+
+ logger.info(f"Importing artifact sequences, {len(seqs)=}")
+
+ def _import_artifact_sequence_wrapped(seq):
+ namespace = Namespace(seq.entity, seq.project)
+ if remapping is not None and namespace in remapping:
+ namespace = remapping[namespace]
+
+ logger.debug(f"Importing artifact sequence {seq=}, {namespace=}")
+ self._import_artifact_sequence(seq, namespace=namespace)
+ logger.debug(f"Finished importing artifact sequence {seq=}, {namespace=}")
+
+ for_each(_import_artifact_sequence_wrapped, seqs, max_workers=max_workers)
+
+ # it's safer to just use artifact on all seqs to make sure we don't miss anything
+ # For seqs that have already been used, this is a no-op.
+ logger.debug(f"Using artifact sequences, {len(seqs)=}")
+
+ def _use_artifact_sequence_wrapped(seq):
+ namespace = Namespace(seq.entity, seq.project)
+ if remapping is not None and namespace in remapping:
+ namespace = remapping[namespace]
+
+ logger.debug(f"Using artifact sequence {seq=}, {namespace=}")
+ self._use_artifact_sequence(seq, namespace=namespace)
+ logger.debug(f"Finished using artifact sequence {seq=}, {namespace=}")
+
+ for_each(_use_artifact_sequence_wrapped, seqs, max_workers=max_workers)
+
+ # Artifacts whose parent runs have been deleted should have that run deleted in the
+ # destination as well
+
+ logger.info("Cleaning up dummy runs")
+ self._cleanup_dummy_runs(
+ namespaces=namespaces,
+ remapping=remapping,
+ )
+
+ logger.info("END: Importing artifact sequences")
+
+ def import_all(
+ self,
+ *,
+ runs: bool = True,
+ artifacts: bool = True,
+ reports: bool = True,
+ namespaces: Optional[Iterable[Namespace]] = None,
+ incremental: bool = True,
+ remapping: Optional[Dict[Namespace, Namespace]] = None,
+ ):
+ logger.info(f"START: Importing all, {runs=}, {artifacts=}, {reports=}")
+ if runs:
+ self.import_runs(
+ namespaces=namespaces,
+ incremental=incremental,
+ remapping=remapping,
+ )
+
+ if reports:
+ self.import_reports(
+ namespaces=namespaces,
+ remapping=remapping,
+ )
+
+ if artifacts:
+ self.import_artifact_sequences(
+ namespaces=namespaces,
+ incremental=incremental,
+ remapping=remapping,
+ )
+
+ logger.info("END: Importing all")
+
+ def _validate_run(
+ self,
+ src_run: Run,
+ *,
+ remapping: Optional[Dict[Namespace, Namespace]] = None,
+ ) -> None:
+ namespace = Namespace(src_run.entity, src_run.project)
+ if remapping is not None and namespace in remapping:
+ namespace = remapping[namespace]
+
+ dst_entity = namespace.entity
+ dst_project = namespace.project
+ run_id = src_run.id
+
+ try:
+ dst_run = self.dst_api.run(f"{dst_entity}/{dst_project}/{run_id}")
+ except wandb.CommError:
+ problems = [f"run does not exist in dst at {dst_entity=}/{dst_project=}"]
+ else:
+ problems = self._get_run_problems(src_run, dst_run)
+
+ d = {
+ "src_entity": src_run.entity,
+ "src_project": src_run.project,
+ "dst_entity": dst_entity,
+ "dst_project": dst_project,
+ "run_id": run_id,
+ }
+ if problems:
+ d["problems"] = problems
+ fname = RUN_ERRORS_FNAME
+ else:
+ fname = RUN_SUCCESSES_FNAME
+
+ with filelock.FileLock("runs.lock"):
+ with open(fname, "a") as f:
+ f.write(json.dumps(d) + "\n")
+
+ def _filter_previously_checked_runs(
+ self,
+ runs: Iterable[Run],
+ *,
+ remapping: Optional[Dict[Namespace, Namespace]] = None,
+ ) -> Iterable[Run]:
+ if (df := _read_ndjson(RUN_SUCCESSES_FNAME)) is None:
+ logger.debug(f"{RUN_SUCCESSES_FNAME=} is empty, yielding all runs")
+ yield from runs
+ return
+
+ data = []
+ for r in runs:
+ namespace = Namespace(r.entity, r.project)
+ if remapping is not None and namespace in remapping:
+ namespace = remapping[namespace]
+
+ data.append(
+ {
+ "src_entity": r.entity,
+ "src_project": r.project,
+ "dst_entity": namespace.entity,
+ "dst_project": namespace.project,
+ "run_id": r.id,
+ "data": r,
+ }
+ )
+ df2 = pl.DataFrame(data)
+ logger.debug(f"Starting with {len(runs)=} in namespaces")
+
+ results = df2.join(
+ df,
+ how="anti",
+ on=["src_entity", "src_project", "dst_entity", "dst_project", "run_id"],
+ )
+ logger.debug(f"After filtering out already successful runs, {len(results)=}")
+
+ if not results.is_empty():
+ results = results.filter(~results["run_id"].is_null())
+ results = results.unique(
+ ["src_entity", "src_project", "dst_entity", "dst_project", "run_id"]
+ )
+
+ for r in results.iter_rows(named=True):
+ yield r["data"]
+
+ def _validate_artifact(
+ self,
+ src_art: Artifact,
+ dst_entity: str,
+ dst_project: str,
+ download_files_and_compare: bool = False,
+ check_entries_are_downloadable: bool = True,
+ ):
+ problems = []
+
+ # These patterns of artifacts are special and should not be validated
+ ignore_patterns = [
+ r"^job-(.*?)\.py(:v\d+)?$",
+ # r"^run-.*-history(?:\:v\d+)?$$",
+ ]
+ for pattern in ignore_patterns:
+ if re.search(pattern, src_art.name):
+ return (src_art, dst_entity, dst_project, problems)
+
+ try:
+ dst_art = self._get_dst_art(src_art, dst_entity, dst_project)
+ except Exception:
+ problems.append("destination artifact not found")
+ return (src_art, dst_entity, dst_project, problems)
+
+ try:
+ logger.debug("Comparing artifact manifests")
+ except Exception as e:
+ problems.append(
+ f"Problem getting problems! problem with {src_art.entity=}, {src_art.project=}, {src_art.name=} {e=}"
+ )
+ else:
+ problems += validation._compare_artifact_manifests(src_art, dst_art)
+
+ if check_entries_are_downloadable:
+ # validation._check_entries_are_downloadable(src_art)
+ validation._check_entries_are_downloadable(dst_art)
+
+ if download_files_and_compare:
+ logger.debug(f"Downloading {src_art=}")
+ try:
+ src_dir = _download_art(src_art, root=f"{SRC_ART_PATH}/{src_art.name}")
+ except requests.HTTPError as e:
+ problems.append(
+ f"Invalid download link for src {src_art.entity=}, {src_art.project=}, {src_art.name=}, {e}"
+ )
+
+ logger.debug(f"Downloading {dst_art=}")
+ try:
+ dst_dir = _download_art(dst_art, root=f"{DST_ART_PATH}/{dst_art.name}")
+ except requests.HTTPError as e:
+ problems.append(
+ f"Invalid download link for dst {dst_art.entity=}, {dst_art.project=}, {dst_art.name=}, {e}"
+ )
+ else:
+ logger.debug(f"Comparing artifact dirs {src_dir=}, {dst_dir=}")
+ if problem := validation._compare_artifact_dirs(src_dir, dst_dir):
+ problems.append(problem)
+
+ return (src_art, dst_entity, dst_project, problems)
+
+ def _validate_runs(
+ self,
+ runs: Iterable[WandbRun],
+ *,
+ skip_previously_validated: bool = True,
+ remapping: Optional[Dict[Namespace, Namespace]] = None,
+ ):
+ base_runs = [r.run for r in runs]
+ if skip_previously_validated:
+ base_runs = list(
+ self._filter_previously_checked_runs(
+ base_runs,
+ remapping=remapping,
+ )
+ )
+
+ def _validate_run(run):
+ logger.debug(f"Validating {run=}")
+ self._validate_run(run, remapping=remapping)
+ logger.debug(f"Finished validating {run=}")
+
+ for_each(_validate_run, base_runs)
+
+ def _collect_failed_runs(self):
+ if (df := _read_ndjson(RUN_ERRORS_FNAME)) is None:
+ logger.debug(f"{RUN_ERRORS_FNAME=} is empty, returning nothing")
+ return
+
+ unique_failed_runs = df[
+ ["src_entity", "src_project", "dst_entity", "dst_project", "run_id"]
+ ].unique()
+
+ for row in unique_failed_runs.iter_rows(named=True):
+ src_entity = row["src_entity"]
+ src_project = row["src_project"]
+ # dst_entity = row["dst_entity"]
+ # dst_project = row["dst_project"]
+ run_id = row["run_id"]
+
+ run = self.src_api.run(f"{src_entity}/{src_project}/{run_id}")
+ yield WandbRun(run, **self.run_api_kwargs)
+
+ def _filter_previously_checked_artifacts(self, seqs: Iterable[ArtifactSequence]):
+ if (df := _read_ndjson(ARTIFACT_SUCCESSES_FNAME)) is None:
+ logger.info(
+ f"{ARTIFACT_SUCCESSES_FNAME=} is empty, yielding all artifact sequences"
+ )
+ for seq in seqs:
+ yield from seq.artifacts
+ return
+
+ for seq in seqs:
+ for art in seq:
+ try:
+ logged_by = _get_run_or_dummy_from_art(art, self.src_api)
+ except requests.HTTPError:
+ logger.exception(f"Failed to get run, skipping: {art=}")
+ continue
+
+ if art.type == "wandb-history" and isinstance(logged_by, _DummyRun):
+ logger.debug(f"Skipping history artifact {art=}")
+ # We can never upload valid history for a deleted run, so skip it
+ continue
+
+ entity = art.entity
+ project = art.project
+ _type = art.type
+ name, ver = _get_art_name_ver(art)
+
+ filtered_df = df.filter(
+ (df["src_entity"] == entity)
+ & (df["src_project"] == project)
+ & (df["name"] == name)
+ & (df["version"] == ver)
+ & (df["type"] == _type)
+ )
+
+ # not in file, so not verified yet, don't filter out
+ if len(filtered_df) == 0:
+ yield art
+
+ def _validate_artifact_sequences(
+ self,
+ seqs: Iterable[ArtifactSequence],
+ *,
+ incremental: bool = True,
+ download_files_and_compare: bool = False,
+ check_entries_are_downloadable: bool = True,
+ remapping: Optional[Dict[Namespace, Namespace]] = None,
+ ):
+ if incremental:
+ logger.info("Validating in incremental mode")
+
+ def filtered_sequences():
+ for seq in seqs:
+ if not seq.artifacts:
+ continue
+
+ art = seq.artifacts[0]
+ try:
+ logged_by = _get_run_or_dummy_from_art(art, self.src_api)
+ except requests.HTTPError:
+ logger.exception(
+ f"Validate Artifact http error: {art.entity=},"
+ f" {art.project=}, {art.name=}"
+ )
+ continue
+
+ if art.type == "wandb-history" and isinstance(logged_by, _DummyRun):
+ # We can never upload valid history for a deleted run, so skip it
+ continue
+
+ yield seq
+
+ artifacts = self._filter_previously_checked_artifacts(filtered_sequences())
+ else:
+ logger.info("Validating in non-incremental mode")
+ artifacts = [art for seq in seqs for art in seq.artifacts]
+
+ def _validate_artifact_wrapped(args):
+ art, entity, project = args
+ if (
+ remapping is not None
+ and (namespace := Namespace(entity, project)) in remapping
+ ):
+ remapped_ns = remapping[namespace]
+ entity = remapped_ns.entity
+ project = remapped_ns.project
+
+ logger.debug(f"Validating {art=}, {entity=}, {project=}")
+ result = self._validate_artifact(
+ art,
+ entity,
+ project,
+ download_files_and_compare=download_files_and_compare,
+ check_entries_are_downloadable=check_entries_are_downloadable,
+ )
+ logger.debug(f"Finished validating {art=}, {entity=}, {project=}")
+ return result
+
+ args = ((art, art.entity, art.project) for art in artifacts)
+ art_problems = for_each(_validate_artifact_wrapped, args)
+ for art, dst_entity, dst_project, problems in art_problems:
+ name, ver = _get_art_name_ver(art)
+ d = {
+ "src_entity": art.entity,
+ "src_project": art.project,
+ "dst_entity": dst_entity,
+ "dst_project": dst_project,
+ "name": name,
+ "version": ver,
+ "type": art.type,
+ }
+
+ if problems:
+ d["problems"] = problems
+ fname = ARTIFACT_ERRORS_FNAME
+ else:
+ fname = ARTIFACT_SUCCESSES_FNAME
+
+ with open(fname, "a") as f:
+ f.write(json.dumps(d) + "\n")
+
+ def _collect_runs(
+ self,
+ *,
+ namespaces: Optional[Iterable[Namespace]] = None,
+ limit: Optional[int] = None,
+ skip_ids: Optional[List[str]] = None,
+ start_date: Optional[str] = None,
+ api: Optional[Api] = None,
+ ) -> Iterable[WandbRun]:
+ api = coalesce(api, self.src_api)
+ namespaces = coalesce(namespaces, self._all_namespaces())
+
+ filters: Dict[str, Any] = {}
+ if skip_ids is not None:
+ filters["name"] = {"$nin": skip_ids}
+ if start_date is not None:
+ filters["createdAt"] = {"$gte": start_date}
+
+ def _runs():
+ for ns in namespaces:
+ logger.debug(f"Collecting runs from {ns=}")
+ for run in api.runs(ns.path, filters=filters):
+ yield WandbRun(run, **self.run_api_kwargs)
+
+ runs = itertools.islice(_runs(), limit)
+ yield from runs
+
+ def _all_namespaces(
+ self, *, entity: Optional[str] = None, api: Optional[Api] = None
+ ):
+ api = coalesce(api, self.src_api)
+ entity = coalesce(entity, api.default_entity)
+ projects = api.projects(entity)
+ for p in projects:
+ yield Namespace(p.entity, p.name)
+
+ def _collect_reports(
+ self,
+ *,
+ namespaces: Optional[Iterable[Namespace]] = None,
+ limit: Optional[int] = None,
+ api: Optional[Api] = None,
+ ):
+ api = coalesce(api, self.src_api)
+ namespaces = coalesce(namespaces, self._all_namespaces())
+
+ wandb.login(key=self.src_api_key, host=self.src_base_url)
+
+ def reports():
+ for ns in namespaces:
+ for r in api.reports(ns.path):
+ yield wr.Report.from_url(r.url, api=api)
+
+ yield from itertools.islice(reports(), limit)
+
+ def _collect_artifact_sequences(
+ self,
+ *,
+ namespaces: Optional[Iterable[Namespace]] = None,
+ limit: Optional[int] = None,
+ api: Optional[Api] = None,
+ ):
+ api = coalesce(api, self.src_api)
+ namespaces = coalesce(namespaces, self._all_namespaces())
+
+ def artifact_sequences():
+ for ns in namespaces:
+ logger.debug(f"Collecting artifact sequences from {ns=}")
+ types = []
+ try:
+ types = [t for t in api.artifact_types(ns.path)]
+ except Exception:
+ logger.exception("Failed to get artifact types.")
+
+ for t in types:
+ collections = []
+
+ # Skip history because it's really for run history
+ if t.name == "wandb-history":
+ continue
+
+ try:
+ collections = t.collections()
+ except Exception:
+ logger.exception("Failed to get artifact collections.")
+
+ for c in collections:
+ if c.is_sequence():
+ yield ArtifactSequence.from_collection(c)
+
+ seqs = itertools.islice(artifact_sequences(), limit)
+ unique_sequences = {seq.identifier: seq for seq in seqs}
+ yield from unique_sequences.values()
+
+
+def _get_art_name_ver(art: Artifact) -> Tuple[str, int]:
+ name, ver = art.name.split(":v")
+ return name, int(ver)
+
+
+def _make_dummy_art(name: str, _type: str, ver: int):
+ art = Artifact(name, ART_DUMMY_PLACEHOLDER_TYPE)
+ art._type = _type
+ art._description = ART_SEQUENCE_DUMMY_PLACEHOLDER
+
+ p = Path(ART_DUMMY_PLACEHOLDER_PATH)
+ p.mkdir(parents=True, exist_ok=True)
+
+ # dummy file with different name to prevent dedupe
+ fname = p / str(ver)
+ with open(fname, "w"):
+ pass
+ art.add_file(fname)
+
+ return art
+
+
+def _make_groups_of_artifacts(seq: ArtifactSequence, start: int = 0):
+ prev_ver = start - 1
+ for art in seq:
+ name, ver = _get_art_name_ver(art)
+
+ # If there's a gap between versions, fill with dummy artifacts
+ if ver - prev_ver > 1:
+ yield [_make_dummy_art(name, art.type, v) for v in range(prev_ver + 1, ver)]
+
+ # Then yield the actual artifact
+ # Must always be a list of one artifact to guarantee ordering
+ yield [art]
+ prev_ver = ver
+
+
+def _recursive_cast_to_dict(obj):
+ if isinstance(obj, list):
+ return [_recursive_cast_to_dict(item) for item in obj]
+ elif isinstance(obj, dict) or hasattr(obj, "items"):
+ new_dict = {}
+ for key, value in obj.items():
+ new_dict[key] = _recursive_cast_to_dict(value)
+ return new_dict
+ else:
+ return obj
+
+
+def _almost_equal(x, y, eps=1e-6):
+ if isinstance(x, dict) and isinstance(y, dict):
+ if x.keys() != y.keys():
+ return False
+ return all(_almost_equal(x[k], y[k], eps) for k in x)
+
+ if isinstance(x, numbers.Number) and isinstance(y, numbers.Number):
+ return abs(x - y) < eps
+
+ if type(x) is not type(y):
+ return False
+
+ return x == y
+
+
+@dataclass
+class _DummyUser:
+ username: str = ""
+
+
+@dataclass
+class _DummyRun:
+ entity: str = ""
+ project: str = ""
+ run_id: str = RUN_DUMMY_PLACEHOLDER
+ id: str = RUN_DUMMY_PLACEHOLDER
+ display_name: str = RUN_DUMMY_PLACEHOLDER
+ notes: str = ""
+ url: str = ""
+ group: str = ""
+ created_at: str = "2000-01-01"
+ user: _DummyUser = field(default_factory=_DummyUser)
+ tags: list = field(default_factory=list)
+ summary: dict = field(default_factory=dict)
+ config: dict = field(default_factory=dict)
+
+ def files(self):
+ return []
+
+
+def _read_ndjson(fname: str) -> Optional[pl.DataFrame]:
+ try:
+ df = pl.read_ndjson(fname)
+ except FileNotFoundError:
+ return None
+ except RuntimeError as e:
+ # No runs previously checked
+ if "empty string is not a valid JSON value" in str(e):
+ return None
+ if "error parsing ndjson" in str(e):
+ return None
+ raise
+
+ return df
+
+
+def _get_run_or_dummy_from_art(art: Artifact, api=None):
+ run = None
+
+ try:
+ run = art.logged_by()
+ except ValueError as e:
+ logger.warning(
+ f"Can't log artifact because run doesn't exist, {art=}, {run=}, {e=}"
+ )
+
+ if run is not None:
+ return run
+
+ query = gql(
+ """
+ query ArtifactCreatedBy(
+ $id: ID!
+ ) {
+ artifact(id: $id) {
+ createdBy {
+ ... on Run {
+ name
+ project {
+ name
+ entityName
+ }
+ }
+ }
+ }
+ }
+ """
+ )
+ response = api.client.execute(query, variable_values={"id": art.id})
+ creator = response.get("artifact", {}).get("createdBy", {})
+ run = _DummyRun(
+ entity=art.entity,
+ project=art.project,
+ run_id=creator.get("name", RUN_DUMMY_PLACEHOLDER),
+ id=creator.get("name", RUN_DUMMY_PLACEHOLDER),
+ )
+ return run
+
+
+def _clear_fname(fname: str) -> None:
+ old_fname = f"{internal.ROOT_DIR}/{fname}"
+ new_fname = f"{internal.ROOT_DIR}/prev_{fname}"
+
+ logger.debug(f"Moving {old_fname=} to {new_fname=}")
+ try:
+ shutil.copy2(old_fname, new_fname)
+ except FileNotFoundError:
+ # this is just to make a copy of the last iteration, so its ok if the src doesn't exist
+ pass
+
+ with open(fname, "w"):
+ pass
+
+
+def _download_art(art: Artifact, root: str) -> Optional[str]:
+ try:
+ with patch("click.echo"):
+ return art.download(root=root, skip_cache=True)
+ except Exception:
+ logger.exception(f"Error downloading artifact {art=}")
+
+
+def _clone_art(art: Artifact, root: Optional[str] = None):
+ if root is None:
+ # Currently, we would only ever clone a src artifact to move it to dst.
+ root = f"{SRC_ART_PATH}/{art.name}"
+
+ if (path := _download_art(art, root=root)) is None:
+ raise ValueError(f"Problem downloading {art=}")
+
+ name, _ = art.name.split(":v")
+
+ # Hack: skip naming validation check for wandb-* types
+ new_art = Artifact(name, ART_DUMMY_PLACEHOLDER_TYPE)
+ new_art._type = art.type
+ new_art._created_at = art.created_at
+
+ new_art._aliases = art.aliases
+ new_art._description = art.description
+
+ with patch("click.echo"):
+ new_art.add_dir(path)
+
+ return new_art
+
+
+def _create_files_if_not_exists() -> None:
+ fnames = [
+ ARTIFACT_ERRORS_FNAME,
+ ARTIFACT_SUCCESSES_FNAME,
+ RUN_ERRORS_FNAME,
+ RUN_SUCCESSES_FNAME,
+ ]
+
+ for fname in fnames:
+ logger.debug(f"Creating {fname=} if not exists")
+ with open(fname, "a"):
+ pass
+
+
+def _merge_dfs(dfs: List[pl.DataFrame]) -> pl.DataFrame:
+ # Ensure there are DataFrames in the list
+ if len(dfs) == 0:
+ return pl.DataFrame()
+
+ if len(dfs) == 1:
+ return dfs[0]
+
+ merged_df = dfs[0]
+ for df in dfs[1:]:
+ merged_df = merged_df.join(df, how="outer", on=["_step"])
+ col_pairs = [
+ (c, f"{c}_right")
+ for c in merged_df.columns
+ if f"{c}_right" in merged_df.columns
+ ]
+ for col, right in col_pairs:
+ new_col = merged_df[col].fill_null(merged_df[right])
+ merged_df = merged_df.with_columns(new_col).drop(right)
+
+ return merged_df
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/internal.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/internal.py
new file mode 100644
index 0000000000000000000000000000000000000000..30a5d2e885b75af1d378098c2d01bc033a716514
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/internal.py
@@ -0,0 +1,241 @@
+from __future__ import annotations
+
+from typing import Any
+
+from wandb.sdk.internal.internal_api import Api as InternalApi
+
+
+class Api:
+ """Internal proxy to the official internal API."""
+
+ # TODO: Move these methods to PublicApi.
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ self._api_args = args
+ self._api_kwargs = kwargs
+ self._api = None
+
+ def __getstate__(self):
+ """Use for serializing.
+
+ self._api is not serializable, so it's dropped
+ """
+ state = self.__dict__.copy()
+ del state["_api"]
+ return state
+
+ def __setstate__(self, state):
+ """Used for deserializing.
+
+ Don't need to set self._api because it's constructed when needed.
+ """
+ self.__dict__.update(state)
+ self._api = None
+
+ @property
+ def api(self) -> InternalApi:
+ # This is a property in order to delay construction of Internal API
+ # for as long as possible. If constructed in constructor, then the
+ # whole InternalAPI is started when simply importing wandb.
+ if self._api is None:
+ self._api = InternalApi(*self._api_args, **self._api_kwargs)
+ return self._api
+
+ @property
+ def api_key(self):
+ return self.api.api_key
+
+ @property
+ def is_authenticated(self):
+ return self.api.access_token is not None or self.api.api_key is not None
+
+ @property
+ def api_url(self):
+ return self.api.api_url
+
+ @property
+ def app_url(self):
+ return self.api.app_url
+
+ @property
+ def default_entity(self):
+ return self.api.default_entity
+
+ @property
+ def git(self):
+ return self.api.git
+
+ def validate_api_key(self) -> bool:
+ """Returns whether the API key stored on initialization is valid."""
+ return self.api.validate_api_key()
+
+ def file_current(self, *args):
+ return self.api.file_current(*args)
+
+ def download_file(self, *args, **kwargs):
+ return self.api.download_file(*args, **kwargs)
+
+ def download_write_file(self, *args, **kwargs):
+ return self.api.download_write_file(*args, **kwargs)
+
+ def set_current_run_id(self, run_id):
+ return self.api.set_current_run_id(run_id)
+
+ def viewer(self):
+ return self.api.viewer()
+
+ def max_cli_version(self):
+ return self.api.max_cli_version()
+
+ def viewer_server_info(self):
+ return self.api.viewer_server_info()
+
+ def list_projects(self, entity=None):
+ return self.api.list_projects(entity=entity)
+
+ def format_project(self, project):
+ return self.api.format_project(project)
+
+ def upsert_project(self, project, id=None, description=None, entity=None):
+ return self.api.upsert_project(
+ project, id=id, description=description, entity=entity
+ )
+
+ def upsert_run(self, *args, **kwargs):
+ return self.api.upsert_run(*args, **kwargs)
+
+ def settings(self, *args, **kwargs):
+ return self.api.settings(*args, **kwargs)
+
+ def clear_setting(
+ self, key: str, globally: bool = False, persist: bool = False
+ ) -> None:
+ return self.api.clear_setting(key, globally, persist)
+
+ def set_setting(
+ self, key: str, value: Any, globally: bool = False, persist: bool = False
+ ) -> None:
+ return self.api.set_setting(key, value, globally, persist)
+
+ def parse_slug(self, *args, **kwargs):
+ return self.api.parse_slug(*args, **kwargs)
+
+ def download_url(self, *args, **kwargs):
+ return self.api.download_url(*args, **kwargs)
+
+ def download_urls(self, *args, **kwargs):
+ return self.api.download_urls(*args, **kwargs)
+
+ def create_anonymous_api_key(self) -> str:
+ return self.api.create_anonymous_api_key()
+
+ def push(self, *args, **kwargs):
+ return self.api.push(*args, **kwargs)
+
+ def sweep(self, *args, **kwargs):
+ return self.api.sweep(*args, **kwargs)
+
+ def upsert_sweep(self, *args, **kwargs):
+ return self.api.upsert_sweep(*args, **kwargs)
+
+ def set_sweep_state(self, *args, **kwargs):
+ return self.api.set_sweep_state(*args, **kwargs)
+
+ def get_sweep_state(self, *args, **kwargs):
+ return self.api.get_sweep_state(*args, **kwargs)
+
+ def stop_sweep(self, *args, **kwargs):
+ return self.api.stop_sweep(*args, **kwargs)
+
+ def cancel_sweep(self, *args, **kwargs):
+ return self.api.cancel_sweep(*args, **kwargs)
+
+ def pause_sweep(self, *args, **kwargs):
+ return self.api.pause_sweep(*args, **kwargs)
+
+ def resume_sweep(self, *args, **kwargs):
+ return self.api.resume_sweep(*args, **kwargs)
+
+ def register_agent(self, *args, **kwargs):
+ return self.api.register_agent(*args, **kwargs)
+
+ def agent_heartbeat(self, *args, **kwargs):
+ return self.api.agent_heartbeat(*args, **kwargs)
+
+ def use_artifact(self, *args, **kwargs):
+ return self.api.use_artifact(*args, **kwargs)
+
+ def create_artifact(self, *args, **kwargs):
+ return self.api.create_artifact(*args, **kwargs)
+
+ def complete_multipart_upload_artifact(self, *args, **kwargs):
+ return self.api.complete_multipart_upload_artifact(*args, **kwargs)
+
+ def run_config(self, *args, **kwargs):
+ return self.api.run_config(*args, **kwargs)
+
+ def upload_file_retry(self, *args, **kwargs):
+ return self.api.upload_file_retry(*args, **kwargs)
+
+ def upload_multipart_file_chunk_retry(self, *args, **kwargs):
+ return self.api.upload_multipart_file_chunk_retry(*args, **kwargs)
+
+ def get_run_info(self, *args, **kwargs):
+ return self.api.get_run_info(*args, **kwargs)
+
+ def get_run_state(self, *args, **kwargs):
+ return self.api.get_run_state(*args, **kwargs)
+
+ def entity_is_team(self, *args, **kwargs):
+ return self.api.entity_is_team(*args, **kwargs)
+
+ def get_project_run_queues(self, *args, **kwargs):
+ return self.api.get_project_run_queues(*args, **kwargs)
+
+ def push_to_run_queue(self, *args, **kwargs):
+ return self.api.push_to_run_queue(*args, **kwargs)
+
+ def pop_from_run_queue(self, *args, **kwargs):
+ return self.api.pop_from_run_queue(*args, **kwargs)
+
+ def ack_run_queue_item(self, *args, **kwargs):
+ return self.api.ack_run_queue_item(*args, **kwargs)
+
+ def create_launch_agent(self, *args, **kwargs):
+ return self.api.create_launch_agent(*args, **kwargs)
+
+ def create_default_resource_config(self, *args, **kwargs):
+ return self.api.create_default_resource_config(*args, **kwargs)
+
+ def create_run_queue(self, *args, **kwargs):
+ return self.api.create_run_queue(*args, **kwargs)
+
+ def upsert_run_queue(self, *args, **kwargs):
+ return self.api.upsert_run_queue(*args, **kwargs)
+
+ def create_custom_chart(self, *args, **kwargs):
+ return self.api.create_custom_chart(*args, **kwargs)
+
+ def update_launch_agent_status(self, *args, **kwargs):
+ return self.api.update_launch_agent_status(*args, **kwargs)
+
+ def launch_agent_introspection(self, *args, **kwargs):
+ return self.api.launch_agent_introspection(*args, **kwargs)
+
+ def fail_run_queue_item_introspection(self, *args, **kwargs):
+ return self.api.fail_run_queue_item_introspection(*args, **kwargs)
+
+ def fail_run_queue_item(self, *args, **kwargs):
+ return self.api.fail_run_queue_item(*args, **kwargs)
+
+ def update_run_queue_item_warning(self, *args, **kwargs):
+ return self.api.update_run_queue_item_warning(*args, **kwargs)
+
+ def get_launch_agent(self, *args, **kwargs):
+ return self.api.get_launch_agent(*args, **kwargs)
+
+ def stop_run(self, *args, **kwargs):
+ return self.api.stop_run(*args, **kwargs)
+
+
+__all__ = ["Api"]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/normalize.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/normalize.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb083a9ef2d43147fdef32a1fcbb8f09c41218f8
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/normalize.py
@@ -0,0 +1,83 @@
+"""normalize."""
+
+from __future__ import annotations
+
+import ast
+import sys
+from functools import wraps
+from typing import Callable, TypeVar
+
+import requests
+from wandb_gql.client import RetryError
+
+from wandb import env
+from wandb.errors import CommError, Error
+from wandb.util import parse_backend_error_messages
+
+_F = TypeVar("_F", bound=Callable)
+
+
+def normalize_exceptions(func: _F) -> _F:
+ """Function decorator for catching common errors and re-raising as wandb.Error."""
+
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ message = "Whoa, you found a bug."
+ try:
+ return func(*args, **kwargs)
+
+ except requests.HTTPError as error:
+ errors = parse_backend_error_messages(error.response)
+ status = error.response.status_code
+
+ if errors:
+ message = f"HTTP {status}: {'; '.join(errors)}"
+ elif error.response.text:
+ message = f"HTTP {status}: {error.response.text}"
+ elif error.response.reason:
+ # Visually different to distinguish backend errors from
+ # standard HTTP status descriptions.
+ message = f"HTTP {status} ({error.response.reason})"
+ else:
+ message = f"HTTP {status}"
+
+ raise CommError(message, error)
+
+ except RetryError as err:
+ if (
+ "response" in dir(err.last_exception)
+ and err.last_exception.response is not None
+ ):
+ try:
+ message = err.last_exception.response.json().get(
+ "errors", [{"message": message}]
+ )[0]["message"]
+ except ValueError:
+ message = err.last_exception.response.text
+ else:
+ message = err.last_exception
+
+ if env.is_debug():
+ raise err.last_exception.with_traceback(sys.exc_info()[2])
+ else:
+ raise CommError(message, err.last_exception).with_traceback(
+ sys.exc_info()[2]
+ )
+ except Error:
+ raise
+ except Exception as err:
+ # gql raises server errors with dict's as strings...
+ if len(err.args) > 0:
+ payload = err.args[0]
+ else:
+ payload = err
+ if str(payload).startswith("{"):
+ message = ast.literal_eval(str(payload))["message"]
+ else:
+ message = str(err)
+ if env.is_debug():
+ raise
+ else:
+ raise CommError(message, err).with_traceback(sys.exc_info()[2])
+
+ return wrapper
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/paginator.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/paginator.py
new file mode 100644
index 0000000000000000000000000000000000000000..d858b82aa0ecd63f22ff8273a046deec7d6d66ee
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/paginator.py
@@ -0,0 +1,138 @@
+from __future__ import annotations
+
+from abc import abstractmethod
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ ClassVar,
+ Iterator,
+ Mapping,
+ Protocol,
+ Sized,
+ TypeVar,
+ overload,
+)
+
+import wandb
+
+if TYPE_CHECKING:
+ from wandb_graphql.language.ast import Document
+
+T = TypeVar("T")
+
+
+# Structural type hint for the client instance
+class _Client(Protocol):
+ def execute(self, *args: Any, **kwargs: Any) -> dict[str, Any]: ...
+
+
+class Paginator(Iterator[T]):
+ """An iterator for paginated objects from GraphQL requests."""
+
+ QUERY: ClassVar[Document | None] = None
+
+ def __init__(
+ self,
+ client: _Client,
+ variables: Mapping[str, Any],
+ per_page: int = 50, # We don't allow unbounded paging
+ ):
+ self.client: _Client = client
+
+ # shallow copy partly guards against mutating the original input
+ self.variables: dict[str, Any] = dict(variables)
+
+ self.per_page: int = per_page
+ self.objects: list[T] = []
+ self.index: int = -1
+ self.last_response: object | None = None
+
+ def __iter__(self) -> Iterator[T]:
+ self.index = -1
+ return self
+
+ @property
+ @abstractmethod
+ def more(self) -> bool:
+ """Whether there are more pages to be fetched."""
+ raise NotImplementedError
+
+ @property
+ @abstractmethod
+ def cursor(self) -> str | None:
+ """The start cursor to use for the next fetched page."""
+ raise NotImplementedError
+
+ @abstractmethod
+ def convert_objects(self) -> list[T]:
+ """Convert the last fetched response data into the iterated objects."""
+ raise NotImplementedError
+
+ def update_variables(self) -> None:
+ """Update the query variables for the next page fetch."""
+ self.variables.update({"perPage": self.per_page, "cursor": self.cursor})
+
+ def _update_response(self) -> None:
+ """Fetch and store the response data for the next page."""
+ self.last_response = self.client.execute(
+ self.QUERY, variable_values=self.variables
+ )
+
+ def _load_page(self) -> bool:
+ """Fetch the next page, if any, returning True and storing the response if there was one."""
+ if not self.more:
+ return False
+ self.update_variables()
+ self._update_response()
+ self.objects.extend(self.convert_objects())
+ return True
+
+ @overload
+ def __getitem__(self, index: int) -> T: ...
+ @overload
+ def __getitem__(self, index: slice) -> list[T]: ...
+
+ def __getitem__(self, index: int | slice) -> T | list[T]:
+ loaded = True
+ stop = index.stop if isinstance(index, slice) else index
+ while loaded and stop > len(self.objects) - 1:
+ loaded = self._load_page()
+ return self.objects[index]
+
+ def __next__(self) -> T:
+ self.index += 1
+ if len(self.objects) <= self.index:
+ if not self._load_page():
+ raise StopIteration
+ if len(self.objects) <= self.index:
+ raise StopIteration
+ return self.objects[self.index]
+
+ next = __next__
+
+
+class SizedPaginator(Paginator[T], Sized):
+ """A Paginator for objects with a known total count."""
+
+ @property
+ def length(self) -> int | None:
+ wandb.termwarn(
+ (
+ "`.length` is deprecated and will be removed in a future version. "
+ "Use `len(...)` instead."
+ ),
+ repeat=False,
+ )
+ return len(self)
+
+ def __len__(self) -> int:
+ if self._length is None:
+ self._load_page()
+ if self._length is None:
+ raise ValueError("Object doesn't provide length")
+ return self._length
+
+ @property
+ @abstractmethod
+ def _length(self) -> int | None:
+ raise NotImplementedError
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..697235c9b25e219d6196f682868d8b1f99c5d5ca
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/__init__.py
@@ -0,0 +1,78 @@
+__all__ = (
+ "Api",
+ "RetryingClient", # doc:exclude
+ "requests", # doc:exclude
+ "ArtifactCollection",
+ "ArtifactCollections",
+ "ArtifactFiles",
+ "Artifacts",
+ "ArtifactType",
+ "ArtifactTypes",
+ "RunArtifacts",
+ "Automations",
+ "File",
+ "Files",
+ "HistoryScan", # doc:exclude
+ "SampledHistoryScan", # doc:exclude
+ "SlackIntegrations", # doc:exclude
+ "WebhookIntegrations", # doc:exclude
+ "Job", # doc:exclude
+ "QueuedRun", # doc:exclude
+ "RunQueue", # doc:exclude
+ "RunQueueAccessType", # doc:exclude
+ "RunQueuePrioritizationMode", # doc:exclude
+ "RunQueueResourceType", # doc:exclude
+ "Project",
+ "Projects",
+ "Sweeps",
+ "QueryGenerator", # doc:exclude
+ "Registry",
+ "Registries", # doc:exclude
+ "BetaReport",
+ "PanelMetricsHelper", # doc:exclude
+ "PythonMongoishQueryGenerator", # doc:exclude
+ "Reports",
+ "Run",
+ "Runs",
+ "Sweep",
+ "Member",
+ "Team",
+ "User",
+)
+
+
+from wandb.apis.public.api import Api, RetryingClient, requests
+from wandb.apis.public.artifacts import (
+ ArtifactCollection,
+ ArtifactCollections,
+ ArtifactFiles,
+ Artifacts,
+ ArtifactType,
+ ArtifactTypes,
+ RunArtifacts,
+)
+from wandb.apis.public.automations import Automations
+from wandb.apis.public.files import FILE_FRAGMENT, File, Files
+from wandb.apis.public.history import HistoryScan, SampledHistoryScan
+from wandb.apis.public.integrations import SlackIntegrations, WebhookIntegrations
+from wandb.apis.public.jobs import (
+ Job,
+ QueuedRun,
+ RunQueue,
+ RunQueueAccessType,
+ RunQueuePrioritizationMode,
+ RunQueueResourceType,
+)
+from wandb.apis.public.projects import PROJECT_FRAGMENT, Project, Projects, Sweeps
+from wandb.apis.public.query_generator import QueryGenerator
+from wandb.apis.public.registries import Registries, Registry
+from wandb.apis.public.reports import (
+ BetaReport,
+ PanelMetricsHelper,
+ PythonMongoishQueryGenerator,
+ Reports,
+)
+from wandb.apis.public.runs import RUN_FRAGMENT, Run, Runs
+from wandb.apis.public.sweeps import SWEEP_FRAGMENT, Sweep
+from wandb.apis.public.teams import Member, Team
+from wandb.apis.public.users import User
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/api.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..323256ab86bb26135bcf18b7f2a2b900f2d54204
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/api.py
@@ -0,0 +1,2513 @@
+"""Use the Public API to export or update data that you have saved to W&B.
+
+Before using this API, you'll want to log data from your script — check the
+[Quickstart](https://docs.wandb.ai/quickstart) for more details.
+
+You might use the Public API to
+ - update metadata or metrics for an experiment after it has been completed,
+ - pull down your results as a dataframe for post-hoc analysis in a Jupyter notebook, or
+ - check your saved model artifacts for those tagged as `ready-to-deploy`.
+
+For more on using the Public API, check out [our guide](https://docs.wandb.com/guides/track/public-api-guide).
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import urllib
+from http import HTTPStatus
+from typing import TYPE_CHECKING, Any, Iterator, Literal
+
+import requests
+from pydantic import ValidationError
+from typing_extensions import Unpack
+from wandb_gql import Client, gql
+from wandb_gql.client import RetryError
+
+import wandb
+from wandb import env, util
+from wandb._analytics import tracked
+from wandb._iterutils import one
+from wandb._strutils import nameof
+from wandb.apis import public
+from wandb.apis.normalize import normalize_exceptions
+from wandb.apis.public.const import RETRY_TIMEDELTA
+from wandb.apis.public.registries import Registries, Registry
+from wandb.apis.public.registries._utils import fetch_org_entity_from_organization
+from wandb.apis.public.utils import (
+ PathType,
+ fetch_org_from_settings_or_entity,
+ gql_compat,
+ parse_org_from_registry_path,
+)
+from wandb.proto.wandb_deprecated import Deprecated
+from wandb.proto.wandb_internal_pb2 import ServerFeature
+from wandb.sdk import wandb_login
+from wandb.sdk.artifacts._validators import (
+ ArtifactPath,
+ FullArtifactPath,
+ is_artifact_registry_project,
+)
+from wandb.sdk.internal.internal_api import Api as InternalApi
+from wandb.sdk.internal.thread_local_settings import _thread_local_api_settings
+from wandb.sdk.launch.utils import LAUNCH_DEFAULT_PROJECT
+from wandb.sdk.lib import retry, runid
+from wandb.sdk.lib.deprecate import deprecate
+from wandb.sdk.lib.gql_request import GraphQLSession
+
+if TYPE_CHECKING:
+ from wandb.automations import (
+ ActionType,
+ Automation,
+ EventType,
+ Integration,
+ NewAutomation,
+ SlackIntegration,
+ WebhookIntegration,
+ )
+ from wandb.automations._utils import WriteAutomationsKwargs
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ from .artifacts import (
+ ArtifactCollection,
+ ArtifactCollections,
+ Artifacts,
+ ArtifactType,
+ ArtifactTypes,
+ )
+ from .teams import Team
+ from .users import User
+
+logger = logging.getLogger(__name__)
+
+
+class RetryingClient:
+ """A GraphQL client that retries requests on failure.
+
+
+ """
+
+ INFO_QUERY = gql(
+ """
+ query ServerInfo{
+ serverInfo {
+ cliVersionInfo
+ latestLocalVersionInfo {
+ outOfDate
+ latestVersionString
+ versionOnThisInstanceString
+ }
+ }
+ }
+ """
+ )
+
+ def __init__(self, client: Client):
+ self._server_info = None
+ self._client = client
+
+ @property
+ def app_url(self):
+ return util.app_url(self._client.transport.url.replace("/graphql", "")) + "/"
+
+ @retry.retriable(
+ retry_timedelta=RETRY_TIMEDELTA,
+ check_retry_fn=util.no_retry_auth,
+ retryable_exceptions=(RetryError, requests.RequestException),
+ )
+ def execute(
+ self, *args, **kwargs
+ ): # User not encouraged to use this class directly
+ try:
+ return self._client.execute(*args, **kwargs)
+ except requests.exceptions.ReadTimeout:
+ if "timeout" not in kwargs:
+ timeout = self._client.transport.default_timeout
+ wandb.termwarn(
+ f"A graphql request initiated by the public wandb API timed out (timeout={timeout} sec). "
+ f"Create a new API with an integer timeout larger than {timeout}, e.g., `api = wandb.Api(timeout={timeout + 10})` "
+ f"to increase the graphql timeout."
+ )
+ raise
+
+ @property
+ def server_info(self):
+ if self._server_info is None:
+ self._server_info = self.execute(self.INFO_QUERY).get("serverInfo")
+ return self._server_info
+
+ def version_supported(
+ self, min_version: str
+ ) -> bool: # User not encouraged to use this class directly
+ from packaging.version import parse
+
+ return parse(min_version) <= parse(
+ self.server_info["cliVersionInfo"]["max_cli_version"]
+ )
+
+
+class Api:
+ """Used for querying the W&B server.
+
+ Examples:
+ ```python
+ import wandb
+
+ wandb.Api()
+ ```
+ """
+
+ _HTTP_TIMEOUT = env.get_http_timeout(19)
+ DEFAULT_ENTITY_QUERY = gql(
+ """
+ query Viewer{
+ viewer {
+ id
+ entity
+ }
+ }
+ """
+ )
+
+ VIEWER_QUERY = gql(
+ """
+ query Viewer{
+ viewer {
+ id
+ flags
+ entity
+ username
+ email
+ admin
+ apiKeys {
+ edges {
+ node {
+ id
+ name
+ description
+ }
+ }
+ }
+ teams {
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ }
+ }
+ """
+ )
+ USERS_QUERY = gql(
+ """
+ query SearchUsers($query: String) {
+ users(query: $query) {
+ edges {
+ node {
+ id
+ flags
+ entity
+ admin
+ email
+ deletedAt
+ username
+ apiKeys {
+ edges {
+ node {
+ id
+ name
+ description
+ }
+ }
+ }
+ teams {
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+ )
+
+ CREATE_PROJECT = gql(
+ """
+ mutation upsertModel(
+ $description: String
+ $entityName: String
+ $id: String
+ $name: String
+ $framework: String
+ $access: String
+ $views: JSONString
+ ) {
+ upsertModel(
+ input: {
+ description: $description
+ entityName: $entityName
+ id: $id
+ name: $name
+ framework: $framework
+ access: $access
+ views: $views
+ }
+ ) {
+ project {
+ id
+ name
+ entityName
+ description
+ access
+ views
+ }
+ model {
+ id
+ name
+ entityName
+ description
+ access
+ views
+ }
+ inserted
+ }
+ }
+ """
+ )
+
+ def __init__(
+ self,
+ overrides: dict[str, Any] | None = None,
+ timeout: int | None = None,
+ api_key: str | None = None,
+ ) -> None:
+ """Initialize the API.
+
+ Args:
+ overrides: You can set `base_url` if you are
+ using a W&B server other than `https://api.wandb.ai`. You can also
+ set defaults for `entity`, `project`, and `run`.
+ timeout: HTTP timeout in seconds for API requests. If not
+ specified, the default timeout will be used.
+ api_key: API key to use for authentication. If not provided,
+ the API key from the current environment or configuration will be used.
+ Prompts for an API key if none is provided
+ or configured in the environment.
+ """
+ self.settings = InternalApi().settings()
+
+ _overrides = overrides or {}
+ self.settings.update(_overrides)
+ self.settings["base_url"] = self.settings["base_url"].rstrip("/")
+ if "organization" in _overrides:
+ self.settings["organization"] = _overrides["organization"]
+ if "username" in _overrides and "entity" not in _overrides:
+ wandb.termwarn(
+ 'Passing "username" to Api is deprecated. please use "entity" instead.'
+ )
+ self.settings["entity"] = _overrides["username"]
+
+ if _thread_local_api_settings.cookies is None:
+ self.api_key = self._load_api_key(
+ base_url=self.settings["base_url"],
+ init_api_key=api_key,
+ )
+ wandb_login._verify_login(
+ key=self.api_key,
+ base_url=self.settings["base_url"],
+ )
+
+ self._viewer = None
+ self._projects = {}
+ self._runs = {}
+ self._sweeps = {}
+ self._reports = {}
+ self._default_entity = None
+ self._timeout = timeout if timeout is not None else self._HTTP_TIMEOUT
+ auth = None
+ if not _thread_local_api_settings.cookies:
+ auth = ("api", self.api_key)
+ proxies = self.settings.get("_proxies") or json.loads(
+ os.environ.get("WANDB__PROXIES", "{}")
+ )
+ self._base_client = Client(
+ transport=GraphQLSession(
+ headers={
+ "User-Agent": self.user_agent,
+ "Use-Admin-Privileges": "true",
+ **(_thread_local_api_settings.headers or {}),
+ },
+ use_json=True,
+ # this timeout won't apply when the DNS lookup fails. in that case, it will be 60s
+ # https://bugs.python.org/issue22889
+ timeout=self._timeout,
+ auth=auth,
+ url="{}/graphql".format(self.settings["base_url"]),
+ cookies=_thread_local_api_settings.cookies,
+ proxies=proxies,
+ )
+ )
+ self._client = RetryingClient(self._base_client)
+ self._sentry = wandb.analytics.sentry.Sentry()
+ self._configure_sentry()
+
+ def _load_api_key(
+ self,
+ base_url: str,
+ init_api_key: str | None = None,
+ ) -> str:
+ """Attempts to load a configured API key or prompt if one is not found.
+
+ The API key is loaded in the following order:
+ 1. Thread local api key
+ 2. User explicitly provided api key
+ 3. Environment variable
+ 4. Netrc file
+ 5. Prompt for api key using wandb.login
+ """
+ # just use thread local api key if it's set
+ if _thread_local_api_settings.api_key:
+ return _thread_local_api_settings.api_key
+ if init_api_key is not None:
+ return init_api_key
+ if os.getenv("WANDB_API_KEY"):
+ return os.environ["WANDB_API_KEY"]
+
+ auth = requests.utils.get_netrc_auth(base_url)
+ if auth:
+ return auth[-1]
+
+ _, prompted_key = wandb_login._login(
+ host=base_url,
+ key=None,
+ # We will explicitly verify the key later
+ verify=False,
+ _silent=(
+ self.settings.get("silent", False) or self.settings.get("quiet", False)
+ ),
+ update_api_key=False,
+ _disable_warning=True,
+ )
+ return prompted_key
+
+ def _configure_sentry(self) -> None:
+ try:
+ viewer = self.viewer
+ except (ValueError, requests.RequestException):
+ # we need the viewer to configure the entity, and user email
+ return
+
+ email = viewer.email if viewer else None
+ entity = self.default_entity
+
+ self._sentry.configure_scope(
+ tags={
+ "entity": entity,
+ "email": email,
+ },
+ )
+
+ def create_project(self, name: str, entity: str) -> None:
+ """Create a new project.
+
+ Args:
+ name: The name of the new project.
+ entity: The entity of the new project.
+ """
+ self.client.execute(self.CREATE_PROJECT, {"entityName": entity, "name": name})
+
+ def create_run(
+ self,
+ *,
+ run_id: str | None = None,
+ project: str | None = None,
+ entity: str | None = None,
+ ) -> public.Run:
+ """Create a new run.
+
+ Args:
+ run_id: The ID to assign to the run. If not specified, W&B
+ creates a random ID.
+ project: The project where to log the run to. If no project is specified,
+ log the run to a project called "Uncategorized".
+ entity: The entity that owns the project. If no entity is
+ specified, log the run to the default entity.
+
+ Returns:
+ The newly created `Run`.
+ """
+ if entity is None:
+ entity = self.default_entity
+ return public.Run.create(self, run_id=run_id, project=project, entity=entity)
+
+ def create_run_queue(
+ self,
+ name: str,
+ type: public.RunQueueResourceType,
+ entity: str | None = None,
+ prioritization_mode: public.RunQueuePrioritizationMode | None = None,
+ config: dict | None = None,
+ template_variables: dict | None = None,
+ ) -> public.RunQueue:
+ """Create a new run queue in W&B Launch.
+
+ Args:
+ name: Name of the queue to create
+ type: Type of resource to be used for the queue. One of
+ "local-container", "local-process", "kubernetes","sagemaker",
+ or "gcp-vertex".
+ entity: Name of the entity to create the queue. If `None`, use
+ the configured or default entity.
+ prioritization_mode: Version of prioritization to use.
+ Either "V0" or `None`.
+ config: Default resource configuration to be used for the queue.
+ Use handlebars (eg. `{{var}}`) to specify template variables.
+ template_variables: A dictionary of template variable schemas to
+ use with the config.
+
+ Returns:
+ The newly created `RunQueue`.
+
+ Raises:
+ `ValueError` if any of the parameters are invalid
+ `wandb.Error` on wandb API errors
+ """
+ # TODO(np): Need to check server capabilities for this feature
+ # 0. assert params are valid/normalized
+ if entity is None:
+ entity = self.settings["entity"] or self.default_entity
+ if entity is None:
+ raise ValueError(
+ "entity must be passed as a parameter, or set in settings"
+ )
+
+ if len(name) == 0:
+ raise ValueError("name must be non-empty")
+ if len(name) > 64:
+ raise ValueError("name must be less than 64 characters")
+
+ if type not in [
+ "local-container",
+ "local-process",
+ "kubernetes",
+ "sagemaker",
+ "gcp-vertex",
+ ]:
+ raise ValueError(
+ "resource_type must be one of 'local-container', 'local-process', 'kubernetes', 'sagemaker', or 'gcp-vertex'"
+ )
+
+ if prioritization_mode:
+ prioritization_mode = prioritization_mode.upper()
+ if prioritization_mode not in ["V0"]:
+ raise ValueError("prioritization_mode must be 'V0' if present")
+
+ if config is None:
+ config = {}
+
+ # 1. create required default launch project in the entity
+ self.create_project(LAUNCH_DEFAULT_PROJECT, entity)
+
+ api = InternalApi(
+ default_settings={
+ "entity": entity,
+ "project": self.project(LAUNCH_DEFAULT_PROJECT),
+ },
+ retry_timedelta=RETRY_TIMEDELTA,
+ )
+
+ # 2. create default resource config, receive config id
+ config_json = json.dumps({"resource_args": {type: config}})
+ create_config_result = api.create_default_resource_config(
+ entity, type, config_json, template_variables
+ )
+ if not create_config_result["success"]:
+ raise wandb.Error("failed to create default resource config")
+ config_id = create_config_result["defaultResourceConfigID"]
+
+ # 3. create run queue
+ create_queue_result = api.create_run_queue(
+ entity,
+ LAUNCH_DEFAULT_PROJECT,
+ name,
+ "PROJECT",
+ prioritization_mode,
+ config_id,
+ )
+ if not create_queue_result["success"]:
+ raise wandb.Error("failed to create run queue")
+
+ return public.RunQueue(
+ client=self.client,
+ name=name,
+ entity=entity,
+ prioritization_mode=prioritization_mode,
+ _access="PROJECT",
+ _default_resource_config_id=config_id,
+ _default_resource_config=config,
+ )
+
+ def create_custom_chart(
+ self,
+ entity: str,
+ name: str,
+ display_name: str,
+ spec_type: Literal["vega2"],
+ access: Literal["private", "public"],
+ spec: str | dict,
+ ) -> str:
+ """Create a custom chart preset and return its id.
+
+ Args:
+ entity: The entity (user or team) that owns the chart
+ name: Unique identifier for the chart preset
+ display_name: Human-readable name shown in the UI
+ spec_type: Type of specification. Must be "vega2" for Vega-Lite v2 specifications.
+ access: Access level for the chart:
+ - "private": Chart is only accessible to the entity that created it
+ - "public": Chart is publicly accessible
+ spec: The Vega/Vega-Lite specification as a dictionary or JSON string
+
+ Returns:
+ The ID of the created chart preset in the format "entity/name"
+
+ Raises:
+ wandb.Error: If chart creation fails
+ UnsupportedError: If the server doesn't support custom charts
+
+ Example:
+ ```python
+ import wandb
+
+ api = wandb.Api()
+
+ # Define a simple bar chart specification
+ vega_spec = {
+ "$schema": "https://vega.github.io/schema/vega-lite/v6.json",
+ "mark": "bar",
+ "data": {"name": "wandb"},
+ "encoding": {
+ "x": {"field": "${field:x}", "type": "ordinal"},
+ "y": {"field": "${field:y}", "type": "quantitative"},
+ },
+ }
+
+ # Create the custom chart
+ chart_id = api.create_custom_chart(
+ entity="my-team",
+ name="my-bar-chart",
+ display_name="My Custom Bar Chart",
+ spec_type="vega2",
+ access="private",
+ spec=vega_spec,
+ )
+
+ # Use with wandb.plot_table()
+ chart = wandb.plot_table(
+ vega_spec_name=chart_id,
+ data_table=my_table,
+ fields={"x": "category", "y": "value"},
+ )
+ ```
+ """
+ # Convert user-facing lowercase access to backend uppercase
+ backend_access = access.upper()
+
+ api = InternalApi(retry_timedelta=RETRY_TIMEDELTA)
+ result = api.create_custom_chart(
+ entity=entity,
+ name=name,
+ display_name=display_name,
+ spec_type=spec_type,
+ access=backend_access,
+ spec=spec,
+ )
+ if result is None or result.get("chart") is None:
+ raise wandb.Error("failed to create custom chart")
+ return result["chart"]["id"]
+
+ def upsert_run_queue(
+ self,
+ name: str,
+ resource_config: dict,
+ resource_type: public.RunQueueResourceType,
+ entity: str | None = None,
+ template_variables: dict | None = None,
+ external_links: dict | None = None,
+ prioritization_mode: public.RunQueuePrioritizationMode | None = None,
+ ):
+ """Upsert a run queue in W&B Launch.
+
+ Args:
+ name: Name of the queue to create
+ entity: Optional name of the entity to create the queue. If `None`,
+ use the configured or default entity.
+ resource_config: Optional default resource configuration to be used
+ for the queue. Use handlebars (eg. `{{var}}`) to specify
+ template variables.
+ resource_type: Type of resource to be used for the queue. One of
+ "local-container", "local-process", "kubernetes", "sagemaker",
+ or "gcp-vertex".
+ template_variables: A dictionary of template variable schemas to
+ be used with the config.
+ external_links: Optional dictionary of external links to be used
+ with the queue.
+ prioritization_mode: Optional version of prioritization to use.
+ Either "V0" or None
+
+ Returns:
+ The upserted `RunQueue`.
+
+ Raises:
+ ValueError if any of the parameters are invalid
+ wandb.Error on wandb API errors
+ """
+ if entity is None:
+ entity = self.settings["entity"] or self.default_entity
+ if entity is None:
+ raise ValueError(
+ "entity must be passed as a parameter, or set in settings"
+ )
+
+ if len(name) == 0:
+ raise ValueError("name must be non-empty")
+ if len(name) > 64:
+ raise ValueError("name must be less than 64 characters")
+
+ prioritization_mode = prioritization_mode or "DISABLED"
+ prioritization_mode = prioritization_mode.upper()
+ if prioritization_mode not in ["V0", "DISABLED"]:
+ raise ValueError(
+ "prioritization_mode must be 'V0' or 'DISABLED' if present"
+ )
+
+ if resource_type not in [
+ "local-container",
+ "local-process",
+ "kubernetes",
+ "sagemaker",
+ "gcp-vertex",
+ ]:
+ raise ValueError(
+ "resource_type must be one of 'local-container', 'local-process', 'kubernetes', 'sagemaker', or 'gcp-vertex'"
+ )
+
+ self.create_project(LAUNCH_DEFAULT_PROJECT, entity)
+ api = InternalApi(
+ default_settings={
+ "entity": entity,
+ "project": self.project(LAUNCH_DEFAULT_PROJECT),
+ },
+ retry_timedelta=RETRY_TIMEDELTA,
+ )
+ # User provides external_links as a dict with name: url format
+ # but backend stores it as a list of dicts with url and label keys.
+ external_links = external_links or {}
+ external_links = {
+ "links": [
+ {
+ "label": key,
+ "url": value,
+ }
+ for key, value in external_links.items()
+ ]
+ }
+ upsert_run_queue_result = api.upsert_run_queue(
+ name,
+ entity,
+ resource_type,
+ {"resource_args": {resource_type: resource_config}},
+ template_variables=template_variables,
+ external_links=external_links,
+ prioritization_mode=prioritization_mode,
+ )
+ if not upsert_run_queue_result["success"]:
+ raise wandb.Error("failed to create run queue")
+ schema_errors = (
+ upsert_run_queue_result.get("configSchemaValidationErrors") or []
+ )
+ for error in schema_errors:
+ wandb.termwarn(f"resource config validation: {error}")
+
+ return public.RunQueue(
+ client=self.client,
+ name=name,
+ entity=entity,
+ )
+
+ def create_user(self, email: str, admin: bool | None = False) -> User:
+ """Create a new user.
+
+ Args:
+ email: The email address of the user.
+ admin: Set user as a global instance administrator.
+
+ Returns:
+ A `User` object.
+ """
+ from .users import User
+
+ return User.create(self, email, admin)
+
+ def sync_tensorboard(self, root_dir, run_id=None, project=None, entity=None):
+ """Sync a local directory containing tfevent files to wandb."""
+ from wandb.sync import SyncManager # TODO: circular import madness
+
+ run_id = run_id or runid.generate_id()
+ project = project or self.settings.get("project") or "uncategorized"
+ entity = entity or self.default_entity
+ # TODO: pipe through log_path to inform the user how to debug
+ sm = SyncManager(
+ project=project,
+ entity=entity,
+ run_id=run_id,
+ mark_synced=False,
+ app_url=self.client.app_url,
+ view=False,
+ verbose=False,
+ sync_tensorboard=True,
+ )
+ sm.add(root_dir)
+ sm.start()
+ while not sm.is_done():
+ _ = sm.poll()
+ return self.run("/".join([entity, project, run_id]))
+
+ @property
+ def client(self) -> RetryingClient:
+ """Returns the client object."""
+ return self._client
+
+ @property
+ def user_agent(self) -> str:
+ """Returns W&B public user agent."""
+ return "W&B Public Client {}".format(wandb.__version__)
+
+ @property
+ def default_entity(self) -> str | None:
+ """Returns the default W&B entity."""
+ if self._default_entity is None:
+ res = self._client.execute(self.DEFAULT_ENTITY_QUERY)
+ self._default_entity = (res.get("viewer") or {}).get("entity")
+ return self._default_entity
+
+ @property
+ def viewer(self) -> User:
+ """Returns the viewer object.
+
+ Raises:
+ ValueError: If viewer data is not able to be fetched from W&B.
+ requests.RequestException: If an error occurs while making the graphql request.
+ """
+ from .users import User
+
+ if self._viewer is None:
+ viewer = self._client.execute(self.VIEWER_QUERY).get("viewer")
+
+ if viewer is None:
+ raise ValueError(
+ "Unable to fetch user data from W&B,"
+ " please verify your API key is valid."
+ )
+
+ self._viewer = User(self._client, viewer)
+ self._default_entity = self._viewer.entity
+ return self._viewer
+
+ def flush(self):
+ """Flush the local cache.
+
+ The api object keeps a local cache of runs, so if the state of the run
+ may change while executing your script you must clear the local cache
+ with `api.flush()` to get the latest values associated with the run.
+ """
+ self._runs = {}
+
+ def from_path(self, path: str):
+ """Return a run, sweep, project or report from a path.
+
+ Args:
+ path: The path to the project, run, sweep or report
+
+ Returns:
+ A `Project`, `Run`, `Sweep`, or `BetaReport` instance.
+
+ Raises:
+ `wandb.Error` if path is invalid or the object doesn't exist.
+
+ Examples:
+ In the proceeding code snippets "project", "team", "run_id", "sweep_id",
+ and "report_name" are placeholders for the project, team, run ID,
+ sweep ID, and the name of a specific report, respectively.
+
+ ```python
+ import wandb
+
+ api = wandb.Api()
+
+ project = api.from_path("project")
+ team_project = api.from_path("team/project")
+ run = api.from_path("team/project/runs/run_id")
+ sweep = api.from_path("team/project/sweeps/sweep_id")
+ report = api.from_path("team/project/reports/report_name")
+ ```
+ """
+ parts = path.strip("/ ").split("/")
+ if len(parts) == 1:
+ return self.project(path)
+ elif len(parts) == 2:
+ return self.project(parts[1], parts[0])
+ elif len(parts) == 3:
+ return self.run(path)
+ elif len(parts) == 4:
+ if parts[2].startswith("run"):
+ return self.run(path)
+ elif parts[2].startswith("sweep"):
+ return self.sweep(path)
+ elif parts[2].startswith("report"):
+ if "--" not in parts[-1]:
+ if "-" in parts[-1]:
+ raise wandb.Error(
+ "Invalid report path, should be team/project/reports/Name--XXXX"
+ )
+ else:
+ parts[-1] = "--" + parts[-1]
+ name, id = parts[-1].split("--")
+ return public.BetaReport(
+ self.client,
+ {
+ "displayName": urllib.parse.unquote(name.replace("-", " ")),
+ "id": id,
+ "spec": "{}",
+ },
+ parts[0],
+ parts[1],
+ )
+ raise wandb.Error(
+ "Invalid path, should be TEAM/PROJECT/TYPE/ID where TYPE is runs, sweeps, or reports"
+ )
+
+ def _parse_project_path(self, path):
+ """Return project and entity for project specified by path."""
+ project = self.settings["project"] or "uncategorized"
+ entity = self.settings["entity"] or self.default_entity
+ if path is None:
+ return entity, project
+ parts = path.split("/", 1)
+ if len(parts) == 1:
+ return entity, path
+ return parts
+
+ def _parse_path(self, path):
+ """Parse url, filepath, or docker paths.
+
+ Allows paths in the following formats:
+ - url: entity/project/runs/id
+ - path: entity/project/id
+ - docker: entity/project:id
+
+ Entity is optional and will fall back to the current logged-in user.
+ """
+ project = self.settings["project"] or "uncategorized"
+ entity = self.settings["entity"] or self.default_entity
+ parts = (
+ path.replace("/runs/", "/").replace("/sweeps/", "/").strip("/ ").split("/")
+ )
+ if ":" in parts[-1]:
+ id = parts[-1].split(":")[-1]
+ parts[-1] = parts[-1].split(":")[0]
+ elif parts[-1]:
+ id = parts[-1]
+ if len(parts) == 1 and project != "uncategorized":
+ pass
+ elif len(parts) > 1:
+ project = parts[1]
+ if entity and id == project:
+ project = parts[0]
+ else:
+ entity = parts[0]
+ if len(parts) == 3:
+ entity = parts[0]
+ else:
+ project = parts[0]
+ return entity, project, id
+
+ def _parse_artifact_path(self, path):
+ """Return project, entity and artifact name for project specified by path."""
+ project = self.settings["project"] or "uncategorized"
+ entity = self.settings["entity"] or self.default_entity
+ if path is None:
+ return entity, project
+
+ parsed = ArtifactPath.from_str(path)
+ parsed = parsed.with_defaults(prefix=entity, project=project)
+ return parsed.prefix, parsed.project, parsed.name
+
+ def projects(
+ self, entity: str | None = None, per_page: int = 200
+ ) -> public.Projects:
+ """Get projects for a given entity.
+
+ Args:
+ entity: Name of the entity requested. If None, will fall back to
+ the default entity passed to `Api`. If no default entity,
+ will raise a `ValueError`.
+ per_page: Sets the page size for query pagination. If set to `None`,
+ use the default size. Usually there is no reason to change this.
+
+ Returns:
+ A `Projects` object which is an iterable collection of `Project`objects.
+ """
+ if entity is None:
+ entity = self.settings["entity"] or self.default_entity
+ if entity is None:
+ raise ValueError(
+ "entity must be passed as a parameter, or set in settings"
+ )
+ if entity not in self._projects:
+ self._projects[entity] = public.Projects(
+ self.client, entity, per_page=per_page
+ )
+ return self._projects[entity]
+
+ def project(self, name: str, entity: str | None = None) -> public.Project:
+ """Return the `Project` with the given name (and entity, if given).
+
+ Args:
+ name: The project name.
+ entity: Name of the entity requested. If None, will fall back to the
+ default entity passed to `Api`. If no default entity, will
+ raise a `ValueError`.
+
+ Returns:
+ A `Project` object.
+ """
+ # For registry artifacts, capture potential org user inputted before resolving entity
+ org = entity if is_artifact_registry_project(name) else ""
+
+ if entity is None:
+ entity = self.settings["entity"] or self.default_entity
+
+ # For registry artifacts, resolve org-based entity
+ if is_artifact_registry_project(name):
+ settings_entity = self.settings["entity"] or self.default_entity
+ entity = InternalApi()._resolve_org_entity_name(
+ entity=settings_entity, organization=org
+ )
+ return public.Project(self.client, entity, name, {})
+
+ def reports(
+ self, path: str = "", name: str | None = None, per_page: int = 50
+ ) -> public.Reports:
+ """Get reports for a given project path.
+
+ Note: `wandb.Api.reports()` API is in beta and will likely change in
+ future releases.
+
+ Args:
+ path: The path to the project the report resides in. Specify the
+ entity that created the project as a prefix followed by a
+ forward slash.
+ name: Name of the report requested.
+ per_page: Sets the page size for query pagination. If set to
+ `None`, use the default size. Usually there is no reason to
+ change this.
+
+ Returns:
+ A `Reports` object which is an iterable collection of
+ `BetaReport` objects.
+
+ Examples:
+ ```python
+ import wandb
+
+ wandb.Api.reports("entity/project")
+ ```
+ """
+ entity, project, _ = self._parse_path(path + "/fake_run")
+
+ if name:
+ name = urllib.parse.unquote(name)
+ key = "/".join([entity, project, str(name)])
+ else:
+ key = "/".join([entity, project])
+
+ if key not in self._reports:
+ self._reports[key] = public.Reports(
+ self.client,
+ public.Project(self.client, entity, project, {}),
+ name=name,
+ per_page=per_page,
+ )
+ return self._reports[key]
+
+ def create_team(self, team: str, admin_username: str | None = None) -> Team:
+ """Create a new team.
+
+ Args:
+ team: The name of the team
+ admin_username: Username of the admin user of the team.
+ Defaults to the current user.
+
+ Returns:
+ A `Team` object.
+ """
+ from .teams import Team
+
+ return Team.create(self, team, admin_username)
+
+ def team(self, team: str) -> Team:
+ """Return the matching `Team` with the given name.
+
+ Args:
+ team: The name of the team.
+
+ Returns:
+ A `Team` object.
+ """
+ from .teams import Team
+
+ return Team(self.client, team)
+
+ def user(self, username_or_email: str) -> User | None:
+ """Return a user from a username or email address.
+
+ This function only works for local administrators. Use `api.viewer`
+ to get your own user object.
+
+ Args:
+ username_or_email: The username or email address of the user.
+
+ Returns:
+ A `User` object or None if a user is not found.
+ """
+ from .users import User
+
+ res = self._client.execute(self.USERS_QUERY, {"query": username_or_email})
+ if len(res["users"]["edges"]) == 0:
+ return None
+ elif len(res["users"]["edges"]) > 1:
+ wandb.termwarn(
+ "Found multiple users, returning the first user matching {}".format(
+ username_or_email
+ )
+ )
+ return User(self._client, res["users"]["edges"][0]["node"])
+
+ def users(self, username_or_email: str) -> list[User]:
+ """Return all users from a partial username or email address query.
+
+ This function only works for local administrators. Use `api.viewer`
+ to get your own user object.
+
+ Args:
+ username_or_email: The prefix or suffix of the user you want to find.
+
+ Returns:
+ An array of `User` objects.
+ """
+ from .users import User
+
+ res = self._client.execute(self.USERS_QUERY, {"query": username_or_email})
+ return [User(self._client, edge["node"]) for edge in res["users"]["edges"]]
+
+ def runs(
+ self,
+ path: str | None = None,
+ filters: dict[str, Any] | None = None,
+ order: str = "+created_at",
+ per_page: int = 50,
+ include_sweeps: bool = True,
+ lazy: bool = True,
+ ):
+ """Returns a `Runs` object, which lazily iterates over `Run` objects.
+
+ Fields you can filter by include:
+ - `createdAt`: The timestamp when the run was created. (in ISO 8601 format, e.g. "2023-01-01T12:00:00Z")
+ - `displayName`: The human-readable display name of the run. (e.g. "eager-fox-1")
+ - `duration`: The total runtime of the run in seconds.
+ - `group`: The group name used to organize related runs together.
+ - `host`: The hostname where the run was executed.
+ - `jobType`: The type of job or purpose of the run.
+ - `name`: The unique identifier of the run. (e.g. "a1b2cdef")
+ - `state`: The current state of the run.
+ - `tags`: The tags associated with the run.
+ - `username`: The username of the user who initiated the run
+
+ Additionally, you can filter by items in the run config or summary metrics.
+ Such as `config.experiment_name`, `summary_metrics.loss`, etc.
+
+ For more complex filtering, you can use MongoDB query operators.
+ For details, see: https://docs.mongodb.com/manual/reference/operator/query
+ The following operations are supported:
+ - `$and`
+ - `$or`
+ - `$nor`
+ - `$eq`
+ - `$ne`
+ - `$gt`
+ - `$gte`
+ - `$lt`
+ - `$lte`
+ - `$in`
+ - `$nin`
+ - `$exists`
+ - `$regex`
+
+
+
+ Args:
+ path: (str) path to project, should be in the form: "entity/project"
+ filters: (dict) queries for specific runs using the MongoDB query language.
+ You can filter by run properties such as config.key, summary_metrics.key, state, entity, createdAt, etc.
+ For example: `{"config.experiment_name": "foo"}` would find runs with a config entry
+ of experiment name set to "foo"
+ order: (str) Order can be `created_at`, `heartbeat_at`, `config.*.value`, or `summary_metrics.*`.
+ If you prepend order with a + order is ascending (default).
+ If you prepend order with a - order is descending.
+ The default order is run.created_at from oldest to newest.
+ per_page: (int) Sets the page size for query pagination.
+ include_sweeps: (bool) Whether to include the sweep runs in the results.
+ lazy: (bool) Whether to use lazy loading for faster performance.
+ When True (default), only essential run metadata is loaded initially.
+ Heavy fields like config, summaryMetrics, and systemMetrics are loaded
+ on-demand when accessed. Set to False for full data upfront.
+
+ Returns:
+ A `Runs` object, which is an iterable collection of `Run` objects.
+
+ Examples:
+ ```python
+ # Find runs in project where config.experiment_name has been set to "foo"
+ api.runs(path="my_entity/project", filters={"config.experiment_name": "foo"})
+ ```
+
+ ```python
+ # Find runs in project where config.experiment_name has been set to "foo" or "bar"
+ api.runs(
+ path="my_entity/project",
+ filters={
+ "$or": [
+ {"config.experiment_name": "foo"},
+ {"config.experiment_name": "bar"},
+ ]
+ },
+ )
+ ```
+
+ ```python
+ # Find runs in project where config.experiment_name matches a regex
+ # (anchors are not supported)
+ api.runs(
+ path="my_entity/project",
+ filters={"config.experiment_name": {"$regex": "b.*"}},
+ )
+ ```
+
+ ```python
+ # Find runs in project where the run name matches a regex
+ # (anchors are not supported)
+ api.runs(
+ path="my_entity/project", filters={"display_name": {"$regex": "^foo.*"}}
+ )
+ ```
+
+ ```python
+ # Find runs in project sorted by ascending loss
+ api.runs(path="my_entity/project", order="+summary_metrics.loss")
+ ```
+ """
+ entity, project = self._parse_project_path(path)
+ filters = filters or {}
+ key = (path or "") + str(filters) + str(order)
+
+ # Check if we have cached results
+ if self._runs.get(key):
+ cached_runs = self._runs[key]
+ # If requesting full data but cached data is lazy, upgrade it
+ if not lazy and cached_runs._lazy:
+ cached_runs.upgrade_to_full()
+ return cached_runs
+
+ # Create new Runs object
+ self._runs[key] = public.Runs(
+ self.client,
+ entity,
+ project,
+ filters=filters,
+ order=order,
+ per_page=per_page,
+ include_sweeps=include_sweeps,
+ lazy=lazy,
+ )
+ return self._runs[key]
+
+ @normalize_exceptions
+ def run(self, path=""):
+ """Return a single run by parsing path in the form `entity/project/run_id`.
+
+ Args:
+ path: Path to run in the form `entity/project/run_id`.
+ If `api.entity` is set, this can be in the form `project/run_id`
+ and if `api.project` is set this can just be the run_id.
+
+ Returns:
+ A `Run` object.
+ """
+ entity, project, run_id = self._parse_path(path)
+ if not self._runs.get(path):
+ # Individual runs should load full data by default
+ self._runs[path] = public.Run(
+ self.client, entity, project, run_id, lazy=False
+ )
+ return self._runs[path]
+
+ def queued_run(
+ self,
+ entity: str,
+ project: str,
+ queue_name: str,
+ run_queue_item_id: str,
+ project_queue=None,
+ priority=None,
+ ):
+ """Return a single queued run based on the path.
+
+ Parses paths of the form `entity/project/queue_id/run_queue_item_id`.
+ """
+ return public.QueuedRun(
+ self.client,
+ entity,
+ project,
+ queue_name,
+ run_queue_item_id,
+ project_queue=project_queue,
+ priority=priority,
+ )
+
+ def run_queue(
+ self,
+ entity: str,
+ name: str,
+ ):
+ """Return the named `RunQueue` for entity.
+
+ See `Api.create_run_queue` for more information on how to create a run queue.
+ """
+ return public.RunQueue(
+ self.client,
+ name,
+ entity,
+ )
+
+ @normalize_exceptions
+ def sweep(self, path=""):
+ """Return a sweep by parsing path in the form `entity/project/sweep_id`.
+
+ Args:
+ path: Path to sweep in the form entity/project/sweep_id.
+ If `api.entity` is set, this can be in the form
+ project/sweep_id and if `api.project` is set
+ this can just be the sweep_id.
+
+ Returns:
+ A `Sweep` object.
+ """
+ entity, project, sweep_id = self._parse_path(path)
+ if not self._sweeps.get(path):
+ self._sweeps[path] = public.Sweep(self.client, entity, project, sweep_id)
+ return self._sweeps[path]
+
+ @normalize_exceptions
+ def artifact_types(self, project: str | None = None) -> ArtifactTypes:
+ """Returns a collection of matching artifact types.
+
+ Args:
+ project: The project name or path to filter on.
+
+ Returns:
+ An iterable `ArtifactTypes` object.
+ """
+ from .artifacts import ArtifactTypes
+
+ project_path = project
+ entity, project = self._parse_project_path(project_path)
+ # If its a Registry project, the entity is considered to be an org instead
+ if is_artifact_registry_project(project):
+ settings_entity = self.settings["entity"] or self.default_entity
+ org = parse_org_from_registry_path(project_path, PathType.PROJECT)
+ entity = InternalApi()._resolve_org_entity_name(
+ entity=settings_entity, organization=org
+ )
+ return ArtifactTypes(self.client, entity, project)
+
+ @normalize_exceptions
+ def artifact_type(self, type_name: str, project: str | None = None) -> ArtifactType:
+ """Returns the matching `ArtifactType`.
+
+ Args:
+ type_name: The name of the artifact type to retrieve.
+ project: If given, a project name or path to filter on.
+
+ Returns:
+ An `ArtifactType` object.
+ """
+ from .artifacts import ArtifactType
+
+ project_path = project
+ entity, project = self._parse_project_path(project_path)
+ # If its an Registry artifact, the entity is an org instead
+ if is_artifact_registry_project(project):
+ org = parse_org_from_registry_path(project_path, PathType.PROJECT)
+ settings_entity = self.settings["entity"] or self.default_entity
+ entity = InternalApi()._resolve_org_entity_name(
+ entity=settings_entity, organization=org
+ )
+ return ArtifactType(self.client, entity, project, type_name)
+
+ @normalize_exceptions
+ def artifact_collections(
+ self, project_name: str, type_name: str, per_page: int = 50
+ ) -> ArtifactCollections:
+ """Returns a collection of matching artifact collections.
+
+ Args:
+ project_name: The name of the project to filter on.
+ type_name: The name of the artifact type to filter on.
+ per_page: Sets the page size for query pagination. None will use the default size.
+ Usually there is no reason to change this.
+
+ Returns:
+ An iterable `ArtifactCollections` object.
+ """
+ from .artifacts import ArtifactCollections
+
+ entity, project = self._parse_project_path(project_name)
+ # If iterating through Registry project, the entity is considered to be an org instead
+ if is_artifact_registry_project(project):
+ org = parse_org_from_registry_path(project_name, PathType.PROJECT)
+ settings_entity = self.settings["entity"] or self.default_entity
+ entity = InternalApi()._resolve_org_entity_name(
+ entity=settings_entity, organization=org
+ )
+ return ArtifactCollections(
+ self.client, entity, project, type_name, per_page=per_page
+ )
+
+ @normalize_exceptions
+ def artifact_collection(self, type_name: str, name: str) -> ArtifactCollection:
+ """Returns a single artifact collection by type.
+
+ You can use the returned `ArtifactCollection` object to retrieve
+ information about specific artifacts in that collection, and more.
+
+ Args:
+ type_name: The type of artifact collection to fetch.
+ name: An artifact collection name. Optionally append the entity
+ that logged the artifact as a prefix followed by a forward
+ slash.
+
+ Returns:
+ An `ArtifactCollection` object.
+
+ Examples:
+ In the proceeding code snippet "type", "entity", "project", and
+ "artifact_name" are placeholders for the collection type, your W&B
+ entity, name of the project the artifact is in, and the name of
+ the artifact, respectively.
+
+ ```python
+ import wandb
+
+ collections = wandb.Api().artifact_collection(
+ type_name="type", name="entity/project/artifact_name"
+ )
+
+ # Get the first artifact in the collection
+ artifact_example = collections.artifacts()[0]
+
+ # Download the contents of the artifact to the specified root directory.
+ artifact_example.download()
+ ```
+ """
+ from .artifacts import ArtifactCollection
+
+ entity, project, collection_name = self._parse_artifact_path(name)
+ # If its an Registry artifact, the entity is considered to be an org instead
+ if is_artifact_registry_project(project):
+ org = parse_org_from_registry_path(name, PathType.ARTIFACT)
+ settings_entity = self.settings["entity"] or self.default_entity
+ entity = InternalApi()._resolve_org_entity_name(
+ entity=settings_entity, organization=org
+ )
+
+ if entity is None:
+ raise ValueError(
+ "Could not determine entity. Please include the entity as part of the collection name path."
+ )
+
+ return ArtifactCollection(
+ self.client, entity, project, collection_name, type_name
+ )
+
+ @normalize_exceptions
+ def artifact_versions(self, type_name, name, per_page=50):
+ """Deprecated. Use `Api.artifacts(type_name, name)` method instead."""
+ deprecate(
+ field_name=Deprecated.api__artifact_versions,
+ warning_message=(
+ "Api.artifact_versions(type_name, name) is deprecated, "
+ "use Api.artifacts(type_name, name) instead."
+ ),
+ )
+ return self.artifacts(type_name, name, per_page=per_page)
+
+ @normalize_exceptions
+ def artifacts(
+ self,
+ type_name: str,
+ name: str,
+ per_page: int = 50,
+ tags: list[str] | None = None,
+ ) -> Artifacts:
+ """Return an `Artifacts` collection.
+
+ Args:
+ type_name: The type of artifacts to fetch.
+ name: The artifact's collection name. Optionally append the
+ entity that logged the artifact as a prefix followed by
+ a forward slash.
+ per_page: Sets the page size for query pagination. If set to
+ `None`, use the default size. Usually there is no reason
+ to change this.
+ tags: Only return artifacts with all of these tags.
+
+ Returns:
+ An iterable `Artifacts` object.
+
+ Examples:
+ In the proceeding code snippet, "type", "entity", "project", and
+ "artifact_name" are placeholders for the artifact type, W&B entity,
+ name of the project the artifact was logged to,
+ and the name of the artifact, respectively.
+
+ ```python
+ import wandb
+
+ wandb.Api().artifacts(type_name="type", name="entity/project/artifact_name")
+ ```
+ """
+ from .artifacts import Artifacts
+
+ entity, project, collection_name = self._parse_artifact_path(name)
+ # If its an Registry project, the entity is considered to be an org instead
+ if is_artifact_registry_project(project):
+ org = parse_org_from_registry_path(name, PathType.ARTIFACT)
+ settings_entity = self.settings["entity"] or self.default_entity
+ entity = InternalApi()._resolve_org_entity_name(
+ entity=settings_entity, organization=org
+ )
+ return Artifacts(
+ self.client,
+ entity,
+ project,
+ collection_name,
+ type_name,
+ per_page=per_page,
+ tags=tags,
+ )
+
+ @normalize_exceptions
+ def _artifact(
+ self, name: str, type: str | None = None, enable_tracking: bool = False
+ ) -> Artifact:
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ if name is None:
+ raise ValueError("You must specify name= to fetch an artifact.")
+ entity, project, artifact_name = self._parse_artifact_path(name)
+
+ # If its an Registry artifact, the entity is an org instead
+ if is_artifact_registry_project(project):
+ organization = (
+ name.split("/")[0]
+ if name.count("/") == 2
+ else self.settings["organization"]
+ )
+ # set entity to match the settings since in above code it was potentially set to an org
+ settings_entity = self.settings["entity"] or self.default_entity
+ # Registry artifacts are under the org entity. Because we offer a shorthand and alias for this path,
+ # we need to fetch the org entity to for the user behind the scenes.
+ entity = InternalApi()._resolve_org_entity_name(
+ entity=settings_entity, organization=organization
+ )
+
+ if entity is None:
+ raise ValueError(
+ "Could not determine entity. Please include the entity as part of the artifact name path."
+ )
+
+ path = FullArtifactPath(prefix=entity, project=project, name=artifact_name)
+ artifact = Artifact._from_name(
+ path=path,
+ client=self.client,
+ enable_tracking=enable_tracking,
+ )
+ if type is not None and artifact.type != type:
+ raise ValueError(
+ f"type {type} specified but this artifact is of type {artifact.type}"
+ )
+ return artifact
+
+ @normalize_exceptions
+ def artifact(self, name: str, type: str | None = None):
+ """Returns a single artifact.
+
+ Args:
+ name: The artifact's name. The name of an artifact resembles a
+ filepath that consists, at a minimum, the name of the project
+ the artifact was logged to, the name of the artifact, and the
+ artifact's version or alias. Optionally append the entity that
+ logged the artifact as a prefix followed by a forward slash.
+ If no entity is specified in the name, the Run or API
+ setting's entity is used.
+ type: The type of artifact to fetch.
+
+ Returns:
+ An `Artifact` object.
+
+ Raises:
+ ValueError: If the artifact name is not specified.
+ ValueError: If the artifact type is specified but does not
+ match the type of the fetched artifact.
+
+ Examples:
+ In the proceeding code snippets "entity", "project", "artifact",
+ "version", and "alias" are placeholders for your W&B entity, name
+ of the project the artifact is in, the name of the artifact,
+ and artifact's version, respectively.
+
+ ```python
+ import wandb
+
+ # Specify the project, artifact's name, and the artifact's alias
+ wandb.Api().artifact(name="project/artifact:alias")
+
+ # Specify the project, artifact's name, and a specific artifact version
+ wandb.Api().artifact(name="project/artifact:version")
+
+ # Specify the entity, project, artifact's name, and the artifact's alias
+ wandb.Api().artifact(name="entity/project/artifact:alias")
+
+ # Specify the entity, project, artifact's name, and a specific artifact version
+ wandb.Api().artifact(name="entity/project/artifact:version")
+ ```
+
+ Note:
+ This method is intended for external use only. Do not call `api.artifact()` within the wandb repository code.
+ """
+ return self._artifact(name=name, type=type, enable_tracking=True)
+
+ @normalize_exceptions
+ def job(self, name: str | None, path: str | None = None) -> public.Job:
+ """Return a `Job` object.
+
+ Args:
+ name: The name of the job.
+ path: The root path to download the job artifact.
+
+ Returns:
+ A `Job` object.
+ """
+ if name is None:
+ raise ValueError("You must specify name= to fetch a job.")
+ elif name.count("/") != 2 or ":" not in name:
+ raise ValueError(
+ "Invalid job specification. A job must be of the form: //:"
+ )
+ return public.Job(self, name, path)
+
+ @normalize_exceptions
+ def list_jobs(self, entity: str, project: str) -> list[dict[str, Any]]:
+ """Return a list of jobs, if any, for the given entity and project.
+
+ Args:
+ entity: The entity for the listed jobs.
+ project: The project for the listed jobs.
+
+ Returns:
+ A list of matching jobs.
+ """
+ if entity is None:
+ raise ValueError("Specify an entity when listing jobs")
+ if project is None:
+ raise ValueError("Specify a project when listing jobs")
+
+ query = gql(
+ """
+ query ArtifactOfType(
+ $entityName: String!,
+ $projectName: String!,
+ $artifactTypeName: String!,
+ ) {
+ project(name: $projectName, entityName: $entityName) {
+ artifactType(name: $artifactTypeName) {
+ artifactCollections {
+ edges {
+ node {
+ artifacts {
+ edges {
+ node {
+ id
+ state
+ aliases {
+ alias
+ }
+ artifactSequence {
+ name
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+ )
+
+ try:
+ artifact_query = self._client.execute(
+ query,
+ {
+ "projectName": project,
+ "entityName": entity,
+ "artifactTypeName": "job",
+ },
+ )
+
+ if not artifact_query or not artifact_query["project"]:
+ wandb.termerror(
+ f"Project: '{project}' not found in entity: '{entity}' or access denied."
+ )
+ return []
+
+ if artifact_query["project"]["artifactType"] is None:
+ return []
+
+ artifacts = artifact_query["project"]["artifactType"][
+ "artifactCollections"
+ ]["edges"]
+
+ return [x["node"]["artifacts"] for x in artifacts]
+ except requests.exceptions.HTTPError:
+ return False
+
+ @normalize_exceptions
+ def artifact_exists(self, name: str, type: str | None = None) -> bool:
+ """Whether an artifact version exists within the specified project and entity.
+
+ Args:
+ name: The name of artifact. Add the artifact's entity and project
+ as a prefix. Append the version or the alias of the artifact
+ with a colon. If the entity or project is not specified,
+ W&B uses override parameters if populated. Otherwise, the
+ entity is pulled from the user settings and the project is
+ set to "Uncategorized".
+ type: The type of artifact.
+
+ Returns:
+ True if the artifact version exists, False otherwise.
+
+ Examples:
+ In the proceeding code snippets "entity", "project", "artifact",
+ "version", and "alias" are placeholders for your W&B entity, name of
+ the project the artifact is in, the name of the artifact, and
+ artifact's version, respectively.
+
+ ```python
+ import wandb
+
+ wandb.Api().artifact_exists("entity/project/artifact:version")
+ wandb.Api().artifact_exists("entity/project/artifact:alias")
+ ```
+
+ """
+ try:
+ self._artifact(name, type)
+ except wandb.errors.CommError as e:
+ if isinstance(e.exc, requests.Timeout):
+ raise
+ return False
+ return True
+
+ @normalize_exceptions
+ def artifact_collection_exists(self, name: str, type: str) -> bool:
+ """Whether an artifact collection exists within a specified project and entity.
+
+ Args:
+ name: An artifact collection name. Optionally append the
+ entity that logged the artifact as a prefix followed by
+ a forward slash. If entity or project is not specified,
+ infer the collection from the override params if they exist.
+ Otherwise, entity is pulled from the user settings and project
+ will default to "uncategorized".
+ type: The type of artifact collection.
+
+ Returns:
+ True if the artifact collection exists, False otherwise.
+
+ Examples:
+ In the proceeding code snippet "type", and "collection_name" refer to the type
+ of the artifact collection and the name of the collection, respectively.
+
+ ```python
+ import wandb
+
+ wandb.Api.artifact_collection_exists(type="type", name="collection_name")
+ ```
+ """
+ try:
+ self.artifact_collection(type, name)
+ except wandb.errors.CommError as e:
+ if isinstance(e.exc, requests.Timeout):
+ raise
+ return False
+ return True
+
+ @tracked
+ def registries(
+ self,
+ organization: str | None = None,
+ filter: dict[str, Any] | None = None,
+ ) -> Registries:
+ """Returns a lazy iterator of `Registry` objects.
+
+ Use the iterator to search and filter registries, collections,
+ or artifact versions across your organization's registry.
+
+ Args:
+ organization: (str, optional) The organization of the registry to fetch.
+ If not specified, use the organization specified in the user's settings.
+ filter: (dict, optional) MongoDB-style filter to apply to each object in the lazy registry iterator.
+ Fields available to filter for registries are
+ `name`, `description`, `created_at`, `updated_at`.
+ Fields available to filter for collections are
+ `name`, `tag`, `description`, `created_at`, `updated_at`
+ Fields available to filter for versions are
+ `tag`, `alias`, `created_at`, `updated_at`, `metadata`
+
+ Returns:
+ A lazy iterator of `Registry` objects.
+
+ Examples:
+ Find all registries with the names that contain "model"
+
+ ```python
+ import wandb
+
+ api = wandb.Api() # specify an org if your entity belongs to multiple orgs
+ api.registries(filter={"name": {"$regex": "model"}})
+ ```
+
+ Find all collections in the registries with the name "my_collection" and the tag "my_tag"
+
+ ```python
+ api.registries().collections(filter={"name": "my_collection", "tag": "my_tag"})
+ ```
+
+ Find all artifact versions in the registries with a collection name that contains "my_collection" and a version that has the alias "best"
+
+ ```python
+ api.registries().collections(
+ filter={"name": {"$regex": "my_collection"}}
+ ).versions(filter={"alias": "best"})
+ ```
+
+ Find all artifact versions in the registries that contain "model" and have the tag "prod" or alias "best"
+
+ ```python
+ api.registries(filter={"name": {"$regex": "model"}}).versions(
+ filter={"$or": [{"tag": "prod"}, {"alias": "best"}]}
+ )
+ ```
+ """
+ if not InternalApi()._server_supports(ServerFeature.ARTIFACT_REGISTRY_SEARCH):
+ raise RuntimeError(
+ "Registry search API is not enabled on this wandb server version. "
+ "Please upgrade your server version or contact support at support@wandb.com."
+ )
+
+ organization = organization or fetch_org_from_settings_or_entity(
+ self.settings, self.default_entity
+ )
+ return Registries(self.client, organization, filter)
+
+ @tracked
+ def registry(self, name: str, organization: str | None = None) -> Registry:
+ """Return a registry given a registry name.
+
+ Args:
+ name: The name of the registry. This is without the `wandb-registry-`
+ prefix.
+ organization: The organization of the registry.
+ If no organization is set in the settings, the organization will be
+ fetched from the entity if the entity only belongs to one
+ organization.
+
+ Returns:
+ A registry object.
+
+ Examples:
+ Fetch and update a registry
+
+ ```python
+ import wandb
+
+ api = wandb.Api()
+ registry = api.registry(name="my-registry", organization="my-org")
+ registry.description = "This is an updated description"
+ registry.save()
+ ```
+ """
+ if not InternalApi()._server_supports(ServerFeature.ARTIFACT_REGISTRY_SEARCH):
+ raise RuntimeError(
+ "api.registry() is not enabled on this wandb server version. "
+ "Please upgrade your server version or contact support at support@wandb.com."
+ )
+ organization = organization or fetch_org_from_settings_or_entity(
+ self.settings, self.default_entity
+ )
+ org_entity = fetch_org_entity_from_organization(self.client, organization)
+ registry = Registry(self.client, organization, org_entity, name)
+ registry.load()
+ return registry
+
+ @tracked
+ def create_registry(
+ self,
+ name: str,
+ visibility: Literal["organization", "restricted"],
+ organization: str | None = None,
+ description: str | None = None,
+ artifact_types: list[str] | None = None,
+ ) -> Registry:
+ """Create a new registry.
+
+ Args:
+ name: The name of the registry. Name must be unique within the organization.
+ visibility: The visibility of the registry.
+ organization: Anyone in the organization can view this registry. You can
+ edit their roles later from the settings in the UI.
+ restricted: Only invited members via the UI can access this registry.
+ Public sharing is disabled.
+ organization: The organization of the registry.
+ If no organization is set in the settings, the organization will be
+ fetched from the entity if the entity only belongs to one organization.
+ description: The description of the registry.
+ artifact_types: The accepted artifact types of the registry. A type is no
+ more than 128 characters and do not include characters `/` or `:`. If
+ not specified, all types are accepted.
+ Allowed types added to the registry cannot be removed later.
+
+ Returns:
+ A registry object.
+
+ Examples:
+ ```python
+ import wandb
+
+ api = wandb.Api()
+ registry = api.create_registry(
+ name="my-registry",
+ visibility="restricted",
+ organization="my-org",
+ description="This is a test registry",
+ artifact_types=["model"],
+ )
+ ```
+ """
+ if not InternalApi()._server_supports(
+ ServerFeature.INCLUDE_ARTIFACT_TYPES_IN_REGISTRY_CREATION
+ ):
+ raise RuntimeError(
+ "create_registry api is not enabled on this wandb server version. "
+ "Please upgrade your server version or contact support at support@wandb.com."
+ )
+
+ organization = organization or fetch_org_from_settings_or_entity(
+ self.settings, self.default_entity
+ )
+
+ try:
+ existing_registry = self.registry(name=name, organization=organization)
+ except ValueError:
+ existing_registry = None
+ if existing_registry:
+ raise ValueError(
+ f"Registry {name!r} already exists in organization {organization!r},"
+ " please use a different name."
+ )
+
+ return Registry.create(
+ self.client,
+ organization,
+ name,
+ visibility,
+ description,
+ artifact_types,
+ )
+
+ @tracked
+ def integrations(
+ self,
+ entity: str | None = None,
+ *,
+ per_page: int = 50,
+ ) -> Iterator[Integration]:
+ """Return an iterator of all integrations for an entity.
+
+ Args:
+ entity: The entity (e.g. team name) for which to
+ fetch integrations. If not provided, the user's default entity
+ will be used.
+ per_page: Number of integrations to fetch per page.
+ Defaults to 50. Usually there is no reason to change this.
+
+ Yields:
+ Iterator[SlackIntegration | WebhookIntegration]: An iterator of any supported integrations.
+ """
+ from wandb.apis.public.integrations import Integrations
+
+ params = {"entityName": entity or self.default_entity}
+ return Integrations(client=self.client, variables=params, per_page=per_page)
+
+ @tracked
+ def webhook_integrations(
+ self, entity: str | None = None, *, per_page: int = 50
+ ) -> Iterator[WebhookIntegration]:
+ """Returns an iterator of webhook integrations for an entity.
+
+ Args:
+ entity: The entity (e.g. team name) for which to
+ fetch integrations. If not provided, the user's default entity
+ will be used.
+ per_page: Number of integrations to fetch per page.
+ Defaults to 50. Usually there is no reason to change this.
+
+ Yields:
+ Iterator[WebhookIntegration]: An iterator of webhook integrations.
+
+ Examples:
+ Get all registered webhook integrations for the team "my-team":
+
+ ```python
+ import wandb
+
+ api = wandb.Api()
+ webhook_integrations = api.webhook_integrations(entity="my-team")
+ ```
+
+ Find only webhook integrations that post requests to "https://my-fake-url.com":
+
+ ```python
+ webhook_integrations = api.webhook_integrations(entity="my-team")
+ my_webhooks = [
+ ig
+ for ig in webhook_integrations
+ if ig.url_endpoint.startswith("https://my-fake-url.com")
+ ]
+ ```
+ """
+ from wandb.apis.public.integrations import WebhookIntegrations
+
+ params = {"entityName": entity or self.default_entity}
+ return WebhookIntegrations(
+ client=self.client, variables=params, per_page=per_page
+ )
+
+ @tracked
+ def slack_integrations(
+ self, *, entity: str | None = None, per_page: int = 50
+ ) -> Iterator[SlackIntegration]:
+ """Returns an iterator of Slack integrations for an entity.
+
+ Args:
+ entity: The entity (e.g. team name) for which to
+ fetch integrations. If not provided, the user's default entity
+ will be used.
+ per_page: Number of integrations to fetch per page.
+ Defaults to 50. Usually there is no reason to change this.
+
+ Yields:
+ Iterator[SlackIntegration]: An iterator of Slack integrations.
+
+ Examples:
+ Get all registered Slack integrations for the team "my-team":
+
+ ```python
+ import wandb
+
+ api = wandb.Api()
+ slack_integrations = api.slack_integrations(entity="my-team")
+ ```
+
+ Find only Slack integrations that post to channel names starting with "team-alerts-":
+
+ ```python
+ slack_integrations = api.slack_integrations(entity="my-team")
+ team_alert_integrations = [
+ ig
+ for ig in slack_integrations
+ if ig.channel_name.startswith("team-alerts-")
+ ]
+ ```
+ """
+ from wandb.apis.public.integrations import SlackIntegrations
+
+ params = {"entityName": entity or self.default_entity}
+ return SlackIntegrations(
+ client=self.client, variables=params, per_page=per_page
+ )
+
+ def _supports_automation(
+ self,
+ *,
+ event: EventType | None = None,
+ action: ActionType | None = None,
+ ) -> bool:
+ """Returns whether the server recognizes the automation event and/or action."""
+ from wandb.automations._utils import (
+ ALWAYS_SUPPORTED_ACTIONS,
+ ALWAYS_SUPPORTED_EVENTS,
+ )
+
+ api = InternalApi()
+ supports_event = (
+ (event is None)
+ or (event in ALWAYS_SUPPORTED_EVENTS)
+ or api._server_supports(f"AUTOMATION_EVENT_{event.value}")
+ )
+ supports_action = (
+ (action is None)
+ or (action in ALWAYS_SUPPORTED_ACTIONS)
+ or api._server_supports(f"AUTOMATION_ACTION_{action.value}")
+ )
+ return supports_event and supports_action
+
+ def _omitted_automation_fragments(self) -> set[str]:
+ """Returns the names of unsupported automation-related fragments.
+
+ Older servers won't recognize newer GraphQL types, so a valid request may
+ unnecessarily error out because it won't recognize fragments defined on those types.
+
+ So e.g. if a server does not support `NO_OP` action types, then the following need to be
+ removed from the body of the GraphQL request:
+
+ - Fragment definition:
+ ```
+ fragment NoOpActionFields on NoOpTriggeredAction {
+ noOp
+ }
+ ```
+
+ - Fragment spread in selection set:
+ ```
+ {
+ ...NoOpActionFields
+ # ... other fields ...
+ }
+ ```
+ """
+ from wandb.automations import ActionType
+ from wandb.automations._generated import (
+ GenericWebhookActionFields,
+ NoOpActionFields,
+ NotificationActionFields,
+ QueueJobActionFields,
+ )
+
+ # Note: we can't currently define this as a constant outside the method
+ # and still keep it nearby in this module, because it relies on pydantic v2-only imports
+ fragment_names: dict[ActionType, str] = {
+ ActionType.NO_OP: nameof(NoOpActionFields),
+ ActionType.QUEUE_JOB: nameof(QueueJobActionFields),
+ ActionType.NOTIFICATION: nameof(NotificationActionFields),
+ ActionType.GENERIC_WEBHOOK: nameof(GenericWebhookActionFields),
+ }
+
+ return set(
+ name
+ for action in ActionType
+ if (not self._supports_automation(action=action))
+ and (name := fragment_names.get(action))
+ )
+
+ @tracked
+ def automation(
+ self,
+ name: str,
+ *,
+ entity: str | None = None,
+ ) -> Automation:
+ """Returns the only Automation matching the parameters.
+
+ Args:
+ name: The name of the automation to fetch.
+ entity: The entity to fetch the automation for.
+
+ Raises:
+ ValueError: If zero or multiple Automations match the search criteria.
+
+ Examples:
+ Get an existing automation named "my-automation":
+
+ ```python
+ import wandb
+
+ api = wandb.Api()
+ automation = api.automation(name="my-automation")
+ ```
+
+ Get an existing automation named "other-automation", from the entity "my-team":
+
+ ```python
+ automation = api.automation(name="other-automation", entity="my-team")
+ ```
+ """
+ return one(
+ self.automations(entity=entity, name=name),
+ too_short=ValueError("No automations found"),
+ too_long=ValueError("Multiple automations found"),
+ )
+
+ @tracked
+ def automations(
+ self,
+ entity: str | None = None,
+ *,
+ name: str | None = None,
+ per_page: int = 50,
+ ) -> Iterator[Automation]:
+ """Returns an iterator over all Automations that match the given parameters.
+
+ If no parameters are provided, the returned iterator will contain all
+ Automations that the user has access to.
+
+ Args:
+ entity: The entity to fetch the automations for.
+ name: The name of the automation to fetch.
+ per_page: The number of automations to fetch per page.
+ Defaults to 50. Usually there is no reason to change this.
+
+ Returns:
+ A list of automations.
+
+ Examples:
+ Fetch all existing automations for the entity "my-team":
+
+ ```python
+ import wandb
+
+ api = wandb.Api()
+ automations = api.automations(entity="my-team")
+ ```
+ """
+ from wandb.apis.public.automations import Automations
+ from wandb.automations._generated import (
+ GET_AUTOMATIONS_BY_ENTITY_GQL,
+ GET_AUTOMATIONS_GQL,
+ )
+
+ # For now, we need to use different queries depending on whether entity is given
+ variables = {"entityName": entity}
+ if entity is None:
+ gql_str = GET_AUTOMATIONS_GQL # Automations for viewer
+ else:
+ gql_str = GET_AUTOMATIONS_BY_ENTITY_GQL # Automations for entity
+
+ # If needed, rewrite the GraphQL field selection set to omit unsupported fields/fragments/types
+ omit_fragments = self._omitted_automation_fragments()
+ query = gql_compat(gql_str, omit_fragments=omit_fragments)
+ iterator = Automations(
+ client=self.client, variables=variables, per_page=per_page, _query=query
+ )
+
+ # FIXME: this is crude, move this client-side filtering logic into backend
+ if name is not None:
+ iterator = filter(lambda x: x.name == name, iterator)
+ yield from iterator
+
+ @normalize_exceptions
+ @tracked
+ def create_automation(
+ self,
+ obj: NewAutomation,
+ *,
+ fetch_existing: bool = False,
+ **kwargs: Unpack[WriteAutomationsKwargs],
+ ) -> Automation:
+ """Create a new Automation.
+
+ Args:
+ obj:
+ The automation to create.
+ fetch_existing:
+ If True, and a conflicting automation already exists, attempt
+ to fetch the existing automation instead of raising an error.
+ **kwargs:
+ Any additional values to assign to the automation before
+ creating it. If given, these will override any values that may
+ already be set on the automation:
+ - `name`: The name of the automation.
+ - `description`: The description of the automation.
+ - `enabled`: Whether the automation is enabled.
+ - `scope`: The scope of the automation.
+ - `event`: The event that triggers the automation.
+ - `action`: The action that is triggered by the automation.
+
+ Returns:
+ The saved Automation.
+
+ Examples:
+ Create a new automation named "my-automation" that sends a Slack notification
+ when a run within a specific project logs a metric exceeding a custom threshold:
+
+ ```python
+ import wandb
+ from wandb.automations import OnRunMetric, RunEvent, SendNotification
+
+ api = wandb.Api()
+
+ project = api.project("my-project", entity="my-team")
+
+ # Use the first Slack integration for the team
+ slack_hook = next(api.slack_integrations(entity="my-team"))
+
+ event = OnRunMetric(
+ scope=project,
+ filter=RunEvent.metric("custom-metric") > 10,
+ )
+ action = SendNotification.from_integration(slack_hook)
+
+ automation = api.create_automation(
+ event >> action,
+ name="my-automation",
+ description="Send a Slack message whenever 'custom-metric' exceeds 10.",
+ )
+ ```
+ """
+ from wandb.automations import Automation
+ from wandb.automations._generated import CREATE_AUTOMATION_GQL, CreateAutomation
+ from wandb.automations._utils import prepare_to_create
+
+ gql_input = prepare_to_create(obj, **kwargs)
+
+ if not self._supports_automation(
+ event=(event := gql_input.triggering_event_type),
+ action=(action := gql_input.triggered_action_type),
+ ):
+ raise ValueError(
+ f"Automation event or action ({event!r} -> {action!r}) "
+ "is not supported on this wandb server version. "
+ "Please upgrade your server version, or contact support at "
+ "support@wandb.com."
+ )
+
+ # If needed, rewrite the GraphQL field selection set to omit unsupported fields/fragments/types
+ omit_fragments = self._omitted_automation_fragments()
+ mutation = gql_compat(CREATE_AUTOMATION_GQL, omit_fragments=omit_fragments)
+ variables = {"params": gql_input.model_dump(exclude_none=True)}
+
+ name = gql_input.name
+ try:
+ data = self.client.execute(mutation, variable_values=variables)
+ except requests.HTTPError as e:
+ status = HTTPStatus(e.response.status_code)
+ if status is HTTPStatus.CONFLICT: # 409
+ if fetch_existing:
+ wandb.termlog(f"Automation {name!r} exists. Fetching it instead.")
+ return self.automation(name=name)
+
+ raise ValueError(
+ f"Automation {name!r} exists. Unable to create another with the same name."
+ ) from None
+ raise
+
+ try:
+ result = CreateAutomation.model_validate(data).result
+ except ValidationError as e:
+ msg = f"Invalid response while creating automation {name!r}"
+ raise RuntimeError(msg) from e
+
+ if (result is None) or (result.trigger is None):
+ msg = f"Empty response while creating automation {name!r}"
+ raise RuntimeError(msg)
+
+ return Automation.model_validate(result.trigger)
+
+ @normalize_exceptions
+ @tracked
+ def update_automation(
+ self,
+ obj: Automation,
+ *,
+ create_missing: bool = False,
+ **kwargs: Unpack[WriteAutomationsKwargs],
+ ) -> Automation:
+ """Update an existing automation.
+
+ Args:
+ obj: The automation to update. Must be an existing automation.
+ create_missing (bool):
+ If True, and the automation does not exist, create it.
+ **kwargs:
+ Any additional values to assign to the automation before
+ updating it. If given, these will override any values that may
+ already be set on the automation:
+ - `name`: The name of the automation.
+ - `description`: The description of the automation.
+ - `enabled`: Whether the automation is enabled.
+ - `scope`: The scope of the automation.
+ - `event`: The event that triggers the automation.
+ - `action`: The action that is triggered by the automation.
+
+ Returns:
+ The updated automation.
+
+ Examples:
+ Disable and edit the description of an existing automation ("my-automation"):
+
+ ```python
+ import wandb
+
+ api = wandb.Api()
+
+ automation = api.automation(name="my-automation")
+ automation.enabled = False
+ automation.description = "Kept for reference, but no longer used."
+
+ updated_automation = api.update_automation(automation)
+ ```
+
+ OR
+
+ ```python
+ import wandb
+
+ api = wandb.Api()
+
+ automation = api.automation(name="my-automation")
+
+ updated_automation = api.update_automation(
+ automation,
+ enabled=False,
+ description="Kept for reference, but no longer used.",
+ )
+ ```
+ """
+ from wandb.automations import ActionType, Automation
+ from wandb.automations._generated import UPDATE_AUTOMATION_GQL, UpdateAutomation
+ from wandb.automations._utils import prepare_to_update
+
+ # Check if the server even supports updating automations.
+ #
+ # NOTE: Unfortunately, there is no current server feature flag for this. As a workaround,
+ # we check whether the server supports the NO_OP action, which is a reasonably safe proxy
+ # for whether it supports updating automations.
+ if not self._supports_automation(action=ActionType.NO_OP):
+ raise RuntimeError(
+ "Updating existing automations is not enabled on this wandb server version. "
+ "Please upgrade your server version, or contact support at support@wandb.com."
+ )
+
+ gql_input = prepare_to_update(obj, **kwargs)
+
+ if not self._supports_automation(
+ event=(event := gql_input.triggering_event_type),
+ action=(action := gql_input.triggered_action_type),
+ ):
+ raise ValueError(
+ f"Automation event or action ({event.value} -> {action.value}) "
+ "is not supported on this wandb server version. "
+ "Please upgrade your server version, or contact support at "
+ "support@wandb.com."
+ )
+
+ # If needed, rewrite the GraphQL field selection set to omit unsupported fields/fragments/types
+ omit_fragments = self._omitted_automation_fragments()
+ mutation = gql_compat(UPDATE_AUTOMATION_GQL, omit_fragments=omit_fragments)
+ variables = {"params": gql_input.model_dump(exclude_none=True)}
+
+ name = gql_input.name
+ try:
+ data = self.client.execute(mutation, variable_values=variables)
+ except requests.HTTPError as e:
+ status = HTTPStatus(e.response.status_code)
+ if status is HTTPStatus.NOT_FOUND: # 404
+ if create_missing:
+ wandb.termlog(f"Automation {name!r} not found. Creating it.")
+ return self.create_automation(obj)
+
+ raise ValueError(
+ f"Automation {name!r} not found. Unable to edit it."
+ ) from e
+
+ # Not a (known) recoverable HTTP error
+ wandb.termerror(f"Got response status {status!r}: {e.response.text!r}")
+ raise
+
+ try:
+ result = UpdateAutomation.model_validate(data).result
+ except ValidationError as e:
+ msg = f"Invalid response while updating automation {name!r}"
+ raise RuntimeError(msg) from e
+
+ if (result is None) or (result.trigger is None):
+ msg = f"Empty response while updating automation {name!r}"
+ raise RuntimeError(msg)
+
+ return Automation.model_validate(result.trigger)
+
+ @normalize_exceptions
+ @tracked
+ def delete_automation(self, obj: Automation | str) -> Literal[True]:
+ """Delete an automation.
+
+ Args:
+ obj: The automation to delete, or its ID.
+
+ Returns:
+ True if the automation was deleted successfully.
+ """
+ from wandb.automations._generated import DELETE_AUTOMATION_GQL, DeleteAutomation
+ from wandb.automations._utils import extract_id
+
+ id_ = extract_id(obj)
+ mutation = gql(DELETE_AUTOMATION_GQL)
+ variables = {"id": id_}
+
+ data = self.client.execute(mutation, variable_values=variables)
+
+ try:
+ result = DeleteAutomation.model_validate(data).result
+ except ValidationError as e:
+ msg = f"Invalid response while deleting automation {id_!r}"
+ raise RuntimeError(msg) from e
+
+ if result is None:
+ msg = f"Empty response while deleting automation {id_!r}"
+ raise RuntimeError(msg)
+
+ if not result.success:
+ raise RuntimeError(f"Failed to delete automation: {id_!r}")
+
+ return result.success
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/artifacts.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/artifacts.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1c8ece0f2a17f815b179304bf501833881cdbce
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/artifacts.py
@@ -0,0 +1,1050 @@
+"""W&B Public API for Artifact objects.
+
+This module provides classes for interacting with W&B artifacts and their
+collections.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from copy import copy
+from typing import TYPE_CHECKING, Any, Iterable, Literal, Mapping, Sequence
+
+from typing_extensions import override
+from wandb_gql import Client, gql
+
+import wandb
+from wandb._strutils import nameof
+from wandb.apis import public
+from wandb.apis.normalize import normalize_exceptions
+from wandb.apis.paginator import Paginator, SizedPaginator
+from wandb.errors.term import termlog
+from wandb.proto.wandb_deprecated import Deprecated
+from wandb.proto.wandb_internal_pb2 import ServerFeature
+from wandb.sdk.artifacts._generated import (
+ ARTIFACT_COLLECTION_MEMBERSHIP_FILES_GQL,
+ ARTIFACT_VERSION_FILES_GQL,
+ CREATE_ARTIFACT_COLLECTION_TAG_ASSIGNMENTS_GQL,
+ DELETE_ARTIFACT_COLLECTION_TAG_ASSIGNMENTS_GQL,
+ DELETE_ARTIFACT_PORTFOLIO_GQL,
+ DELETE_ARTIFACT_SEQUENCE_GQL,
+ MOVE_ARTIFACT_COLLECTION_GQL,
+ PROJECT_ARTIFACT_COLLECTION_GQL,
+ PROJECT_ARTIFACT_COLLECTIONS_GQL,
+ PROJECT_ARTIFACT_TYPE_GQL,
+ PROJECT_ARTIFACT_TYPES_GQL,
+ PROJECT_ARTIFACTS_GQL,
+ RUN_INPUT_ARTIFACTS_GQL,
+ RUN_OUTPUT_ARTIFACTS_GQL,
+ UPDATE_ARTIFACT_PORTFOLIO_GQL,
+ UPDATE_ARTIFACT_SEQUENCE_GQL,
+ ArtifactCollectionMembershipFiles,
+ ArtifactCollectionsFragment,
+ ArtifactsFragment,
+ ArtifactTypeFragment,
+ ArtifactTypesFragment,
+ ArtifactVersionFiles,
+ FilesFragment,
+ ProjectArtifactCollection,
+ ProjectArtifactCollections,
+ ProjectArtifacts,
+ ProjectArtifactType,
+ ProjectArtifactTypes,
+ RunInputArtifactConnectionFragment,
+ RunOutputArtifactConnectionFragment,
+)
+from wandb.sdk.artifacts._gqlutils import omit_artifact_fields
+from wandb.sdk.artifacts._validators import (
+ SOURCE_ARTIFACT_COLLECTION_TYPE,
+ FullArtifactPath,
+ validate_artifact_name,
+ validate_artifact_type,
+)
+from wandb.sdk.internal.internal_api import Api as InternalApi
+from wandb.sdk.lib import deprecate
+
+from .utils import gql_compat
+
+if TYPE_CHECKING:
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ from . import RetryingClient, Run
+
+
+class ArtifactTypes(Paginator["ArtifactType"]):
+ """An lazy iterator of `ArtifactType` objects for a specific project.
+
+
+ """
+
+ QUERY = gql(PROJECT_ARTIFACT_TYPES_GQL)
+
+ last_response: ArtifactTypesFragment | None
+
+ def __init__(
+ self,
+ client: Client,
+ entity: str,
+ project: str,
+ per_page: int = 50,
+ ):
+ self.entity = entity
+ self.project = project
+
+ variable_values = {
+ "entityName": entity,
+ "projectName": project,
+ }
+ super().__init__(client, variable_values, per_page)
+
+ @override
+ def _update_response(self) -> None:
+ """Fetch and validate the response data for the current page."""
+ data = self.client.execute(self.QUERY, variable_values=self.variables)
+ result = ProjectArtifactTypes.model_validate(data)
+
+ # Extract the inner `*Connection` result for faster/easier access.
+ if not ((proj := result.project) and (conn := proj.artifact_types)):
+ raise ValueError(f"Unable to parse {nameof(type(self))!r} response data")
+
+ self.last_response = ArtifactTypesFragment.model_validate(conn)
+
+ @property
+ def _length(self) -> None:
+ """Returns `None`.
+
+
+ """
+ # TODO
+ return None
+
+ @property
+ def more(self) -> bool:
+ """Returns whether there are more artifact types to fetch.
+
+
+ """
+ if self.last_response is None:
+ return True
+ return self.last_response.page_info.has_next_page
+
+ @property
+ def cursor(self) -> str | None:
+ """Returns the cursor for the next page of results.
+
+
+ """
+ if self.last_response is None:
+ return None
+ return self.last_response.edges[-1].cursor
+
+ def update_variables(self) -> None:
+ """Update the cursor variable for pagination.
+
+
+ """
+ self.variables.update({"cursor": self.cursor})
+
+ def convert_objects(self) -> list[ArtifactType]:
+ """Convert the raw response data into a list of ArtifactType objects.
+
+
+ """
+ if self.last_response is None:
+ return []
+
+ return [
+ ArtifactType(
+ client=self.client,
+ entity=self.entity,
+ project=self.project,
+ type_name=node.name,
+ attrs=node.model_dump(exclude_unset=True),
+ )
+ for edge in self.last_response.edges
+ if edge.node and (node := ArtifactTypeFragment.model_validate(edge.node))
+ ]
+
+
+class ArtifactType:
+ """An artifact object that satisfies query based on the specified type.
+
+ Args:
+ client: The client instance to use for querying W&B.
+ entity: The entity (user or team) that owns the project.
+ project: The name of the project to query for artifact types.
+ type_name: The name of the artifact type.
+ attrs: Optional mapping of attributes to initialize the artifact type. If not provided,
+ the object will load its attributes from W&B upon initialization.
+
+
+ """
+
+ def __init__(
+ self,
+ client: Client,
+ entity: str,
+ project: str,
+ type_name: str,
+ attrs: Mapping[str, Any] | None = None,
+ ):
+ self.client = client
+ self.entity = entity
+ self.project = project
+ self.type = type_name
+ self._attrs = attrs
+ if self._attrs is None:
+ self.load()
+
+ def load(self) -> Mapping[str, Any]:
+ """Load the artifact type attributes from W&B.
+
+
+ """
+ data: Mapping[str, Any] | None = self.client.execute(
+ gql(PROJECT_ARTIFACT_TYPE_GQL),
+ variable_values={
+ "entityName": self.entity,
+ "projectName": self.project,
+ "artifactTypeName": self.type,
+ },
+ )
+ result = ProjectArtifactType.model_validate(data)
+ if not ((proj := result.project) and (artifact_type := proj.artifact_type)):
+ raise ValueError(f"Could not find artifact type {self.type}")
+
+ self._attrs = artifact_type.model_dump(exclude_unset=True)
+ return self._attrs
+
+ @property
+ def id(self) -> str:
+ """The unique identifier of the artifact type."""
+ return self._attrs["id"]
+
+ @property
+ def name(self) -> str:
+ """The name of the artifact type."""
+ return self._attrs["name"]
+
+ @normalize_exceptions
+ def collections(self, per_page: int = 50) -> ArtifactCollections:
+ """Get all artifact collections associated with this artifact type.
+
+ Args:
+ per_page (int): The number of artifact collections to fetch per page.
+ Default is 50.
+ """
+ return ArtifactCollections(self.client, self.entity, self.project, self.type)
+
+ def collection(self, name: str) -> ArtifactCollection:
+ """Get a specific artifact collection by name.
+
+ Args:
+ name (str): The name of the artifact collection to retrieve.
+ """
+ return ArtifactCollection(
+ self.client, self.entity, self.project, name, self.type
+ )
+
+ def __repr__(self) -> str:
+ return f""
+
+
+class ArtifactCollections(SizedPaginator["ArtifactCollection"]):
+ """Artifact collections of a specific type in a project.
+
+ Args:
+ client: The client instance to use for querying W&B.
+ entity: The entity (user or team) that owns the project.
+ project: The name of the project to query for artifact collections.
+ type_name: The name of the artifact type for which to fetch collections.
+ per_page: The number of artifact collections to fetch per page. Default is 50.
+
+
+ """
+
+ last_response: ArtifactCollectionsFragment | None
+
+ def __init__(
+ self,
+ client: Client,
+ entity: str,
+ project: str,
+ type_name: str,
+ per_page: int = 50,
+ ):
+ self.entity = entity
+ self.project = project
+ self.type_name = type_name
+
+ variable_values = {
+ "entityName": entity,
+ "projectName": project,
+ "artifactTypeName": type_name,
+ }
+
+ if server_supports_artifact_collections_gql_edges(client):
+ rename_fields = None
+ else:
+ rename_fields = {"artifactCollections": "artifactSequences"}
+
+ self.QUERY = gql_compat(
+ PROJECT_ARTIFACT_COLLECTIONS_GQL, rename_fields=rename_fields
+ )
+
+ super().__init__(client, variable_values, per_page)
+
+ @override
+ def _update_response(self) -> None:
+ """Fetch and validate the response data for the current page."""
+ data = self.client.execute(self.QUERY, variable_values=self.variables)
+ result = ProjectArtifactCollections.model_validate(data)
+
+ # Extract the inner `*Connection` result for faster/easier access.
+ if not (
+ (proj := result.project)
+ and (type_ := proj.artifact_type)
+ and (conn := type_.artifact_collections)
+ ):
+ raise ValueError(f"Unable to parse {nameof(type(self))!r} response data")
+
+ self.last_response = ArtifactCollectionsFragment.model_validate(conn)
+
+ @property
+ def _length(self) -> int:
+ """Returns the total number of artifact collections.
+
+
+ """
+ if self.last_response is None:
+ self._load_page()
+ return self.last_response.total_count
+
+ @property
+ def more(self):
+ """Returns whether there are more artifacts to fetch.
+
+
+ """
+ if self.last_response is None:
+ return True
+ return self.last_response.page_info.has_next_page
+
+ @property
+ def cursor(self):
+ """Returns the cursor for the next page of results.
+
+
+ """
+ if self.last_response is None:
+ return None
+ return self.last_response.edges[-1].cursor
+
+ def update_variables(self) -> None:
+ """Update the cursor variable for pagination.
+
+
+ """
+ self.variables.update({"cursor": self.cursor})
+
+ def convert_objects(self) -> list[ArtifactCollection]:
+ """Convert the raw response data into a list of ArtifactCollection objects.
+
+
+ """
+ if self.last_response is None:
+ return []
+ return [
+ ArtifactCollection(
+ client=self.client,
+ entity=self.entity,
+ project=self.project,
+ name=node.name,
+ type=self.type_name,
+ )
+ for edge in self.last_response.edges
+ if (node := edge.node)
+ ]
+
+
+class ArtifactCollection:
+ """An artifact collection that represents a group of related artifacts.
+
+ Args:
+ client: The client instance to use for querying W&B.
+ entity: The entity (user or team) that owns the project.
+ project: The name of the project to query for artifact collections.
+ name: The name of the artifact collection.
+ type: The type of the artifact collection (e.g., "dataset", "model").
+ organization: Optional organization name if applicable.
+ attrs: Optional mapping of attributes to initialize the artifact collection.
+ If not provided, the object will load its attributes from W&B upon
+ initialization.
+
+
+ """
+
+ def __init__(
+ self,
+ client: Client,
+ entity: str,
+ project: str,
+ name: str,
+ type: str,
+ organization: str | None = None,
+ attrs: Mapping[str, Any] | None = None,
+ is_sequence: bool | None = None,
+ ):
+ self.client = client
+ self.entity = entity
+ self.project = project
+ self._name = validate_artifact_name(name)
+ self._saved_name = name
+ self._type = type
+ self._saved_type = type
+ self._attrs = attrs
+ if is_sequence is not None:
+ self._is_sequence = is_sequence
+ if (attrs is None) or (is_sequence is None):
+ self.load()
+ self._aliases = [a["node"]["alias"] for a in self._attrs["aliases"]["edges"]]
+ self._description = self._attrs["description"]
+ self._created_at = self._attrs["createdAt"]
+ self._tags = [a["node"]["name"] for a in self._attrs["tags"]["edges"]]
+ self._saved_tags = copy(self._tags)
+ self.organization = organization
+
+ @property
+ def id(self) -> str:
+ """The unique identifier of the artifact collection."""
+ return self._attrs["id"]
+
+ @normalize_exceptions
+ def artifacts(self, per_page: int = 50) -> Artifacts:
+ """Get all artifacts in the collection."""
+ return Artifacts(
+ client=self.client,
+ entity=self.entity,
+ project=self.project,
+ collection_name=self._saved_name,
+ type=self._saved_type,
+ per_page=per_page,
+ )
+
+ @property
+ def aliases(self) -> list[str]:
+ """Artifact Collection Aliases."""
+ return self._aliases
+
+ @property
+ def created_at(self) -> str:
+ """The creation date of the artifact collection."""
+ return self._created_at
+
+ def load(self):
+ """Load the artifact collection attributes from W&B.
+
+
+ """
+ if server_supports_artifact_collections_gql_edges(self.client):
+ rename_fields = None
+ else:
+ rename_fields = {"artifactCollection": "artifactSequence"}
+
+ response = self.client.execute(
+ gql_compat(PROJECT_ARTIFACT_COLLECTION_GQL, rename_fields=rename_fields),
+ variable_values={
+ "entityName": self.entity,
+ "projectName": self.project,
+ "artifactTypeName": self._saved_type,
+ "artifactCollectionName": self._saved_name,
+ },
+ )
+
+ result = ProjectArtifactCollection.model_validate(response)
+
+ if not (
+ result.project
+ and (proj := result.project)
+ and (type_ := proj.artifact_type)
+ and (collection := type_.artifact_collection)
+ ):
+ raise ValueError(f"Could not find artifact type {self._saved_type}")
+
+ sequence = type_.artifact_sequence
+ self._is_sequence = (
+ sequence is not None
+ ) and sequence.typename__ == SOURCE_ARTIFACT_COLLECTION_TYPE
+
+ if self._attrs is None:
+ self._attrs = collection.model_dump(exclude_unset=True)
+ return self._attrs
+
+ @normalize_exceptions
+ def change_type(self, new_type: str) -> None:
+ """Deprecated, change type directly with `save` instead."""
+ deprecate.deprecate(
+ field_name=Deprecated.artifact_collection__change_type,
+ warning_message="ArtifactCollection.change_type(type) is deprecated, use ArtifactCollection.save() instead.",
+ )
+
+ if self._saved_type != new_type:
+ try:
+ validate_artifact_type(self._saved_type, self.name)
+ except ValueError as e:
+ raise ValueError(
+ f"The current type '{self._saved_type!r}' is an internal type and cannot be changed."
+ ) from e
+
+ # Check that the new type is not going to conflict with internal types
+ validate_artifact_type(new_type, self.name)
+
+ if not self.is_sequence():
+ raise ValueError("Artifact collection needs to be a sequence")
+ termlog(
+ f"Changing artifact collection type of {self._saved_type} to {new_type}"
+ )
+ self.client.execute(
+ gql(MOVE_ARTIFACT_COLLECTION_GQL),
+ variable_values={
+ "artifactSequenceID": self.id,
+ "destinationArtifactTypeName": new_type,
+ },
+ )
+ self._saved_type = new_type
+ self._type = new_type
+
+ def is_sequence(self) -> bool:
+ """Return whether the artifact collection is a sequence."""
+ return self._is_sequence
+
+ @normalize_exceptions
+ def delete(self) -> None:
+ """Delete the entire artifact collection."""
+ self.client.execute(
+ gql(
+ DELETE_ARTIFACT_SEQUENCE_GQL
+ if self.is_sequence()
+ else DELETE_ARTIFACT_PORTFOLIO_GQL
+ ),
+ variable_values={"id": self.id},
+ )
+
+ @property
+ def description(self) -> str:
+ """A description of the artifact collection."""
+ return self._description
+
+ @description.setter
+ def description(self, description: str | None) -> None:
+ """Set the description of the artifact collection."""
+ self._description = description
+
+ @property
+ def tags(self) -> list[str]:
+ """The tags associated with the artifact collection."""
+ return self._tags
+
+ @tags.setter
+ def tags(self, tags: list[str]) -> None:
+ """Set the tags associated with the artifact collection."""
+ if any(not re.match(r"^[-\w]+([ ]+[-\w]+)*$", tag) for tag in tags):
+ raise ValueError(
+ "Tags must only contain alphanumeric characters or underscores separated by spaces or hyphens"
+ )
+ self._tags = tags
+
+ @property
+ def name(self) -> str:
+ """The name of the artifact collection."""
+ return self._name
+
+ @name.setter
+ def name(self, name: str) -> None:
+ """Set the name of the artifact collection."""
+ self._name = validate_artifact_name(name)
+
+ @property
+ def type(self):
+ """Returns the type of the artifact collection."""
+ return self._type
+
+ @type.setter
+ def type(self, type: list[str]) -> None:
+ """Set the type of the artifact collection."""
+ if not self.is_sequence():
+ raise ValueError(
+ "Type can only be changed if the artifact collection is a sequence."
+ )
+ self._type = type
+
+ def _update_collection(self) -> None:
+ self.client.execute(
+ gql(
+ UPDATE_ARTIFACT_SEQUENCE_GQL
+ if self.is_sequence()
+ else UPDATE_ARTIFACT_PORTFOLIO_GQL
+ ),
+ variable_values={
+ "id": self.id,
+ "name": self.name,
+ "description": self.description,
+ },
+ )
+ self._saved_name = self._name
+
+ def _update_collection_type(self) -> None:
+ self.client.execute(
+ gql(MOVE_ARTIFACT_COLLECTION_GQL),
+ variable_values={
+ "artifactSequenceID": self.id,
+ "destinationArtifactTypeName": self.type,
+ },
+ )
+ self._saved_type = self._type
+
+ def _add_tags(self, tags_to_add: Iterable[str]) -> None:
+ self.client.execute(
+ gql(CREATE_ARTIFACT_COLLECTION_TAG_ASSIGNMENTS_GQL),
+ variable_values={
+ "entityName": self.entity,
+ "projectName": self.project,
+ "artifactCollectionName": self._saved_name,
+ "tags": [{"tagName": tag} for tag in tags_to_add],
+ },
+ )
+
+ def _delete_tags(self, tags_to_delete: Iterable[str]) -> None:
+ self.client.execute(
+ gql(DELETE_ARTIFACT_COLLECTION_TAG_ASSIGNMENTS_GQL),
+ variable_values={
+ "entityName": self.entity,
+ "projectName": self.project,
+ "artifactCollectionName": self._saved_name,
+ "tags": [{"tagName": tag} for tag in tags_to_delete],
+ },
+ )
+
+ @normalize_exceptions
+ def save(self) -> None:
+ """Persist any changes made to the artifact collection."""
+ if self._saved_type != self.type:
+ try:
+ validate_artifact_type(self.type, self._name)
+ except ValueError as e:
+ raise ValueError(f"Failed to save artifact collection: {e}") from e
+ try:
+ validate_artifact_type(self._saved_type, self._name)
+ except ValueError as e:
+ raise ValueError(
+ f"Failed to save artifact collection '{self._name}': "
+ f"The current type '{self._saved_type!r}' is an internal type and cannot be changed."
+ ) from e
+
+ self._update_collection()
+
+ if self.is_sequence() and (self._saved_type != self._type):
+ self._update_collection_type()
+
+ current_tags = set(self._tags)
+ saved_tags = set(self._saved_tags)
+ if tags_to_add := (current_tags - saved_tags):
+ self._add_tags(tags_to_add)
+ if tags_to_delete := (saved_tags - current_tags):
+ self._delete_tags(tags_to_delete)
+ self._saved_tags = copy(self._tags)
+
+ def __repr__(self) -> str:
+ return f""
+
+
+class Artifacts(SizedPaginator["Artifact"]):
+ """An iterable collection of artifact versions associated with a project.
+
+ Optionally pass in filters to narrow down the results based on specific criteria.
+
+ Args:
+ client: The client instance to use for querying W&B.
+ entity: The entity (user or team) that owns the project.
+ project: The name of the project to query for artifacts.
+ collection_name: The name of the artifact collection to query.
+ type: The type of the artifacts to query. Common examples include
+ "dataset" or "model".
+ filters: Optional mapping of filters to apply to the query.
+ order: Optional string to specify the order of the results.
+ per_page: The number of artifact versions to fetch per page. Default is 50.
+ tags: Optional string or list of strings to filter artifacts by tags.
+
+
+ """
+
+ last_response: ArtifactsFragment | None
+
+ def __init__(
+ self,
+ client: Client,
+ entity: str,
+ project: str,
+ collection_name: str,
+ type: str,
+ filters: Mapping[str, Any] | None = None,
+ order: str | None = None,
+ per_page: int = 50,
+ tags: str | list[str] | None = None,
+ ):
+ self.entity = entity
+ self.collection_name = collection_name
+ self.type = type
+ self.project = project
+ self.filters = {"state": "COMMITTED"} if filters is None else filters
+ self.tags = [tags] if isinstance(tags, str) else tags
+ self.order = order
+ variables = {
+ "project": self.project,
+ "entity": self.entity,
+ "order": self.order,
+ "type": self.type,
+ "collection": self.collection_name,
+ "filters": json.dumps(self.filters),
+ }
+
+ if server_supports_artifact_collections_gql_edges(client):
+ rename_fields = None
+ else:
+ rename_fields = {"artifactCollection": "artifactSequence"}
+
+ self.QUERY = gql_compat(
+ PROJECT_ARTIFACTS_GQL,
+ omit_fields=omit_artifact_fields(client),
+ rename_fields=rename_fields,
+ )
+
+ super().__init__(client, variables, per_page)
+
+ @override
+ def _update_response(self) -> None:
+ data = self.client.execute(self.QUERY, variable_values=self.variables)
+ result = ProjectArtifacts.model_validate(data)
+
+ # Extract the inner `*Connection` result for faster/easier access.
+ if not (
+ (proj := result.project)
+ and (type_ := proj.artifact_type)
+ and (collection := type_.artifact_collection)
+ and (conn := collection.artifacts)
+ ):
+ raise ValueError(f"Unable to parse {nameof(type(self))!r} response data")
+
+ self.last_response = ArtifactsFragment.model_validate(conn)
+
+ @property
+ def _length(self) -> int:
+ """Returns the total number of artifacts in the collection.
+
+
+ """
+ if self.last_response is None:
+ self._load_page()
+ return self.last_response.total_count
+
+ @property
+ def more(self) -> bool:
+ """Returns whether there are more files to fetch.
+
+
+ """
+ if self.last_response is None:
+ return True
+ return self.last_response.page_info.has_next_page
+
+ @property
+ def cursor(self) -> str | None:
+ """Returns the cursor for the next page of results.
+
+
+ """
+ if self.last_response is None:
+ return None
+ return self.last_response.edges[-1].cursor
+
+ def convert_objects(self) -> list[Artifact]:
+ """Convert the raw response data into a list of wandb.Artifact objects.
+
+
+ """
+ if self.last_response is None:
+ return []
+
+ artifact_edges = (edge for edge in self.last_response.edges if edge.node)
+ artifacts = (
+ wandb.Artifact._from_attrs(
+ path=FullArtifactPath(
+ prefix=self.entity,
+ project=self.project,
+ name=f"{self.collection_name}:{edge.version}",
+ ),
+ attrs=edge.node,
+ client=self.client,
+ )
+ for edge in artifact_edges
+ )
+ required_tags = set(self.tags or [])
+ return [art for art in artifacts if required_tags.issubset(art.tags)]
+
+
+class RunArtifacts(SizedPaginator["Artifact"]):
+ """An iterable collection of artifacts associated with a specific run.
+
+
+ """
+
+ last_response: (
+ RunOutputArtifactConnectionFragment | RunInputArtifactConnectionFragment
+ )
+
+ #: The pydantic model used to parse the (inner part of the) raw response.
+ _response_cls: type[
+ RunOutputArtifactConnectionFragment | RunInputArtifactConnectionFragment
+ ]
+
+ def __init__(
+ self,
+ client: Client,
+ run: Run,
+ mode: Literal["logged", "used"] = "logged",
+ per_page: int = 50,
+ ):
+ self.run = run
+
+ if mode == "logged":
+ self.run_key = "outputArtifacts"
+ self.QUERY = gql_compat(
+ RUN_OUTPUT_ARTIFACTS_GQL, omit_fields=omit_artifact_fields(client)
+ )
+ self._response_cls = RunOutputArtifactConnectionFragment
+ elif mode == "used":
+ self.run_key = "inputArtifacts"
+ self.QUERY = gql_compat(
+ RUN_INPUT_ARTIFACTS_GQL, omit_fields=omit_artifact_fields(client)
+ )
+ self._response_cls = RunInputArtifactConnectionFragment
+ else:
+ raise ValueError("mode must be logged or used")
+
+ variable_values = {
+ "entity": run.entity,
+ "project": run.project,
+ "runName": run.id,
+ }
+ super().__init__(client, variable_values, per_page)
+
+ @override
+ def _update_response(self) -> None:
+ data = self.client.execute(self.QUERY, variable_values=self.variables)
+
+ # Extract the inner `*Connection` result for faster/easier access.
+ inner_data = data["project"]["run"][self.run_key]
+ self.last_response = self._response_cls.model_validate(inner_data)
+
+ @property
+ def _length(self) -> int:
+ """Returns the total number of artifacts in the collection.
+
+
+ """
+ if self.last_response is None:
+ self._load_page()
+ return self.last_response.total_count
+
+ @property
+ def more(self) -> bool:
+ """Returns whether there are more artifacts to fetch.
+
+
+ """
+ if self.last_response is None:
+ return True
+ return self.last_response.page_info.has_next_page
+
+ @property
+ def cursor(self) -> str | None:
+ """Returns the cursor for the next page of results.
+
+
+ """
+ if self.last_response is None:
+ return None
+ return self.last_response.edges[-1].cursor
+
+ def convert_objects(self) -> list[Artifact]:
+ """Convert the raw response data into a list of wandb.Artifact objects.
+
+
+ """
+ if self.last_response is None:
+ return []
+
+ return [
+ wandb.Artifact._from_attrs(
+ path=FullArtifactPath(
+ prefix=proj.entity_name,
+ project=proj.name,
+ name=f"{artifact_seq.name}:v{node.version_index}",
+ ),
+ attrs=node,
+ client=self.client,
+ )
+ for edge in self.last_response.edges
+ if (node := edge.node)
+ and (artifact_seq := node.artifact_sequence)
+ and (proj := artifact_seq.project)
+ ]
+
+
+class ArtifactFiles(SizedPaginator["public.File"]):
+ """A paginator for files in an artifact.
+
+
+ """
+
+ last_response: FilesFragment | None
+
+ def __init__(
+ self,
+ client: Client,
+ artifact: Artifact,
+ names: Sequence[str] | None = None,
+ per_page: int = 50,
+ ):
+ self.query_via_membership = InternalApi()._server_supports(
+ ServerFeature.ARTIFACT_COLLECTION_MEMBERSHIP_FILES
+ )
+ self.artifact = artifact
+
+ if self.query_via_membership:
+ query_str = ARTIFACT_COLLECTION_MEMBERSHIP_FILES_GQL
+ variables = {
+ "entityName": artifact.entity,
+ "projectName": artifact.project,
+ "artifactName": artifact.name.split(":")[0],
+ "artifactVersionIndex": artifact.version,
+ "fileNames": names,
+ }
+ else:
+ query_str = ARTIFACT_VERSION_FILES_GQL
+ variables = {
+ "entityName": artifact.source_entity,
+ "projectName": artifact.source_project,
+ "artifactName": artifact.source_name,
+ "artifactTypeName": artifact.type,
+ "fileNames": names,
+ }
+
+ # The server must advertise at least SDK 0.12.21
+ # to get storagePath
+ if not client.version_supported("0.12.21"):
+ self.QUERY = gql_compat(query_str, omit_fields={"storagePath"})
+ else:
+ self.QUERY = gql(query_str)
+
+ super().__init__(client, variables, per_page)
+
+ @override
+ def _update_response(self) -> None:
+ data = self.client.execute(self.QUERY, variable_values=self.variables)
+
+ # Extract the inner `*Connection` result for faster/easier access.
+ if self.query_via_membership:
+ result = ArtifactCollectionMembershipFiles.model_validate(data)
+ conn = result.project.artifact_collection.artifact_membership.files
+ else:
+ result = ArtifactVersionFiles.model_validate(data)
+ conn = result.project.artifact_type.artifact.files
+
+ if conn is None:
+ raise ValueError(f"Unable to parse {nameof(type(self))!r} response data")
+
+ self.last_response = FilesFragment.model_validate(conn)
+
+ @property
+ def path(self) -> list[str]:
+ """Returns the path of the artifact."""
+ return [self.artifact.entity, self.artifact.project, self.artifact.name]
+
+ @property
+ def _length(self) -> int:
+ if self.last_response is None:
+ self._load_page()
+ """Returns the total number of files in the artifact.
+
+
+ """
+ return self.artifact.file_count
+
+ @property
+ def more(self) -> bool:
+ """Returns whether there are more files to fetch.
+
+
+ """
+ if self.last_response is None:
+ return True
+ return self.last_response.page_info.has_next_page
+
+ @property
+ def cursor(self) -> str | None:
+ """Returns the cursor for the next page of results.
+
+
+ """
+ if self.last_response is None:
+ return None
+ return self.last_response.edges[-1].cursor
+
+ def update_variables(self) -> None:
+ """Update the variables dictionary with the cursor.
+
+
+ """
+ self.variables.update({"fileLimit": self.per_page, "fileCursor": self.cursor})
+
+ def convert_objects(self) -> list[public.File]:
+ """Convert the raw response data into a list of public.File objects.
+
+
+ """
+ if self.last_response is None:
+ return []
+
+ return [
+ public.File(
+ client=self.client,
+ attrs=node.model_dump(exclude_unset=True),
+ )
+ for edge in self.last_response.edges
+ if (node := edge.node)
+ ]
+
+ def __repr__(self) -> str:
+ path_str = "/".join(self.path)
+ return f""
+
+
+def server_supports_artifact_collections_gql_edges(
+ client: RetryingClient, warn: bool = False
+) -> bool:
+ """Check if W&B server supports GraphQL edges for artifact collections.
+
+
+ """
+ # TODO: Validate this version
+ # Edges were merged into core on Mar 2, 2022: https://github.com/wandb/core/commit/81c90b29eaacfe0a96dc1ebd83c53560ca763e8b
+ # CLI version was bumped to "0.12.11" on Mar 3, 2022: https://github.com/wandb/core/commit/328396fa7c89a2178d510a1be9c0d4451f350d7b
+ supported = client.version_supported("0.12.11") # edges were merged on
+ if not supported and warn:
+ # First local release to include the above is 0.9.50: https://github.com/wandb/local/releases/tag/0.9.50
+ wandb.termwarn(
+ "W&B Local Server version does not support ArtifactCollection gql edges; falling back to using legacy ArtifactSequence. Please update server to at least version 0.9.50."
+ )
+ return supported
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/automations.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/automations.py
new file mode 100644
index 0000000000000000000000000000000000000000..abc4ba241d75b6a38fce6128d13901350bf81d4b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/automations.py
@@ -0,0 +1,86 @@
+"""W&B Public API for Automation objects."""
+
+from __future__ import annotations
+
+from itertools import chain
+from typing import TYPE_CHECKING, Any, Iterable, Mapping
+
+from pydantic import ValidationError
+from typing_extensions import override
+from wandb_graphql.language.ast import Document
+
+from wandb._strutils import nameof
+from wandb.apis.paginator import Paginator, _Client
+
+if TYPE_CHECKING:
+ from wandb.automations import Automation
+ from wandb.automations._generated import ProjectConnectionFields
+
+
+class Automations(Paginator["Automation"]):
+ """An lazy iterator of `Automation` objects.
+
+
+ """
+
+ last_response: ProjectConnectionFields | None
+ _query: Document
+
+ def __init__(
+ self,
+ client: _Client,
+ variables: Mapping[str, Any],
+ per_page: int = 50,
+ _query: Document | None = None,
+ ):
+ super().__init__(client, variables, per_page=per_page)
+ if _query is None:
+ raise RuntimeError(f"Query required for {nameof(type(self))}")
+ self._query = _query
+
+ @property
+ def more(self) -> bool:
+ """Whether there are more items to fetch.
+
+
+ """
+ if self.last_response is None:
+ return True
+ return self.last_response.page_info.has_next_page
+
+ @property
+ def cursor(self) -> str | None:
+ """The start cursor to use for the next page.
+
+
+ """
+ if self.last_response is None:
+ return None
+ return self.last_response.page_info.end_cursor
+
+ @override
+ def _update_response(self) -> None:
+ """Fetch the raw response data for the current page."""
+ from wandb.automations._generated import ProjectConnectionFields
+
+ data: dict[str, Any] = self.client.execute(
+ self._query, variable_values=self.variables
+ )
+ try:
+ page_data = data["searchScope"]["projects"]
+ self.last_response = ProjectConnectionFields.model_validate(page_data)
+ except (LookupError, AttributeError, ValidationError) as e:
+ raise ValueError("Unexpected response data") from e
+
+ def convert_objects(self) -> Iterable[Automation]:
+ """Parse the page data into a list of objects.
+
+
+ """
+ from wandb.automations import Automation
+
+ page = self.last_response
+ return [
+ Automation.model_validate(obj)
+ for obj in chain.from_iterable(edge.node.triggers for edge in page.edges)
+ ]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/const.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/const.py
new file mode 100644
index 0000000000000000000000000000000000000000..e75e387177d8b2c65d468ded64f4080b5b67a5bd
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/const.py
@@ -0,0 +1,6 @@
+from __future__ import annotations
+
+import datetime
+
+# Only retry requests for 20 seconds in the public api
+RETRY_TIMEDELTA = datetime.timedelta(seconds=20)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/files.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/files.py
new file mode 100644
index 0000000000000000000000000000000000000000..46d7c365ddfe13fd75ed14c2e8d2b04944c81a1a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/files.py
@@ -0,0 +1,411 @@
+"""W&B Public API for File objects.
+
+This module provides classes for interacting with files stored in W&B.
+
+Example:
+```python
+from wandb.apis.public import Api
+
+# Get files from a specific run
+run = Api().run("entity/project/run_id")
+files = run.files()
+
+# Work with files
+for file in files:
+ print(f"File: {file.name}")
+ print(f"Size: {file.size} bytes")
+ print(f"Type: {file.mimetype}")
+
+ # Download file
+ if file.size < 1000000: # Less than 1MB
+ file.download(root="./downloads")
+
+ # Get S3 URI for large files
+ if file.size >= 1000000:
+ print(f"S3 URI: {file.path_uri}")
+```
+
+Note:
+ This module is part of the W&B Public API and provides methods to access,
+ download, and manage files stored in W&B. Files are typically associated
+ with specific runs and can include model weights, datasets, visualizations,
+ and other artifacts.
+"""
+
+from __future__ import annotations
+
+import io
+import os
+
+import requests
+from wandb_gql import gql
+from wandb_gql.client import RetryError
+
+import wandb
+from wandb import util
+from wandb.apis.attrs import Attrs
+from wandb.apis.normalize import normalize_exceptions
+from wandb.apis.paginator import SizedPaginator
+from wandb.apis.public import utils
+from wandb.apis.public.api import Api, RetryingClient
+from wandb.apis.public.const import RETRY_TIMEDELTA
+from wandb.apis.public.runs import Run, _server_provides_internal_id_for_project
+from wandb.sdk.lib import retry
+
+FILE_FRAGMENT = """fragment RunFilesFragment on Run {
+ files(names: $fileNames, after: $fileCursor, first: $fileLimit, pattern: $pattern) {
+ edges {
+ node {
+ id
+ name
+ url(upload: $upload)
+ directUrl
+ sizeBytes
+ mimetype
+ updatedAt
+ md5
+ }
+ cursor
+ }
+ pageInfo {
+ endCursor
+ hasNextPage
+ }
+ }
+}"""
+
+
+class Files(SizedPaginator["File"]):
+ """A lazy iterator over a collection of `File` objects.
+
+ Access and manage files uploaded to W&B during a run. Handles pagination
+ automatically when iterating through large collections of files.
+
+ Example:
+ ```python
+ from wandb.apis.public.files import Files
+ from wandb.apis.public.api import Api
+
+ # Example run object
+ run = Api().run("entity/project/run-id")
+
+ # Create a Files object to iterate over files in the run
+ files = Files(api.client, run)
+
+ # Iterate over files
+ for file in files:
+ print(file.name)
+ print(file.url)
+ print(file.size)
+
+ # Download the file
+ file.download(root="download_directory", replace=True)
+ ```
+ """
+
+ def _get_query(self):
+ """Generate query dynamically based on server capabilities."""
+ with_internal_id = _server_provides_internal_id_for_project(self.client)
+ return gql(
+ f"""
+ query RunFiles($project: String!, $entity: String!, $name: String!, $fileCursor: String,
+ $fileLimit: Int = 50, $fileNames: [String] = [], $upload: Boolean = false, $pattern: String) {{
+ project(name: $project, entityName: $entity) {{
+ {"internalId" if with_internal_id else ""}
+ run(name: $name) {{
+ fileCount
+ ...RunFilesFragment
+ }}
+ }}
+ }}
+ {FILE_FRAGMENT}
+ """
+ )
+
+ def __init__(
+ self,
+ client: RetryingClient,
+ run: Run,
+ names: list[str] | None = None,
+ per_page: int = 50,
+ upload: bool = False,
+ pattern: str | None = None,
+ ):
+ """Initialize a lazy iterator over a collection of `File` objects.
+
+ Files are retrieved in pages from the W&B server as needed.
+
+ Args:
+ client: The run object that contains the files
+ run: The run object that contains the files
+ names (list, optional): A list of file names to filter the files
+ per_page (int, optional): The number of files to fetch per page
+ upload (bool, optional): If `True`, fetch the upload URL for each file
+ pattern (str, optional): Pattern to match when returning files from W&B
+ This pattern uses mySQL's LIKE syntax,
+ so matching all files that end with .json would be "%.json".
+ If both names and pattern are provided, a ValueError will be raised.
+ """
+ if names and pattern:
+ raise ValueError(
+ "Querying for files by both names and pattern is not supported."
+ " Please provide either a list of names or a pattern to match.",
+ )
+
+ self.run = run
+ variables = {
+ "project": run.project,
+ "entity": run.entity,
+ "name": run.id,
+ "fileNames": names or [],
+ "upload": upload,
+ "pattern": pattern,
+ }
+ super().__init__(client, variables, per_page)
+
+ def _update_response(self) -> None:
+ """Fetch and store the response data for the next page using dynamic query."""
+ self.last_response = self.client.execute(
+ self._get_query(), variable_values=self.variables
+ )
+
+ @property
+ def _length(self):
+ """
+ Returns total number of files.
+
+
+ """
+ if not self.last_response:
+ self._load_page()
+
+ return self.last_response["project"]["run"]["fileCount"]
+
+ @property
+ def more(self):
+ """Returns whether there are more files to fetch.
+
+
+ """
+ if self.last_response:
+ return self.last_response["project"]["run"]["files"]["pageInfo"][
+ "hasNextPage"
+ ]
+ else:
+ return True
+
+ @property
+ def cursor(self):
+ """Returns the cursor position for pagination of file results.
+
+
+ """
+ if self.last_response:
+ return self.last_response["project"]["run"]["files"]["edges"][-1]["cursor"]
+ else:
+ return None
+
+ def update_variables(self):
+ """Updates the GraphQL query variables for pagination.
+
+
+ """
+ self.variables.update({"fileLimit": self.per_page, "fileCursor": self.cursor})
+
+ def convert_objects(self):
+ """Converts GraphQL edges to File objects.
+
+
+ """
+ return [
+ File(self.client, r["node"], self.run)
+ for r in self.last_response["project"]["run"]["files"]["edges"]
+ ]
+
+ def __repr__(self):
+ return "".format("/".join(self.run.path), len(self))
+
+
+class File(Attrs):
+ """File saved to W&B.
+
+ Represents a single file stored in W&B. Includes access to file metadata.
+ Files are associated with a specific run and
+ can include text files, model weights, datasets, visualizations, and other
+ artifacts. You can download the file, delete the file, and access file
+ properties.
+
+ Specify one or more attributes in a dictionary to fine a specific
+ file logged to a specific run. You can search using the following keys:
+
+ - id (str): The ID of the run that contains the file
+ - name (str): Name of the file
+ - url (str): path to file
+ - direct_url (str): path to file in the bucket
+ - sizeBytes (int): size of file in bytes
+ - md5 (str): md5 of file
+ - mimetype (str): mimetype of file
+ - updated_at (str): timestamp of last update
+ - path_uri (str): path to file in the bucket, currently only available for S3 objects and reference files
+
+ Args:
+ client: The run object that contains the file
+ attrs (dict): A dictionary of attributes that define the file
+ run: The run object that contains the file
+
+
+ """
+
+ def __init__(self, client, attrs, run=None):
+ self.client = client
+ self._attrs = attrs
+ self.run = run
+ self.server_supports_delete_file_with_project_id: bool | None = None
+ super().__init__(dict(attrs))
+
+ @property
+ def size(self):
+ """Returns the size of the file in bytes."""
+ size_bytes = self._attrs["sizeBytes"]
+ if size_bytes is not None:
+ return int(size_bytes)
+ return 0
+
+ @property
+ def path_uri(self) -> str:
+ """Returns the URI path to the file in the storage bucket.
+
+ Returns:
+ str: The S3 URI (e.g., 's3://bucket/path/to/file') if the file is stored in S3,
+ the direct URL if it's a reference file, or an empty string if unavailable.
+ """
+ if not (direct_url := self._attrs.get("directUrl")):
+ wandb.termwarn("Unable to find direct_url of file")
+ return ""
+
+ # For reference files, both the directUrl and the url are just the path to the file in the bucket
+ if direct_url == self._attrs.get("url"):
+ return direct_url
+
+ try:
+ return utils.parse_s3_url_to_s3_uri(direct_url)
+ except ValueError:
+ wandb.termwarn("path_uri is only available for files stored in S3")
+ return ""
+
+ @normalize_exceptions
+ @retry.retriable(
+ retry_timedelta=RETRY_TIMEDELTA,
+ check_retry_fn=util.no_retry_auth,
+ retryable_exceptions=(RetryError, requests.RequestException),
+ )
+ def download(
+ self,
+ root: str = ".",
+ replace: bool = False,
+ exist_ok: bool = False,
+ api: Api | None = None,
+ ) -> io.TextIOWrapper:
+ """Downloads a file previously saved by a run from the wandb server.
+
+ Args:
+ root: Local directory to save the file. Defaults to the
+ current working directory (".").
+ replace: If `True`, download will overwrite a local file
+ if it exists. Defaults to `False`.
+ exist_ok: If `True`, will not raise ValueError if file already
+ exists and will not re-download unless replace=True.
+ Defaults to `False`.
+ api: If specified, the `Api` instance used to download the file.
+
+ Raises:
+ `ValueError` if file already exists, `replace=False` and
+ `exist_ok=False`.
+ """
+ if api is None:
+ api = wandb.Api()
+
+ path = os.path.join(root, self.name)
+ if os.path.exists(path) and not replace:
+ if exist_ok:
+ return open(path)
+ else:
+ raise ValueError(
+ "File already exists, pass replace=True to overwrite or exist_ok=True to leave it as is and don't error."
+ )
+
+ util.download_file_from_url(path, self.url, api.api_key)
+ return open(path)
+
+ @normalize_exceptions
+ def delete(self):
+ """Delete the file from the W&B server."""
+ project_id_mutation_fragment = ""
+ project_id_variable_fragment = ""
+ variable_values = {
+ "files": [self.id],
+ }
+
+ # Add projectId to mutation and variables if the server supports it.
+ # Otherwise, do not include projectId in mutation for older server versions which do not support it.
+ if self._server_accepts_project_id_for_delete_file():
+ variable_values["projectId"] = self.run._project_internal_id
+ project_id_variable_fragment = ", $projectId: Int"
+ project_id_mutation_fragment = "projectId: $projectId"
+
+ mutation_string = """
+ mutation deleteFiles($files: [ID!]!{}) {{
+ deleteFiles(input: {{
+ files: $files
+ {}
+ }}) {{
+ success
+ }}
+ }}
+ """.format(project_id_variable_fragment, project_id_mutation_fragment)
+ mutation = gql(mutation_string)
+
+ self.client.execute(
+ mutation,
+ variable_values=variable_values,
+ )
+
+ def __repr__(self):
+ return "".format(
+ self.name,
+ self.mimetype,
+ util.to_human_size(self.size, units=util.POW_2_BYTES),
+ )
+
+ @normalize_exceptions
+ def _server_accepts_project_id_for_delete_file(self) -> bool:
+ """Returns True if the server supports deleting files with a projectId.
+
+ This check is done by utilizing GraphQL introspection in the available fields on the DeleteFiles API.
+ """
+ query_string = """
+ query ProbeDeleteFilesProjectIdInput {
+ DeleteFilesProjectIdInputType: __type(name:"DeleteFilesInput") {
+ inputFields{
+ name
+ }
+ }
+ }
+ """
+
+ # Only perform the query once to avoid extra network calls
+ if self.server_supports_delete_file_with_project_id is None:
+ query = gql(query_string)
+ res = self.client.execute(query)
+
+ # If projectId is in the inputFields, the server supports deleting files with a projectId
+ self.server_supports_delete_file_with_project_id = "projectId" in [
+ x["name"]
+ for x in (
+ res.get("DeleteFilesProjectIdInputType", {}).get(
+ "inputFields", [{}]
+ )
+ )
+ ]
+
+ return self.server_supports_delete_file_with_project_id
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/history.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/history.py
new file mode 100644
index 0000000000000000000000000000000000000000..24071e1395fa95ace5a0b821c7ed3068948605db
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/history.py
@@ -0,0 +1,203 @@
+"""W&B Public API for Run History.
+
+This module provides classes for efficiently scanning and sampling run
+history data.
+
+Note:
+ This module is part of the W&B Public API and provides methods
+ to access run history data. It handles pagination automatically and offers
+ both complete and sampled access to metrics logged during training runs.
+"""
+
+from __future__ import annotations
+
+import json
+
+from wandb_gql import gql
+
+from wandb.apis.normalize import normalize_exceptions
+from wandb.apis.public import api, runs
+
+
+class HistoryScan:
+ """Iterator for scanning complete run history.
+
+
+ """
+
+ QUERY = gql(
+ """
+ query HistoryPage($entity: String!, $project: String!, $run: String!, $minStep: Int64!, $maxStep: Int64!, $pageSize: Int!) {
+ project(name: $project, entityName: $entity) {
+ run(name: $run) {
+ history(minStep: $minStep, maxStep: $maxStep, samples: $pageSize)
+ }
+ }
+ }
+ """
+ )
+
+ def __init__(
+ self,
+ client: api.RetryingClient,
+ run: api.public.runs.Run,
+ min_step: int,
+ max_step: int,
+ page_size: int = 1000,
+ ):
+ """Initialize a HistoryScan instance.
+
+ Args:
+ client: The client instance to use for making API calls to the W&B backend.
+ run: The run object whose history is to be scanned.
+ min_step: The minimum step to start scanning from.
+ max_step: The maximum step to scan up to.
+ page_size: Number of history rows to fetch per page.
+ Default page_size is 1000.
+ """
+ self.client = client
+ self.run = run
+ self.page_size = page_size
+ self.min_step = min_step
+ self.max_step = max_step
+ self.page_offset = min_step # minStep for next page
+ self.scan_offset = 0 # index within current page of rows
+ self.rows = [] # current page of rows
+
+ def __iter__(self):
+ self.page_offset = self.min_step
+ self.scan_offset = 0
+ self.rows = []
+ return self
+
+ def __next__(self):
+ """Return the next row of history data with automatic pagination.
+
+
+ """
+ while True:
+ if self.scan_offset < len(self.rows):
+ row = self.rows[self.scan_offset]
+ self.scan_offset += 1
+ return row
+ if self.page_offset >= self.max_step:
+ raise StopIteration()
+ self._load_next()
+
+ next = __next__
+
+ @normalize_exceptions
+ def _load_next(self):
+ max_step = self.page_offset + self.page_size
+ if max_step > self.max_step:
+ max_step = self.max_step
+ variables = {
+ "entity": self.run.entity,
+ "project": self.run.project,
+ "run": self.run.id,
+ "minStep": int(self.page_offset),
+ "maxStep": int(max_step),
+ "pageSize": int(self.page_size),
+ }
+
+ res = self.client.execute(self.QUERY, variable_values=variables)
+ res = res["project"]["run"]["history"]
+ self.rows = [json.loads(row) for row in res]
+ self.page_offset += self.page_size
+ self.scan_offset = 0
+
+
+class SampledHistoryScan:
+ """Iterator for sampling run history data.
+
+
+ """
+
+ QUERY = gql(
+ """
+ query SampledHistoryPage($entity: String!, $project: String!, $run: String!, $spec: JSONString!) {
+ project(name: $project, entityName: $entity) {
+ run(name: $run) {
+ sampledHistory(specs: [$spec])
+ }
+ }
+ }
+ """
+ )
+
+ def __init__(
+ self,
+ client: api.RetryingClient,
+ run: runs.Run,
+ keys: list,
+ min_step: int,
+ max_step: int,
+ page_size: int = 1000,
+ ):
+ """Initialize a SampledHistoryScan instance.
+
+ Args:
+ client: The client instance to use for making API calls to the W&B backend.
+ run: The run object whose history is to be sampled.
+ keys: List of keys to sample from the history.
+ min_step: The minimum step to start sampling from.
+ max_step: The maximum step to sample up to.
+ page_size: Number of sampled history rows to fetch per page.
+ Default page_size is 1000.
+ """
+ self.client = client
+ self.run = run
+ self.keys = keys
+ self.page_size = page_size
+ self.min_step = min_step
+ self.max_step = max_step
+ self.page_offset = min_step # minStep for next page
+ self.scan_offset = 0 # index within current page of rows
+ self.rows = [] # current page of rows
+
+ def __iter__(self):
+ self.page_offset = self.min_step
+ self.scan_offset = 0
+ self.rows = []
+ return self
+
+ def __next__(self):
+ """Return the next row of sampled history data with automatic pagination.
+
+
+ """
+ while True:
+ if self.scan_offset < len(self.rows):
+ row = self.rows[self.scan_offset]
+ self.scan_offset += 1
+ return row
+ if self.page_offset >= self.max_step:
+ raise StopIteration()
+ self._load_next()
+
+ next = __next__
+
+ @normalize_exceptions
+ def _load_next(self):
+ max_step = self.page_offset + self.page_size
+ if max_step > self.max_step:
+ max_step = self.max_step
+ variables = {
+ "entity": self.run.entity,
+ "project": self.run.project,
+ "run": self.run.id,
+ "spec": json.dumps(
+ {
+ "keys": self.keys,
+ "minStep": int(self.page_offset),
+ "maxStep": int(max_step),
+ "samples": int(self.page_size),
+ }
+ ),
+ }
+
+ res = self.client.execute(self.QUERY, variable_values=variables)
+ res = res["project"]["run"]["sampledHistory"]
+ self.rows = res[0]
+ self.page_offset += self.page_size
+ self.scan_offset = 0
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/integrations.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/integrations.py
new file mode 100644
index 0000000000000000000000000000000000000000..2081f001937d9bd6cb6a324bb23684181fb0095d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/integrations.py
@@ -0,0 +1,203 @@
+"""W&B Public API for integrations.
+
+This module provides classes for interacting with W&B integrations.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Iterable
+
+from pydantic import ValidationError
+from typing_extensions import override
+from wandb_gql import gql
+from wandb_graphql.language.ast import Document
+
+from wandb.apis.paginator import Paginator
+
+if TYPE_CHECKING:
+ from wandb.apis.paginator import _Client
+ from wandb.automations import Integration, SlackIntegration, WebhookIntegration
+ from wandb.automations._generated import (
+ GenericWebhookIntegrationConnectionFields,
+ IntegrationConnectionFields,
+ SlackIntegrationConnectionFields,
+ )
+
+
+class Integrations(Paginator["Integration"]):
+ """An lazy iterator of `Integration` objects."""
+
+ last_response: IntegrationConnectionFields | None
+ _query: Document
+
+ def __init__(self, client: _Client, variables: dict[str, Any], per_page: int = 50):
+ from wandb.automations._generated import INTEGRATIONS_BY_ENTITY_GQL
+
+ super().__init__(client, variables, per_page=per_page)
+ # All integrations for entity
+ self._query = gql(INTEGRATIONS_BY_ENTITY_GQL)
+
+ @property
+ def more(self) -> bool:
+ """Whether there are more Integrations to fetch.
+
+
+ """
+ if self.last_response is None:
+ return True
+ return self.last_response.page_info.has_next_page
+
+ @property
+ def cursor(self) -> str | None:
+ """The start cursor to use for the next page.
+
+
+ """
+ if self.last_response is None:
+ return None
+ return self.last_response.page_info.end_cursor
+
+ @override
+ def _update_response(self) -> None:
+ """Fetch and parse the response data for the current page."""
+ from wandb.automations._generated import IntegrationConnectionFields
+
+ data: dict[str, Any] = self.client.execute(
+ self._query, variable_values=self.variables
+ )
+ try:
+ page_data = data["entity"]["integrations"]
+ self.last_response = IntegrationConnectionFields.model_validate(page_data)
+ except (LookupError, AttributeError, ValidationError) as e:
+ raise ValueError("Unexpected response data") from e
+
+ def convert_objects(self) -> Iterable[Integration]:
+ """Parse the page data into a list of integrations."""
+ from wandb.automations.integrations import _IntegrationEdge
+
+ page = self.last_response
+ return [_IntegrationEdge.model_validate(edge).node for edge in page.edges]
+
+
+class WebhookIntegrations(Paginator["WebhookIntegration"]):
+ """An lazy iterator of `WebhookIntegration` objects.
+
+
+ """
+
+ last_response: GenericWebhookIntegrationConnectionFields | None
+ _query: Document
+
+ def __init__(self, client: _Client, variables: dict[str, Any], per_page: int = 50):
+ from wandb.automations._generated import (
+ GENERIC_WEBHOOK_INTEGRATIONS_BY_ENTITY_GQL,
+ )
+
+ super().__init__(client, variables, per_page=per_page)
+ # Webhook integrations for entity
+ self._query = gql(GENERIC_WEBHOOK_INTEGRATIONS_BY_ENTITY_GQL)
+
+ @property
+ def more(self) -> bool:
+ """Whether there are more webhook integrations to fetch."""
+ if self.last_response is None:
+ return True
+ return self.last_response.page_info.has_next_page
+
+ @property
+ def cursor(self) -> str | None:
+ """The start cursor to use for the next page."""
+ if self.last_response is None:
+ return None
+ return self.last_response.page_info.end_cursor
+
+ @override
+ def _update_response(self) -> None:
+ """Fetch and parse the response data for the current page."""
+ from wandb.automations._generated import (
+ GenericWebhookIntegrationConnectionFields,
+ )
+
+ data: dict[str, Any] = self.client.execute(
+ self._query, variable_values=self.variables
+ )
+ try:
+ page_data = data["entity"]["integrations"]
+ self.last_response = (
+ GenericWebhookIntegrationConnectionFields.model_validate(page_data)
+ )
+ except (LookupError, AttributeError, ValidationError) as e:
+ raise ValueError("Unexpected response data") from e
+
+ def convert_objects(self) -> Iterable[WebhookIntegration]:
+ """Parse the page data into a list of webhook integrations."""
+ from wandb.automations import WebhookIntegration
+
+ typename = "GenericWebhookIntegration"
+ return [
+ # Filter on typename__ needed because the GQL response still
+ # includes all integration types
+ WebhookIntegration.model_validate(node)
+ for edge in self.last_response.edges
+ if (node := edge.node) and (node.typename__ == typename)
+ ]
+
+
+class SlackIntegrations(Paginator["SlackIntegration"]):
+ """An lazy iterator of `SlackIntegration` objects.
+
+
+ """
+
+ last_response: SlackIntegrationConnectionFields | None
+ _query: Document
+
+ def __init__(self, client: _Client, variables: dict[str, Any], per_page: int = 50):
+ from wandb.automations._generated import SLACK_INTEGRATIONS_BY_ENTITY_GQL
+
+ super().__init__(client, variables, per_page=per_page)
+ # Slack integrations for entity
+ self._query = gql(SLACK_INTEGRATIONS_BY_ENTITY_GQL)
+
+ @property
+ def more(self) -> bool:
+ """Whether there are more Slack integrations to fetch."""
+ if self.last_response is None:
+ return True
+ return self.last_response.page_info.has_next_page
+
+ @property
+ def cursor(self) -> str | None:
+ """The start cursor to use for the next page."""
+ if self.last_response is None:
+ return None
+ return self.last_response.page_info.end_cursor
+
+ @override
+ def _update_response(self) -> None:
+ """Fetch and parse the response data for the current page."""
+ from wandb.automations._generated import SlackIntegrationConnectionFields
+
+ data: dict[str, Any] = self.client.execute(
+ self._query, variable_values=self.variables
+ )
+ try:
+ page_data = data["entity"]["integrations"]
+ self.last_response = SlackIntegrationConnectionFields.model_validate(
+ page_data
+ )
+ except (LookupError, AttributeError, ValidationError) as e:
+ raise ValueError("Unexpected response data") from e
+
+ def convert_objects(self) -> Iterable[SlackIntegration]:
+ """Parse the page data into a list of Slack integrations."""
+ from wandb.automations import SlackIntegration
+
+ typename = "SlackIntegration"
+ return [
+ # Filter on typename__ needed because the GQL response still
+ # includes all integration types
+ SlackIntegration.model_validate(node)
+ for edge in self.last_response.edges
+ if (node := edge.node) and (node.typename__ == typename)
+ ]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/jobs.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/jobs.py
new file mode 100644
index 0000000000000000000000000000000000000000..eaffa19acc97c8dce6d9e4197585fc2ff17e1d02
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/jobs.py
@@ -0,0 +1,744 @@
+"""W&B Public API for management Launch Jobs and Launch Queues.
+
+This module provides classes for managing W&B jobs, queued runs, and run
+queues.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import time
+from typing import TYPE_CHECKING, Any, Literal, Mapping
+
+from wandb_gql import gql
+
+import wandb
+from wandb import util
+from wandb.apis import public
+from wandb.apis.normalize import normalize_exceptions
+from wandb.errors import CommError
+from wandb.sdk.artifacts.artifact_state import ArtifactState
+from wandb.sdk.data_types._dtypes import InvalidType, Type, TypeRegistry
+from wandb.sdk.launch.errors import LaunchError
+from wandb.sdk.launch.utils import (
+ LAUNCH_DEFAULT_PROJECT,
+ _fetch_git_repo,
+ apply_patch,
+ convert_jupyter_notebook_to_script,
+)
+
+if TYPE_CHECKING:
+ from wandb.apis.public import Api, RetryingClient
+
+
+class Job:
+ _name: str
+ _input_types: Type
+ _output_types: Type
+ _entity: str
+ _project: str
+ _entrypoint: list[str]
+ _notebook_job: bool
+ _partial: bool
+
+ def __init__(self, api: Api, name, path: str | None = None) -> None:
+ try:
+ self._job_artifact = api._artifact(name, type="job")
+ except CommError:
+ raise CommError(f"Job artifact {name} not found")
+ if path:
+ self._fpath = path
+ self._job_artifact.download(root=path)
+ else:
+ self._fpath = self._job_artifact.download()
+ self._name = name
+ self._api = api
+ self._entity = api.default_entity
+
+ with open(os.path.join(self._fpath, "wandb-job.json")) as f:
+ self._job_info: Mapping[str, Any] = json.load(f)
+ source_info = self._job_info.get("source", {})
+ # only use notebook job if entrypoint not set and notebook is set
+ self._notebook_job = source_info.get("notebook", False)
+ self._entrypoint = source_info.get("entrypoint")
+ self._dockerfile = source_info.get("dockerfile")
+ self._build_context = source_info.get("build_context")
+ self._base_image = source_info.get("base_image")
+ self._args = source_info.get("args")
+ self._partial = self._job_info.get("_partial", False)
+ self._requirements_file = os.path.join(self._fpath, "requirements.frozen.txt")
+ self._input_types = TypeRegistry.type_from_dict(
+ self._job_info.get("input_types")
+ )
+ self._output_types = TypeRegistry.type_from_dict(
+ self._job_info.get("output_types")
+ )
+ if self._job_info.get("source_type") == "artifact":
+ self._set_configure_launch_project(self._configure_launch_project_artifact)
+ if self._job_info.get("source_type") == "repo":
+ self._set_configure_launch_project(self._configure_launch_project_repo)
+ if self._job_info.get("source_type") == "image":
+ self._set_configure_launch_project(self._configure_launch_project_container)
+
+ @property
+ def name(self):
+ """The name of the job."""
+ return self._name
+
+ def _set_configure_launch_project(self, func):
+ self.configure_launch_project = func
+
+ def _get_code_artifact(self, artifact_string):
+ artifact_string, base_url, is_id = util.parse_artifact_string(artifact_string)
+ if is_id:
+ code_artifact = wandb.Artifact._from_id(artifact_string, self._api._client)
+ else:
+ code_artifact = self._api._artifact(name=artifact_string, type="code")
+ if code_artifact is None:
+ raise LaunchError("No code artifact found")
+ if code_artifact.state == ArtifactState.DELETED:
+ raise LaunchError(
+ f"Job {self.name} references deleted code artifact {code_artifact.name}"
+ )
+ return code_artifact
+
+ def _configure_launch_project_notebook(self, launch_project):
+ new_fname = convert_jupyter_notebook_to_script(
+ self._entrypoint[-1], launch_project.project_dir
+ )
+ new_entrypoint = self._entrypoint
+ new_entrypoint[-1] = new_fname
+ launch_project.set_job_entry_point(new_entrypoint)
+
+ def _configure_launch_project_repo(self, launch_project):
+ git_info = self._job_info.get("source", {}).get("git", {})
+ _fetch_git_repo(
+ launch_project.project_dir,
+ git_info["remote"],
+ git_info["commit"],
+ )
+ if os.path.exists(os.path.join(self._fpath, "diff.patch")):
+ with open(os.path.join(self._fpath, "diff.patch")) as f:
+ apply_patch(f.read(), launch_project.project_dir)
+ shutil.copy(self._requirements_file, launch_project.project_dir)
+ launch_project.python_version = self._job_info.get("runtime")
+ if self._notebook_job:
+ self._configure_launch_project_notebook(launch_project)
+ else:
+ launch_project.set_job_entry_point(self._entrypoint)
+
+ if self._dockerfile:
+ launch_project.set_job_dockerfile(self._dockerfile)
+ if self._build_context:
+ launch_project.set_job_build_context(self._build_context)
+ if self._base_image:
+ launch_project.set_job_base_image(self._base_image)
+
+ def _configure_launch_project_artifact(self, launch_project):
+ artifact_string = self._job_info.get("source", {}).get("artifact")
+ if artifact_string is None:
+ raise LaunchError(f"Job {self.name} had no source artifact")
+
+ code_artifact = self._get_code_artifact(artifact_string)
+ launch_project.python_version = self._job_info.get("runtime")
+ shutil.copy(self._requirements_file, launch_project.project_dir)
+
+ code_artifact.download(launch_project.project_dir)
+
+ if self._notebook_job:
+ self._configure_launch_project_notebook(launch_project)
+ else:
+ launch_project.set_job_entry_point(self._entrypoint)
+
+ if self._dockerfile:
+ launch_project.set_job_dockerfile(self._dockerfile)
+ if self._build_context:
+ launch_project.set_job_build_context(self._build_context)
+ if self._base_image:
+ launch_project.set_job_base_image(self._base_image)
+
+ def _configure_launch_project_container(self, launch_project):
+ launch_project.docker_image = self._job_info.get("source", {}).get("image")
+ if launch_project.docker_image is None:
+ raise LaunchError(
+ "Job had malformed source dictionary without an image key"
+ )
+ if self._entrypoint:
+ launch_project.set_job_entry_point(self._entrypoint)
+
+ def set_entrypoint(self, entrypoint: list[str]):
+ """Set the entrypoint for the job."""
+ self._entrypoint = entrypoint
+
+ def call(
+ self,
+ config,
+ project=None,
+ entity=None,
+ queue=None,
+ resource="local-container",
+ resource_args=None,
+ template_variables=None,
+ project_queue=None,
+ priority=None,
+ ):
+ """Call the job with the given configuration.
+
+ Args:
+ config (dict): The configuration to pass to the job.
+ This should be a dictionary containing key-value pairs that
+ match the input types defined in the job.
+ project (str, optional): The project to log the run to. Defaults
+ to the job's project.
+ entity (str, optional): The entity to log the run under. Defaults
+ to the job's entity.
+ queue (str, optional): The name of the queue to enqueue the job to.
+ Defaults to None.
+ resource (str, optional): The resource type to use for execution.
+ Defaults to "local-container".
+ resource_args (dict, optional): Additional arguments for the
+ resource type. Defaults to None.
+ template_variables (dict, optional): Template variables to use for
+ the job. Defaults to None.
+ project_queue (str, optional): The project that manages the queue.
+ Defaults to None.
+ priority (int, optional): The priority of the queued run.
+ Defaults to None.
+ """
+ from wandb.sdk.launch import _launch_add
+
+ run_config = {}
+ for key, item in config.items():
+ if util._is_artifact_object(item):
+ if isinstance(item, wandb.Artifact) and item.is_draft():
+ raise ValueError("Cannot queue jobs with unlogged artifacts")
+ run_config[key] = util.artifact_to_json(item)
+
+ run_config.update(config)
+
+ assigned_config_type = self._input_types.assign(run_config)
+ if self._partial:
+ wandb.termwarn(
+ "Launching manually created job for the first time, can't verify types"
+ )
+ else:
+ if isinstance(assigned_config_type, InvalidType):
+ raise TypeError(self._input_types.explain(run_config))
+
+ queued_run = _launch_add.launch_add(
+ job=self._name,
+ config={"overrides": {"run_config": run_config}},
+ template_variables=template_variables,
+ project=project or self._project,
+ entity=entity or self._entity,
+ queue_name=queue,
+ resource=resource,
+ project_queue=project_queue,
+ resource_args=resource_args,
+ priority=priority,
+ )
+ return queued_run
+
+
+class QueuedRun:
+ """A single queued run associated with an entity and project.
+
+ Args:
+ entity: The entity associated with the queued run.
+ project (str): The project where runs executed by the queue are logged to.
+ queue_name (str): The name of the queue.
+ run_queue_item_id (int): The id of the run queue item.
+ project_queue (str): The project that manages the queue.
+ priority (str): The priority of the queued run.
+
+ Call `run = queued_run.wait_until_running()` or
+ `run = queued_run.wait_until_finished()` to access the run.
+ """
+
+ def __init__(
+ self,
+ client,
+ entity,
+ project,
+ queue_name,
+ run_queue_item_id,
+ project_queue=LAUNCH_DEFAULT_PROJECT,
+ priority=None,
+ ):
+ self.client = client
+ self._entity = entity
+ self._project = project
+ self._queue_name = queue_name
+ self._run_queue_item_id = run_queue_item_id
+ self.sweep = None
+ self._run = None
+ self.project_queue = project_queue
+ self.priority = priority
+
+ @property
+ def queue_name(self):
+ """The name of the queue."""
+ return self._queue_name
+
+ @property
+ def id(self):
+ """The id of the queued run."""
+ return self._run_queue_item_id
+
+ @property
+ def project(self):
+ """The project associated with the queued run."""
+ return self._project
+
+ @property
+ def entity(self):
+ """The entity associated with the queued run."""
+ return self._entity
+
+ @property
+ def state(self):
+ """The state of the queued run."""
+ item = self._get_item()
+ if item:
+ return item["state"].lower()
+
+ raise ValueError(
+ f"Could not find QueuedRunItem associated with id: {self.id} on queue {self.queue_name} at itemId: {self.id}"
+ )
+
+ @normalize_exceptions
+ def _get_run_queue_item_legacy(self) -> dict:
+ query = gql(
+ """
+ query GetRunQueueItem($projectName: String!, $entityName: String!, $runQueue: String!) {
+ project(name: $projectName, entityName: $entityName) {
+ runQueue(name:$runQueue) {
+ runQueueItems {
+ edges {
+ node {
+ id
+ state
+ associatedRunId
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+ )
+ variable_values = {
+ "projectName": self.project_queue,
+ "entityName": self._entity,
+ "runQueue": self.queue_name,
+ }
+ res = self.client.execute(query, variable_values)
+
+ for item in res["project"]["runQueue"]["runQueueItems"]["edges"]:
+ if str(item["node"]["id"]) == str(self.id):
+ return item["node"]
+
+ @normalize_exceptions
+ def _get_item(self):
+ query = gql(
+ """
+ query GetRunQueueItem($projectName: String!, $entityName: String!, $runQueue: String!, $itemId: ID!) {
+ project(name: $projectName, entityName: $entityName) {
+ runQueue(name: $runQueue) {
+ runQueueItem(id: $itemId) {
+ id
+ state
+ associatedRunId
+ }
+ }
+ }
+ }
+ """
+ )
+ variable_values = {
+ "projectName": self.project_queue,
+ "entityName": self._entity,
+ "runQueue": self.queue_name,
+ "itemId": self.id,
+ }
+ try:
+ res = self.client.execute(query, variable_values) # exception w/ old server
+ if res["project"]["runQueue"].get("runQueueItem") is not None:
+ return res["project"]["runQueue"]["runQueueItem"]
+ except Exception as e:
+ if "Cannot query field" not in str(e):
+ raise LaunchError(f"Unknown exception: {e}")
+
+ return self._get_run_queue_item_legacy()
+
+ @normalize_exceptions
+ def wait_until_finished(self):
+ """Wait for the queued run to complete and return the finished run."""
+ if not self._run:
+ self.wait_until_running()
+
+ self._run.wait_until_finished()
+ # refetch run to get updated summary
+ self._run.load(force=True)
+ return self._run
+
+ @normalize_exceptions
+ def delete(self, delete_artifacts=False):
+ """Delete the given queued run from the wandb backend."""
+ query = gql(
+ """
+ query fetchRunQueuesFromProject($entityName: String!, $projectName: String!, $runQueueName: String!) {
+ project(name: $projectName, entityName: $entityName) {
+ runQueue(name: $runQueueName) {
+ id
+ }
+ }
+ }
+ """
+ )
+
+ res = self.client.execute(
+ query,
+ variable_values={
+ "entityName": self.entity,
+ "projectName": self.project_queue,
+ "runQueueName": self.queue_name,
+ },
+ )
+
+ if res["project"].get("runQueue") is not None:
+ queue_id = res["project"]["runQueue"]["id"]
+
+ mutation = gql(
+ """
+ mutation DeleteFromRunQueue(
+ $queueID: ID!,
+ $runQueueItemId: ID!
+ ) {
+ deleteFromRunQueue(input: {
+ queueID: $queueID
+ runQueueItemId: $runQueueItemId
+ }) {
+ success
+ clientMutationId
+ }
+ }
+ """
+ )
+ self.client.execute(
+ mutation,
+ variable_values={
+ "queueID": queue_id,
+ "runQueueItemId": self._run_queue_item_id,
+ },
+ )
+
+ @normalize_exceptions
+ def wait_until_running(self):
+ """Wait until the queued run is running and return the run."""
+ if self._run is not None:
+ return self._run
+
+ while True:
+ # sleep here to hide an ugly warning
+ time.sleep(2)
+ item = self._get_item()
+ if item and item["associatedRunId"] is not None:
+ try:
+ self._run = public.Run(
+ self.client,
+ self._entity,
+ self.project,
+ item["associatedRunId"],
+ None,
+ )
+ self._run_id = item["associatedRunId"]
+ except ValueError as e:
+ wandb.termwarn(str(e))
+ else:
+ return self._run
+ elif item:
+ wandb.termlog("Waiting for run to start")
+
+ time.sleep(3)
+
+ def __repr__(self):
+ return f" None:
+ self._name: str = name
+ self._client = client
+ self._entity = entity
+ self._prioritization_mode = prioritization_mode
+ self._access = _access
+ self._default_resource_config_id = _default_resource_config_id
+ self._default_resource_config = _default_resource_config
+ self._template_variables = None
+ self._type = None
+ self._items = None
+ self._id = None
+
+ @property
+ def name(self):
+ """The name of the queue."""
+ return self._name
+
+ @property
+ def entity(self):
+ """The entity that owns the queue."""
+ return self._entity
+
+ @property
+ def prioritization_mode(self) -> RunQueuePrioritizationMode:
+ """The prioritization mode of the queue.
+
+ Can be set to "DISABLED" or "V0".
+ """
+ if self._prioritization_mode is None:
+ self._get_metadata()
+ return self._prioritization_mode
+
+ @property
+ def access(self) -> RunQueueAccessType:
+ """The access level of the queue."""
+ if self._access is None:
+ self._get_metadata()
+ return self._access
+
+ @property
+ def external_links(self) -> dict[str, str]:
+ """External resource links for the queue."""
+ if self._external_links is None:
+ self._get_metadata()
+ return self._external_links
+
+ @property
+ def type(self) -> RunQueueResourceType:
+ """The resource type for execution."""
+ if self._type is None:
+ if self._default_resource_config_id is None:
+ self._get_metadata()
+ self._get_default_resource_config()
+ return self._type
+
+ @property
+ def default_resource_config(self):
+ """The default configuration for resources."""
+ if self._default_resource_config is None:
+ if self._default_resource_config_id is None:
+ self._get_metadata()
+ self._get_default_resource_config()
+ return self._default_resource_config
+
+ @property
+ def template_variables(self):
+ """Variables for resource templates."""
+ if self._template_variables is None:
+ if self._default_resource_config_id is None:
+ self._get_metadata()
+ self._get_default_resource_config()
+ return self._template_variables
+
+ @property
+ def id(self) -> str:
+ """The id of the queue."""
+ if self._id is None:
+ self._get_metadata()
+ return self._id
+
+ @property
+ def items(self) -> list[QueuedRun]:
+ """Up to the first 100 queued runs. Modifying this list will not modify the queue or any enqueued items!"""
+ # TODO(np): Add a paginated interface
+ if self._items is None:
+ self._get_items()
+ return self._items
+
+ @normalize_exceptions
+ def delete(self):
+ """Delete the run queue from the wandb backend."""
+ query = gql(
+ """
+ mutation DeleteRunQueue($id: ID!) {
+ deleteRunQueues(input: {queueIDs: [$id]}) {
+ success
+ clientMutationId
+ }
+ }
+ """
+ )
+ variable_values = {"id": self.id}
+ res = self._client.execute(query, variable_values)
+ if res["deleteRunQueues"]["success"]:
+ self._id = None
+ self._access = None
+ self._default_resource_config_id = None
+ self._default_resource_config = None
+ self._items = None
+ else:
+ raise CommError(f"Failed to delete run queue {self.name}")
+
+ def __repr__(self):
+ return f""
+
+ @normalize_exceptions
+ def _get_metadata(self):
+ query = gql(
+ """
+ query GetRunQueueMetadata($projectName: String!, $entityName: String!, $runQueue: String!) {
+ project(name: $projectName, entityName: $entityName) {
+ runQueue(name: $runQueue) {
+ id
+ access
+ defaultResourceConfigID
+ prioritizationMode
+ externalLinks
+ }
+ }
+ }
+ """
+ )
+ variable_values = {
+ "projectName": LAUNCH_DEFAULT_PROJECT,
+ "entityName": self._entity,
+ "runQueue": self._name,
+ }
+ res = self._client.execute(query, variable_values)
+ self._id = res["project"]["runQueue"]["id"]
+ self._access = res["project"]["runQueue"]["access"]
+ self._default_resource_config_id = res["project"]["runQueue"][
+ "defaultResourceConfigID"
+ ]
+ self._external_links = res["project"]["runQueue"]["externalLinks"]
+ if self._default_resource_config_id is None:
+ self._default_resource_config = {}
+ self._prioritization_mode = res["project"]["runQueue"]["prioritizationMode"]
+
+ @normalize_exceptions
+ def _get_default_resource_config(self):
+ query = gql(
+ """
+ query GetDefaultResourceConfig($entityName: String!, $id: ID!) {
+ entity(name: $entityName) {
+ defaultResourceConfig(id: $id) {
+ config
+ resource
+ templateVariables {
+ name
+ schema
+ }
+ }
+ }
+ }
+ """
+ )
+ variable_values = {
+ "entityName": self._entity,
+ "id": self._default_resource_config_id,
+ }
+ res = self._client.execute(query, variable_values)
+ self._type = res["entity"]["defaultResourceConfig"]["resource"]
+ self._default_resource_config = res["entity"]["defaultResourceConfig"]["config"]
+ self._template_variables = res["entity"]["defaultResourceConfig"][
+ "templateVariables"
+ ]
+
+ @normalize_exceptions
+ def _get_items(self):
+ query = gql(
+ """
+ query GetRunQueueItems($projectName: String!, $entityName: String!, $runQueue: String!) {
+ project(name: $projectName, entityName: $entityName) {
+ runQueue(name: $runQueue) {
+ runQueueItems(first: 100) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+ )
+ variable_values = {
+ "projectName": LAUNCH_DEFAULT_PROJECT,
+ "entityName": self._entity,
+ "runQueue": self._name,
+ }
+ res = self._client.execute(query, variable_values)
+ self._items = []
+ for item in res["project"]["runQueue"]["runQueueItems"]["edges"]:
+ self._items.append(
+ QueuedRun(
+ self._client,
+ self._entity,
+ LAUNCH_DEFAULT_PROJECT,
+ self._name,
+ item["node"]["id"],
+ )
+ )
+
+ @classmethod
+ def create(
+ cls,
+ name: str,
+ resource: RunQueueResourceType,
+ entity: str | None = None,
+ prioritization_mode: RunQueuePrioritizationMode | None = None,
+ config: dict | None = None,
+ template_variables: dict | None = None,
+ ) -> RunQueue:
+ """Create a RunQueue.
+
+ Args:
+ name: The name of the run queue to create.
+ resource: The resource type for execution.
+ entity: The entity (user or team) that will own the queue.
+ Defaults to the default entity of the API client.
+ prioritization_mode: The prioritization mode for the queue.
+ Can be "DISABLED" or "V0". Defaults to None.
+ config: Optional dictionary for the default resource
+ configuration. Defaults to None.
+ template_variables: Optional dictionary for template variables
+ used in the resource configuration.
+ """
+ public_api = Api()
+ return public_api.create_run_queue(
+ name, resource, entity, prioritization_mode, config, template_variables
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/projects.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/projects.py
new file mode 100644
index 0000000000000000000000000000000000000000..59833de451203d6c5626cc80176a42209e33bab1
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/projects.py
@@ -0,0 +1,278 @@
+"""W&B Public API for Project objects.
+
+This module provides classes for interacting with W&B projects and their
+associated data.
+
+Example:
+```python
+from wandb.apis.public import Api
+
+# Get all projects for an entity
+projects = Api().projects("entity")
+
+# Access project data
+for project in projects:
+ print(f"Project: {project.name}")
+ print(f"URL: {project.url}")
+
+ # Get artifact types
+ for artifact_type in project.artifacts_types():
+ print(f"Artifact Type: {artifact_type.name}")
+
+ # Get sweeps
+ for sweep in project.sweeps():
+ print(f"Sweep ID: {sweep.id}")
+ print(f"State: {sweep.state}")
+```
+
+Note:
+ This module is part of the W&B Public API and provides methods to access
+ and manage projects. For creating new projects, use wandb.init()
+ with a new project name.
+"""
+
+from __future__ import annotations
+
+from requests import HTTPError
+from wandb_gql import gql
+
+from wandb.apis import public
+from wandb.apis.attrs import Attrs
+from wandb.apis.normalize import normalize_exceptions
+from wandb.apis.paginator import Paginator
+from wandb.apis.public.api import RetryingClient
+from wandb.apis.public.sweeps import Sweeps
+from wandb.sdk.lib import ipython
+
+PROJECT_FRAGMENT = """fragment ProjectFragment on Project {
+ id
+ name
+ entityName
+ createdAt
+ isBenchmark
+}"""
+
+
+class Projects(Paginator["Project"]):
+ """An lazy iterator of `Project` objects.
+
+ An iterable interface to access projects created and saved by the entity.
+
+ Args:
+ client (`wandb.apis.internal.Api`): The API client instance to use.
+ entity (str): The entity name (username or team) to fetch projects for.
+ per_page (int): Number of projects to fetch per request (default is 50).
+
+ Example:
+ ```python
+ from wandb.apis.public.api import Api
+
+ # Find projects that belong to this entity
+ projects = Api().projects(entity="entity")
+
+ # Iterate over files
+ for project in projects:
+ print(f"Project: {project.name}")
+ print(f"- URL: {project.url}")
+ print(f"- Created at: {project.created_at}")
+ print(f"- Is benchmark: {project.is_benchmark}")
+ ```
+ """
+
+ QUERY = gql(f"""#graphql
+ query Projects($entity: String, $cursor: String, $perPage: Int = 50) {{
+ models(entityName: $entity, after: $cursor, first: $perPage) {{
+ edges {{
+ node {{
+ ...ProjectFragment
+ }}
+ cursor
+ }}
+ pageInfo {{
+ endCursor
+ hasNextPage
+ }}
+ }}
+ }}
+ {PROJECT_FRAGMENT}
+ """)
+
+ def __init__(
+ self,
+ client: RetryingClient,
+ entity: str,
+ per_page: int = 50,
+ ) -> Projects:
+ """An iterable collection of `Project` objects.
+
+ Args:
+ client: The API client used to query W&B.
+ entity: The entity which owns the projects.
+ per_page: The number of projects to fetch per request to the API.
+ """
+ self.client = client
+ self.entity = entity
+ variables = {
+ "entity": self.entity,
+ }
+ super().__init__(client, variables, per_page)
+
+ @property
+ def length(self) -> None:
+ """Returns the total number of projects.
+
+ Note: This property is not available for projects.
+
+
+ """
+ # For backwards compatibility, even though this isn't a SizedPaginator
+ return None
+
+ @property
+ def more(self):
+ """Returns `True` if there are more projects to fetch. Returns
+ `False` if there are no more projects to fetch.
+
+
+ """
+ if self.last_response:
+ return self.last_response["models"]["pageInfo"]["hasNextPage"]
+ else:
+ return True
+
+ @property
+ def cursor(self):
+ """Returns the cursor position for pagination of project results.
+
+
+ """
+ if self.last_response:
+ return self.last_response["models"]["edges"][-1]["cursor"]
+ else:
+ return None
+
+ def convert_objects(self):
+ """Converts GraphQL edges to File objects.
+
+
+ """
+ return [
+ Project(self.client, self.entity, p["node"]["name"], p["node"])
+ for p in self.last_response["models"]["edges"]
+ ]
+
+ def __repr__(self):
+ return f""
+
+
+class Project(Attrs):
+ """A project is a namespace for runs.
+
+ Args:
+ client: W&B API client instance.
+ name (str): The name of the project.
+ entity (str): The entity name that owns the project.
+ """
+
+ QUERY = gql(f"""#graphql
+ query Project($project: String!, $entity: String!) {{
+ project(name: $project, entityName: $entity) {{
+ ...ProjectFragment
+ }}
+ }}
+ {PROJECT_FRAGMENT}
+ """)
+
+ def __init__(
+ self,
+ client: RetryingClient,
+ entity: str,
+ project: str,
+ attrs: dict,
+ ) -> Project:
+ """A single project associated with an entity.
+
+ Args:
+ client: The API client used to query W&B.
+ entity: The entity which owns the project.
+ project: The name of the project to query.
+ attrs: The attributes of the project.
+ """
+ super().__init__(dict(attrs))
+ self._is_loaded = bool(attrs)
+ self.client = client
+ self.name = project
+ self.entity = entity
+
+ def _load(self):
+ variable_values = {"project": self.name, "entity": self.entity}
+ try:
+ response = self.client.execute(self.QUERY, variable_values)
+ except HTTPError as e:
+ raise ValueError(f"Unable to fetch project ID: {variable_values!r}") from e
+
+ self._attrs = response["project"]
+ self._is_loaded = True
+
+ @property
+ def path(self):
+ """Returns the path of the project. The path is a list containing the
+ entity and project name."""
+ return [self.entity, self.name]
+
+ @property
+ def url(self):
+ """Returns the URL of the project."""
+ return self.client.app_url + "/".join(self.path + ["workspace"])
+
+ def to_html(self, height=420, hidden=False):
+ """Generate HTML containing an iframe displaying this project.
+
+
+ """
+ url = self.url + "?jupyter=true"
+ style = f"border:none;width:100%;height:{height}px;"
+ prefix = ""
+ if hidden:
+ style += "display:none;"
+ prefix = ipython.toggle_button("project")
+ return prefix + f""
+
+ def _repr_html_(self) -> str:
+ return self.to_html()
+
+ def __repr__(self):
+ return "".format("/".join(self.path))
+
+ @normalize_exceptions
+ def artifacts_types(self, per_page=50):
+ """Returns all artifact types associated with this project."""
+ return public.ArtifactTypes(self.client, self.entity, self.name)
+
+ @normalize_exceptions
+ def sweeps(self, per_page=50):
+ """Return a paginated collection of sweeps in this project.
+
+ Args:
+ per_page: The number of sweeps to fetch per request to the API.
+
+ Returns:
+ A `Sweeps` object, which is an iterable collection of `Sweep` objects.
+ """
+ return Sweeps(self.client, self.entity, self.name, per_page=per_page)
+
+ @property
+ def id(self) -> str:
+ if not self._is_loaded:
+ self._load()
+
+ if "id" not in self._attrs:
+ raise ValueError(f"Project {self.name} not found")
+
+ return self._attrs["id"]
+
+ def __getattr__(self, name: str):
+ if not self._is_loaded:
+ self._load()
+
+ return super().__getattr__(name)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/query_generator.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/query_generator.py
new file mode 100644
index 0000000000000000000000000000000000000000..def8ce18b74d9b452864bc5f25bbfeec147070ce
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/query_generator.py
@@ -0,0 +1,179 @@
+from __future__ import annotations
+
+
+class QueryGenerator:
+ """QueryGenerator is a helper object to write filters for runs.
+
+
+ """
+
+ INDIVIDUAL_OP_TO_MONGO = {
+ "!=": "$ne",
+ ">": "$gt",
+ ">=": "$gte",
+ "<": "$lt",
+ "<=": "$lte",
+ "IN": "$in",
+ "NIN": "$nin",
+ "REGEX": "$regex",
+ }
+ MONGO_TO_INDIVIDUAL_OP = {v: k for k, v in INDIVIDUAL_OP_TO_MONGO.items()}
+
+ GROUP_OP_TO_MONGO = {"AND": "$and", "OR": "$or"}
+ MONGO_TO_GROUP_OP = {v: k for k, v in GROUP_OP_TO_MONGO.items()}
+
+ def __init__(self):
+ pass
+
+ @classmethod
+ def format_order_key(cls, key: str):
+ """Format a key for sorting."""
+ if key.startswith(("+", "-")):
+ direction = key[0]
+ key = key[1:]
+ else:
+ direction = "-"
+ parts = key.split(".")
+ if len(parts) == 1:
+ # Assume the user meant summary_metrics if not a run column
+ if parts[0] not in ["createdAt", "updatedAt", "name", "sweep"]:
+ return direction + "summary_metrics." + parts[0]
+ # Assume summary metrics if prefix isn't known
+ elif parts[0] not in ["config", "summary_metrics", "tags"]:
+ return direction + ".".join(["summary_metrics"] + parts)
+ else:
+ return direction + ".".join(parts)
+
+ def _is_group(self, op):
+ return op.get("filters") is not None
+
+ def _is_individual(self, op):
+ return op.get("key") is not None
+
+ def _to_mongo_op_value(self, op, value):
+ if op == "=":
+ return value
+ else:
+ return {self.INDIVIDUAL_OP_TO_MONGO[op]: value}
+
+ def key_to_server_path(self, key):
+ """Convert a key dictionary to the corresponding server path string."""
+ if key["section"] == "config":
+ return "config." + key["name"]
+ elif key["section"] == "summary":
+ return "summary_metrics." + key["name"]
+ elif key["section"] == "keys_info":
+ return "keys_info.keys." + key["name"]
+ elif key["section"] == "run":
+ return key["name"]
+ elif key["section"] == "tags":
+ return "tags." + key["name"]
+ raise ValueError("Invalid key: {}".format(key))
+
+ def server_path_to_key(self, path):
+ """Convert a server path string to the corresponding key dictionary."""
+ if path.startswith("config."):
+ return {"section": "config", "name": path.split("config.", 1)[1]}
+ elif path.startswith("summary_metrics."):
+ return {"section": "summary", "name": path.split("summary_metrics.", 1)[1]}
+ elif path.startswith("keys_info.keys."):
+ return {"section": "keys_info", "name": path.split("keys_info.keys.", 1)[1]}
+ elif path.startswith("tags."):
+ return {"section": "tags", "name": path.split("tags.", 1)[1]}
+ else:
+ return {"section": "run", "name": path}
+
+ def keys_to_order(self, keys):
+ """Convert a list of key dictionaries to an order string."""
+ orders = []
+ for key in keys["keys"]:
+ order = self.key_to_server_path(key["key"])
+ if key.get("ascending"):
+ order = "+" + order
+ else:
+ order = "-" + order
+ orders.append(order)
+ # return ",".join(orders)
+ return orders
+
+ def order_to_keys(self, order):
+ """Convert an order string to a list of key dictionaries."""
+ keys = []
+ for k in order: # orderstr.split(","):
+ name = k[1:]
+ if k[0] == "+":
+ ascending = True
+ elif k[0] == "-":
+ ascending = False
+ else:
+ raise Exception("you must sort by ascending(+) or descending(-)")
+
+ key = {"key": {"section": "run", "name": name}, "ascending": ascending}
+ keys.append(key)
+
+ return {"keys": keys}
+
+ def _to_mongo_individual(self, filter):
+ if filter["key"]["name"] == "":
+ return None
+
+ if filter.get("value") is None and filter["op"] != "=" and filter["op"] != "!=":
+ return None
+
+ if filter.get("disabled") is not None and filter["disabled"]:
+ return None
+
+ if filter["key"]["section"] == "tags":
+ if filter["op"] == "IN":
+ return {"tags": {"$in": filter["value"]}}
+ if filter["value"] is False:
+ return {
+ "$or": [{"tags": None}, {"tags": {"$ne": filter["key"]["name"]}}]
+ }
+ else:
+ return {"tags": filter["key"]["name"]}
+ path = self.key_to_server_path(filter["key"])
+ if path is None:
+ return path
+ return {path: self._to_mongo_op_value(filter["op"], filter["value"])}
+
+ def filter_to_mongo(self, filter):
+ """Returns dictionary with filter format converted to MongoDB filter."""
+ if self._is_individual(filter):
+ return self._to_mongo_individual(filter)
+ elif self._is_group(filter):
+ return {
+ self.GROUP_OP_TO_MONGO[filter["op"]]: [
+ self.filter_to_mongo(f) for f in filter["filters"]
+ ]
+ }
+
+ def mongo_to_filter(self, filter):
+ """Returns dictionary with MongoDB filter converted to filter format."""
+ # Returns {"op": "OR", "filters": [{"op": "AND", "filters": []}]}
+ if filter is None:
+ return None # this covers the case where self.filter_to_mongo returns None.
+
+ group_op = None
+ for key in filter.keys():
+ # if self.MONGO_TO_GROUP_OP[key]:
+ if key in self.MONGO_TO_GROUP_OP:
+ group_op = key
+ break
+ if group_op is not None:
+ return {
+ "op": self.MONGO_TO_GROUP_OP[group_op],
+ "filters": [self.mongo_to_filter(f) for f in filter[group_op]],
+ }
+ else:
+ for k, v in filter.items():
+ if isinstance(v, dict):
+ # TODO: do we always have one key in this case?
+ op = next(iter(v.keys()))
+ return {
+ "key": self.server_path_to_key(k),
+ "op": self.MONGO_TO_INDIVIDUAL_OP[op],
+ "value": v[op],
+ }
+ else:
+ return {"key": self.server_path_to_key(k), "op": "=", "value": v}
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/registries/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/registries/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ba451b425be56a42905463a35c0cbe8c16b56fe
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/registries/__init__.py
@@ -0,0 +1,7 @@
+__all__ = [
+ "Registry", # doc:exclude
+ "Registries", # doc:exclude
+]
+
+from .registries_search import Registries
+from .registry import Registry
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/registries/_freezable_list.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/registries/_freezable_list.py
new file mode 100644
index 0000000000000000000000000000000000000000..14971f4d0dc2eda0c36ca5d8185b50e7d457c547
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/registries/_freezable_list.py
@@ -0,0 +1,176 @@
+from __future__ import annotations
+
+from itertools import chain
+from typing import (
+ Any,
+ Iterable,
+ Iterator,
+ MutableSequence,
+ Sequence,
+ TypeVar,
+ final,
+ overload,
+)
+
+from wandb._strutils import nameof
+
+T = TypeVar("T")
+
+
+@final
+class FreezableList(MutableSequence[T]):
+ """A list-like container type that only allows adding new items.
+
+ It tracks "saved" (immutable) and "draft" (mutable) items.
+ Items can be added, inserted, and removed while in draft state, but once frozen,
+ they become immutable. Unlike a set, duplicate items are allowed in the draft
+ state but duplicates already present in the saved state cannot be added.
+ Any initial items passed to the constructor are saved.
+ """
+
+ def __init__(self, iterable: Iterable[T] | None = None, /) -> None:
+ self._frozen: tuple[T, ...] = tuple(iterable or ())
+ self._draft: list[T] = []
+
+ def append(self, value: T) -> None:
+ """Append an item to the draft list. No duplicates are allowed."""
+ if (value in self._frozen) or (value in self._draft):
+ return
+ self._draft.append(value)
+
+ def remove(self, value: T) -> None:
+ """Remove the first occurrence of value from the draft list."""
+ if value in self._frozen:
+ raise ValueError(f"Cannot remove item from frozen list: {value!r}")
+ self._draft.remove(value)
+
+ def freeze(self) -> None:
+ """Freeze any draft items by adding them to the saved tuple."""
+ # Filter out duplicates already in saved before extending
+ new_items = tuple(item for item in self._draft if item not in self._frozen)
+ self._frozen = self._frozen + new_items
+ self._draft.clear()
+
+ def __eq__(self, value: object) -> bool:
+ if not isinstance(value, Sequence):
+ return NotImplemented
+ return list(self) == list(value)
+
+ def __contains__(self, value: Any) -> bool:
+ return value in self._frozen or value in self._draft
+
+ def __len__(self) -> int:
+ return len(self._frozen) + len(self._draft)
+
+ def __iter__(self) -> Iterator[T]:
+ return iter(chain(self._frozen, self._draft))
+
+ @overload
+ def __getitem__(self, index: int) -> T: ...
+
+ @overload
+ def __getitem__(self, index: slice) -> Sequence[T]: ...
+
+ def __getitem__(self, index: int | slice) -> T | Sequence[T]:
+ return [*self._frozen, *self._draft][index]
+
+ @overload
+ def __setitem__(self, index: int, value: T) -> None: ...
+
+ @overload
+ def __setitem__(self, index: slice, value: Iterable[T]) -> None: ...
+
+ def __setitem__(self, index: int | slice, value: T | Iterable[T]) -> None:
+ if isinstance(index, slice):
+ # Setting slices might affect saved items, disallow for simplicity
+ raise TypeError(f"{nameof(type(self))!r} does not support slice assignment")
+ else:
+ if value in self._frozen or value in self._draft:
+ return
+
+ # The frozen items are sequentially first and protected from changes
+ len_frozen = len(self._frozen)
+ size = len(self)
+
+ if (index >= size) or (index < -size):
+ raise IndexError("Index out of range")
+
+ draft_index = (index % size) - len_frozen
+ if draft_index < 0:
+ raise ValueError(f"Cannot assign to saved item at index {index!r}")
+ self._draft[draft_index] = value
+
+ @overload
+ def __delitem__(self, index: int) -> None: ...
+
+ @overload
+ def __delitem__(self, index: slice) -> None: ...
+
+ def __delitem__(self, index: int | slice) -> None:
+ if isinstance(index, slice):
+ raise TypeError(f"{nameof(type(self))!r} does not support slice deletion")
+ else:
+ # The frozen items are sequentially first and protected from changes
+ len_frozen = len(self._frozen)
+ size = len(self)
+
+ if (index >= size) or (index < -size):
+ raise IndexError("Index out of range")
+
+ draft_index = (index % size) - len_frozen
+ if draft_index < 0:
+ raise ValueError(f"Cannot delete saved item at index {index!r}")
+ del self._draft[draft_index]
+
+ def insert(self, index: int, value: T) -> None:
+ """Insert item before index.
+
+ Insertion is only allowed at indices corresponding to the draft portion
+ of the list (i.e., index >= len(frozen_items)). Negative indices are
+ interpreted relative to the combined length of frozen and draft items.
+ """
+ if value in self._frozen or value in self._draft:
+ # Silently ignore duplicates, similar to append
+ return
+
+ # The frozen items are sequentially first and protected from changes
+ len_frozen = len(self._frozen)
+ size = len(self)
+
+ # Follow the behavior of `list.insert()` when the index is out of bounds.
+ # - negative out-of-bounds index: prepend. Will only work if the frozen items are empty.
+ if index < -size and not self._frozen:
+ return self._draft.insert(0, value)
+
+ # - positive out-of-bounds index: append.
+ if index >= size:
+ return self._draft.append(value)
+
+ # - in-bounds index: insert only if into the draft portion.
+ draft_index = (index % size) - len_frozen
+ if draft_index < 0:
+ raise IndexError(
+ f"Cannot insert into the frozen list (index < {len_frozen})"
+ )
+ return self._draft.insert(draft_index, value)
+
+ def __repr__(self) -> str:
+ return f"{nameof(type(self))}(frozen={list(self._frozen)!r}, draft={list(self._draft)!r})"
+
+ @property
+ def draft(self) -> tuple[T, ...]:
+ """A read-only, tuple copy of the current draft items."""
+ return tuple(self._draft)
+
+
+class AddOnlyArtifactTypesList(FreezableList[str]):
+ def remove(self, value: str) -> None:
+ try:
+ super().remove(value)
+ except ValueError:
+ raise ValueError(
+ f"Cannot remove artifact type: {value!r} that has been saved to the registry"
+ )
+
+ def __repr__(self) -> str:
+ return f"{nameof(type(self))}(saved={list(self._frozen)!r}, draft={list(self._draft)!r})"
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/registries/_utils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/registries/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f73fa749f226563d548217773f8d698bc11efde3
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/registries/_utils.py
@@ -0,0 +1,139 @@
+from __future__ import annotations
+
+from enum import Enum
+from functools import lru_cache
+from typing import TYPE_CHECKING, Any, Literal, Mapping, Sequence
+
+from wandb._strutils import ensureprefix
+from wandb.sdk.artifacts._validators import (
+ REGISTRY_PREFIX,
+ validate_artifact_types_list,
+)
+
+if TYPE_CHECKING:
+ from wandb_gql import Client
+
+from wandb_gql import gql
+
+
+class Visibility(str, Enum):
+ # names are what users see/pass into Python methods
+ # values are what's expected by backend API
+ organization = "PRIVATE"
+ restricted = "RESTRICTED"
+
+ @classmethod
+ def _missing_(cls, value: object) -> Any:
+ return next((e for e in cls if e.name == value), None)
+
+
+def format_gql_artifact_types_input(
+ artifact_types: list[str] | None,
+) -> list[dict[str, str]]:
+ """Format the artifact types for the GQL input.
+
+ Args:
+ artifact_types: The artifact types to add to the registry.
+
+ Returns:
+ The artifact types for the GQL input.
+ """
+ if artifact_types is None:
+ return []
+ return [{"name": typ} for typ in validate_artifact_types_list(artifact_types)]
+
+
+def gql_to_registry_visibility(
+ visibility: str,
+) -> Literal["organization", "restricted"]:
+ """Convert the GQL visibility to the registry visibility.
+
+ Args:
+ visibility: The GQL visibility.
+
+ Returns:
+ The registry visibility.
+ """
+ try:
+ return Visibility(visibility).name
+ except ValueError:
+ raise ValueError(f"Invalid visibility: {visibility!r} from backend")
+
+
+def registry_visibility_to_gql(
+ visibility: Literal["organization", "restricted"],
+) -> str:
+ """Convert the registry visibility to the GQL visibility."""
+ try:
+ return Visibility[visibility].value
+ except LookupError:
+ allowed_str = ", ".join(map(repr, (e.name for e in Visibility)))
+ raise ValueError(
+ f"Invalid visibility: {visibility!r}. Must be one of: {allowed_str}"
+ )
+
+
+def ensure_registry_prefix_on_names(query: Any, in_name: bool = False) -> Any:
+ """Traverse the filter to prepend the `name` key value with the registry prefix unless the value is a regex.
+
+ - in_name: True if we are under a "name" key (or propagating from one).
+
+ EX: {"name": "model"} -> {"name": "wandb-registry-model"}
+ """
+ if isinstance((txt := query), str):
+ if in_name:
+ return ensureprefix(txt, REGISTRY_PREFIX)
+ return txt
+ if isinstance((dct := query), Mapping):
+ new_dict = {}
+ for key, obj in dct.items():
+ if key == "name":
+ new_dict[key] = ensure_registry_prefix_on_names(obj, in_name=True)
+ elif key == "$regex":
+ # For regex operator, we skip transformation of its value.
+ new_dict[key] = obj
+ else:
+ # For any other key, propagate the in_name and skip_transform flags as-is.
+ new_dict[key] = ensure_registry_prefix_on_names(obj, in_name=in_name)
+ return new_dict
+ if isinstance((objs := query), Sequence):
+ return list(
+ map(lambda x: ensure_registry_prefix_on_names(x, in_name=in_name), objs)
+ )
+ return query
+
+
+@lru_cache(maxsize=10)
+def fetch_org_entity_from_organization(client: Client, organization: str) -> str:
+ """Fetch the org entity from the organization.
+
+ Args:
+ client (Client): Graphql client.
+ organization (str): The organization to fetch the org entity for.
+ """
+ query = gql(
+ """
+ query FetchOrgEntityFromOrganization($organization: String!) {
+ organization(name: $organization) {
+ orgEntity {
+ name
+ }
+ }
+ }
+ """
+ )
+ try:
+ response = client.execute(query, variable_values={"organization": organization})
+ except Exception as e:
+ raise ValueError(
+ f"Error fetching org entity for organization: {organization!r}"
+ ) from e
+
+ if (
+ not (org := response["organization"])
+ or not (org_entity := org["orgEntity"])
+ or not (org_name := org_entity["name"])
+ ):
+ raise ValueError(f"Organization entity for {organization!r} not found.")
+
+ return org_name
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/registries/registries_search.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/registries/registries_search.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4e9b455bb4cb35a6ab1263f2ce906a04d4a1fc2
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/registries/registries_search.py
@@ -0,0 +1,353 @@
+"""Public API: registries search."""
+
+from __future__ import annotations
+
+import json
+from typing import TYPE_CHECKING, Any
+
+from pydantic import ValidationError
+from typing_extensions import override
+from wandb_gql import gql
+
+from wandb._analytics import tracked
+from wandb.apis.paginator import Paginator
+from wandb.apis.public.utils import gql_compat
+from wandb.sdk.artifacts._generated import (
+ FETCH_REGISTRIES_GQL,
+ REGISTRY_COLLECTIONS_GQL,
+ REGISTRY_VERSIONS_GQL,
+ ArtifactCollectionType,
+ FetchRegistries,
+ RegistriesPage,
+ RegistryCollections,
+ RegistryCollectionsPage,
+ RegistryVersions,
+ RegistryVersionsPage,
+)
+from wandb.sdk.artifacts._gqlutils import omit_artifact_fields
+from wandb.sdk.artifacts._validators import FullArtifactPath, remove_registry_prefix
+
+from ._utils import ensure_registry_prefix_on_names
+
+if TYPE_CHECKING:
+ from wandb_gql import Client
+
+ from wandb.sdk.artifacts.artifact import Artifact
+
+
+class Registries(Paginator):
+ """An lazy iterator of `Registry` objects."""
+
+ QUERY = gql(FETCH_REGISTRIES_GQL)
+
+ last_response: RegistriesPage | None
+ _last_org_entity: str | None
+
+ def __init__(
+ self,
+ client: Client,
+ organization: str,
+ filter: dict[str, Any] | None = None,
+ per_page: int | None = 100,
+ ):
+ self.client = client
+ self.organization = organization
+ self.filter = ensure_registry_prefix_on_names(filter or {})
+ variables = {
+ "organization": organization,
+ "filters": json.dumps(self.filter),
+ }
+
+ super().__init__(client, variables, per_page)
+
+ self._last_org_entity = None
+
+ def __next__(self):
+ # Implement custom next since its possible to load empty pages because of auth
+ self.index += 1
+ while len(self.objects) <= self.index:
+ if not self._load_page():
+ raise StopIteration
+ return self.objects[self.index]
+
+ @tracked
+ def collections(self, filter: dict[str, Any] | None = None) -> Collections:
+ return Collections(
+ client=self.client,
+ organization=self.organization,
+ registry_filter=self.filter,
+ collection_filter=filter,
+ )
+
+ @tracked
+ def versions(self, filter: dict[str, Any] | None = None) -> Versions:
+ return Versions(
+ client=self.client,
+ organization=self.organization,
+ registry_filter=self.filter,
+ collection_filter=None,
+ artifact_filter=filter,
+ )
+
+ @property
+ def length(self):
+ if self.last_response is None:
+ return None
+ return len(self.last_response.edges)
+
+ @property
+ def more(self):
+ if self.last_response is None:
+ return True
+ return self.last_response.page_info.has_next_page
+
+ @property
+ def cursor(self):
+ if self.last_response is None:
+ return None
+ return self.last_response.page_info.end_cursor
+
+ @override
+ def _update_response(self) -> None:
+ data = self.client.execute(self.QUERY, variable_values=self.variables)
+ result = FetchRegistries.model_validate(data)
+ if not ((org := result.organization) and (org_entity := org.org_entity)):
+ raise ValueError(
+ f"Organization {self.organization!r} not found. Please verify the organization name is correct."
+ )
+
+ try:
+ page_data = org_entity.projects
+ self.last_response = RegistriesPage.model_validate(page_data)
+ self._last_org_entity = org_entity.name
+ except (LookupError, AttributeError, ValidationError) as e:
+ raise ValueError("Unexpected response data") from e
+
+ def convert_objects(self):
+ from wandb.apis.public.registries.registry import Registry
+
+ if (self.last_response is None) or (self._last_org_entity is None):
+ return []
+
+ nodes = (e.node for e in self.last_response.edges)
+ return [
+ Registry(
+ client=self.client,
+ organization=self.organization,
+ entity=self._last_org_entity,
+ name=remove_registry_prefix(node.name),
+ attrs=node.model_dump(),
+ )
+ for node in nodes
+ ]
+
+
+class Collections(Paginator["ArtifactCollection"]):
+ """An lazy iterator of `ArtifactCollection` objects in a Registry."""
+
+ QUERY = gql(REGISTRY_COLLECTIONS_GQL)
+
+ last_response: RegistryCollectionsPage | None
+
+ def __init__(
+ self,
+ client: Client,
+ organization: str,
+ registry_filter: dict[str, Any] | None = None,
+ collection_filter: dict[str, Any] | None = None,
+ per_page: int | None = 100,
+ ):
+ self.client = client
+ self.organization = organization
+ self.registry_filter = registry_filter
+ self.collection_filter = collection_filter or {}
+
+ variables = {
+ "registryFilter": json.dumps(f) if (f := registry_filter) else None,
+ "collectionFilter": json.dumps(f) if (f := collection_filter) else None,
+ "organization": organization,
+ "collectionTypes": [ArtifactCollectionType.PORTFOLIO],
+ "perPage": per_page,
+ }
+
+ super().__init__(client, variables, per_page)
+
+ def __next__(self):
+ # Implement custom next since its possible to load empty pages because of auth
+ self.index += 1
+ while len(self.objects) <= self.index:
+ if not self._load_page():
+ raise StopIteration
+ return self.objects[self.index]
+
+ @tracked
+ def versions(self, filter: dict[str, Any] | None = None) -> Versions:
+ return Versions(
+ client=self.client,
+ organization=self.organization,
+ registry_filter=self.registry_filter,
+ collection_filter=self.collection_filter,
+ artifact_filter=filter,
+ )
+
+ @property
+ def length(self):
+ if self.last_response is None:
+ return None
+ return self.last_response.total_count
+
+ @property
+ def more(self):
+ if self.last_response is None:
+ return True
+ return self.last_response.page_info.has_next_page
+
+ @property
+ def cursor(self):
+ if self.last_response is None:
+ return None
+ return self.last_response.page_info.end_cursor
+
+ @override
+ def _update_response(self) -> None:
+ data = self.client.execute(self.QUERY, variable_values=self.variables)
+ result = RegistryCollections.model_validate(data)
+ if not (
+ (org_data := result.organization)
+ and (org_entity_data := org_data.org_entity)
+ ):
+ raise ValueError(
+ f"Organization {self.organization!r} not found. Please verify the organization name is correct."
+ )
+
+ try:
+ page_data = org_entity_data.artifact_collections
+ self.last_response = RegistryCollectionsPage.model_validate(page_data)
+ except (LookupError, AttributeError, ValidationError) as e:
+ raise ValueError("Unexpected response data") from e
+
+ def convert_objects(self):
+ from wandb.apis.public import ArtifactCollection
+
+ if self.last_response is None:
+ return []
+
+ nodes = (e.node for e in self.last_response.edges)
+ return [
+ ArtifactCollection(
+ client=self.client,
+ entity=project.entity.name,
+ project=project.name,
+ name=node.name,
+ type=node.default_artifact_type.name,
+ organization=self.organization,
+ attrs=node.model_dump(),
+ is_sequence=False,
+ )
+ for node in nodes
+ if (project := node.project)
+ ]
+
+
+class Versions(Paginator["Artifact"]):
+ """An lazy iterator of `Artifact` objects in a Registry."""
+
+ last_response: RegistryVersionsPage | None
+
+ def __init__(
+ self,
+ client: Client,
+ organization: str,
+ registry_filter: dict[str, Any] | None = None,
+ collection_filter: dict[str, Any] | None = None,
+ artifact_filter: dict[str, Any] | None = None,
+ per_page: int = 100,
+ ):
+ self.client = client
+ self.organization = organization
+ self.registry_filter = registry_filter
+ self.collection_filter = collection_filter
+ self.artifact_filter = artifact_filter or {}
+
+ self.QUERY = gql_compat(
+ REGISTRY_VERSIONS_GQL, omit_fields=omit_artifact_fields(client)
+ )
+
+ variables = {
+ "registryFilter": json.dumps(f) if (f := registry_filter) else None,
+ "collectionFilter": json.dumps(f) if (f := collection_filter) else None,
+ "artifactFilter": json.dumps(f) if (f := artifact_filter) else None,
+ "organization": organization,
+ }
+
+ super().__init__(client, variables, per_page)
+
+ def __next__(self):
+ # Implement custom next since its possible to load empty pages because of auth
+ self.index += 1
+ while len(self.objects) <= self.index:
+ if not self._load_page():
+ raise StopIteration
+ return self.objects[self.index]
+
+ @property
+ def length(self) -> int | None:
+ if self.last_response is None:
+ return None
+ return len(self.last_response.edges)
+
+ @property
+ def more(self) -> bool:
+ if self.last_response is None:
+ return True
+ return self.last_response.page_info.has_next_page
+
+ @property
+ def cursor(self) -> str | None:
+ if self.last_response is None:
+ return None
+ return self.last_response.page_info.end_cursor
+
+ @override
+ def _update_response(self) -> None:
+ data = self.client.execute(self.QUERY, variable_values=self.variables)
+ result = RegistryVersions.model_validate(data)
+ if not (
+ (org_data := result.organization)
+ and (org_entity_data := org_data.org_entity)
+ ):
+ raise ValueError(
+ f"Organization {self.organization!r} not found. Please verify the organization name is correct."
+ )
+
+ try:
+ page_data = org_entity_data.artifact_memberships
+ self.last_response = RegistryVersionsPage.model_validate(page_data)
+ except (LookupError, AttributeError, ValidationError) as e:
+ raise ValueError("Unexpected response data") from e
+
+ def convert_objects(self) -> list[Artifact]:
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ if self.last_response is None:
+ return []
+
+ nodes = (e.node for e in self.last_response.edges)
+ return [
+ Artifact._from_attrs(
+ path=FullArtifactPath(
+ prefix=project.entity.name,
+ project=project.name,
+ name=f"{collection.name}:v{node.version_index}",
+ ),
+ attrs=artifact,
+ client=self.client,
+ aliases=[alias.alias for alias in node.aliases],
+ )
+ for node in nodes
+ if (
+ (collection := node.artifact_collection)
+ and (project := collection.project)
+ and (artifact := node.artifact)
+ )
+ ]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/registries/registry.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/registries/registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..410ef02496b0d55ece6eed630ab41ccc902949ef
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/registries/registry.py
@@ -0,0 +1,370 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Literal
+
+from wandb_gql import gql
+
+import wandb
+from wandb._analytics import tracked
+from wandb.proto.wandb_internal_pb2 import ServerFeature
+from wandb.sdk.artifacts._validators import REGISTRY_PREFIX, validate_project_name
+from wandb.sdk.internal.internal_api import Api as InternalApi
+from wandb.sdk.projects._generated import (
+ DELETE_PROJECT_GQL,
+ FETCH_REGISTRY_GQL,
+ RENAME_PROJECT_GQL,
+ UPSERT_REGISTRY_PROJECT_GQL,
+ DeleteProject,
+ RenameProject,
+ UpsertRegistryProject,
+)
+
+from ._freezable_list import AddOnlyArtifactTypesList
+from ._utils import (
+ fetch_org_entity_from_organization,
+ format_gql_artifact_types_input,
+ gql_to_registry_visibility,
+ registry_visibility_to_gql,
+)
+from .registries_search import Collections, Versions
+
+if TYPE_CHECKING:
+ from wandb_gql import Client
+
+
+class Registry:
+ """A single registry in the Registry."""
+
+ def __init__(
+ self,
+ client: Client,
+ organization: str,
+ entity: str,
+ name: str,
+ attrs: dict[str, Any] | None = None,
+ ):
+ self.client = client
+ self._name = name
+ self._saved_name = name
+ self._entity = entity
+ self._organization = organization
+ if attrs is not None:
+ self._update_attributes(attrs)
+
+ def _update_attributes(self, attrs: dict[str, Any]) -> None:
+ """Helper method to update instance attributes from a dictionary."""
+ self._id = attrs.get("id", "")
+ if self._id is None:
+ raise ValueError(f"Registry {self.name}'s id is not found")
+
+ self._description = attrs.get("description", "")
+ self._allow_all_artifact_types = attrs.get(
+ "allowAllArtifactTypesInRegistry", False
+ )
+ self._artifact_types = AddOnlyArtifactTypesList(
+ t["node"]["name"] for t in attrs.get("artifactTypes", {}).get("edges", [])
+ )
+ self._created_at = attrs.get("createdAt", "")
+ self._updated_at = attrs.get("updatedAt", "")
+ self._visibility = gql_to_registry_visibility(attrs.get("access", ""))
+
+ @property
+ def full_name(self) -> str:
+ """Full name of the registry including the `wandb-registry-` prefix."""
+ return f"wandb-registry-{self.name}"
+
+ @property
+ def name(self) -> str:
+ """Name of the registry without the `wandb-registry-` prefix."""
+ return self._name
+
+ @name.setter
+ def name(self, value: str):
+ self._name = value
+
+ @property
+ def entity(self) -> str:
+ """Organization entity of the registry."""
+ return self._entity
+
+ @property
+ def organization(self) -> str:
+ """Organization name of the registry."""
+ return self._organization
+
+ @property
+ def description(self) -> str:
+ """Description of the registry."""
+ return self._description
+
+ @description.setter
+ def description(self, value: str):
+ """Set the description of the registry."""
+ self._description = value
+
+ @property
+ def allow_all_artifact_types(self):
+ """Returns whether all artifact types are allowed in the registry.
+
+ If `True` then artifacts of any type can be added to this registry.
+ If `False` then artifacts are restricted to the types in `artifact_types` for this registry.
+ """
+ return self._allow_all_artifact_types
+
+ @allow_all_artifact_types.setter
+ def allow_all_artifact_types(self, value: bool):
+ """Set whether all artifact types are allowed in the registry."""
+ self._allow_all_artifact_types = value
+
+ @property
+ def artifact_types(self) -> AddOnlyArtifactTypesList:
+ """Returns the artifact types allowed in the registry.
+
+ If `allow_all_artifact_types` is `True` then `artifact_types` reflects the
+ types previously saved or currently used in the registry.
+ If `allow_all_artifact_types` is `False` then artifacts are restricted to the
+ types in `artifact_types`.
+
+ Note:
+ Previously saved artifact types cannot be removed.
+
+ Example:
+ ```python
+ import wandb
+
+ registry = wandb.Api().create_registry()
+ registry.artifact_types.append("model")
+ registry.save() # once saved, the artifact type `model` cannot be removed
+ registry.artifact_types.append("accidentally_added")
+ registry.artifact_types.remove(
+ "accidentally_added"
+ ) # Types can only be removed if it has not been saved yet
+ ```
+ """
+ return self._artifact_types
+
+ @property
+ def created_at(self) -> str:
+ """Timestamp of when the registry was created."""
+ return self._created_at
+
+ @property
+ def updated_at(self) -> str:
+ """Timestamp of when the registry was last updated."""
+ return self._updated_at
+
+ @property
+ def path(self):
+ return [self.entity, self.full_name]
+
+ @property
+ def visibility(self) -> Literal["organization", "restricted"]:
+ """Visibility of the registry.
+
+ Returns:
+ Literal["organization", "restricted"]: The visibility level.
+ - "organization": Anyone in the organization can view this registry.
+ You can edit their roles later from the settings in the UI.
+ - "restricted": Only invited members via the UI can access this registry.
+ Public sharing is disabled.
+ """
+ return self._visibility
+
+ @visibility.setter
+ def visibility(self, value: Literal["organization", "restricted"]):
+ """Set the visibility of the registry.
+
+ Args:
+ value: The visibility level. Options are:
+ - "organization": Anyone in the organization can view this registry.
+ You can edit their roles later from the settings in the UI.
+ - "restricted": Only invited members via the UI can access this registry.
+ Public sharing is disabled.
+ """
+ self._visibility = value
+
+ @tracked
+ def collections(self, filter: dict[str, Any] | None = None) -> Collections:
+ """Returns the collections belonging to the registry."""
+ registry_filter = {
+ "name": self.full_name,
+ }
+ return Collections(self.client, self.organization, registry_filter, filter)
+
+ @tracked
+ def versions(self, filter: dict[str, Any] | None = None) -> Versions:
+ """Returns the versions belonging to the registry."""
+ registry_filter = {
+ "name": self.full_name,
+ }
+ return Versions(self.client, self.organization, registry_filter, None, filter)
+
+ @classmethod
+ @tracked
+ def create(
+ cls,
+ client: Client,
+ organization: str,
+ name: str,
+ visibility: Literal["organization", "restricted"],
+ description: str | None = None,
+ artifact_types: list[str] | None = None,
+ ):
+ """Create a new registry.
+
+ The registry name must be unique within the organization.
+ This function should be called using `api.create_registry()`
+
+ Args:
+ client: The GraphQL client.
+ organization: The name of the organization.
+ name: The name of the registry (without the `wandb-registry-` prefix).
+ visibility: The visibility level ('organization' or 'restricted').
+ description: An optional description for the registry.
+ artifact_types: An optional list of allowed artifact types.
+
+ Returns:
+ Registry: The newly created Registry object.
+
+ Raises:
+ ValueError: If a registry with the same name already exists in the
+ organization or if the creation fails.
+ """
+ org_entity = fetch_org_entity_from_organization(client, organization)
+ full_name = REGISTRY_PREFIX + name
+ validate_project_name(full_name)
+ accepted_artifact_types = []
+ if artifact_types:
+ accepted_artifact_types = format_gql_artifact_types_input(artifact_types)
+ visibility_value = registry_visibility_to_gql(visibility)
+ registry_creation_error = (
+ f"Failed to create registry {name!r} in organization {organization!r}."
+ )
+ try:
+ response = client.execute(
+ gql(UPSERT_REGISTRY_PROJECT_GQL),
+ variable_values={
+ "description": description,
+ "entityName": org_entity,
+ "name": full_name,
+ "access": visibility_value,
+ "allowAllArtifactTypesInRegistry": not accepted_artifact_types,
+ "artifactTypes": accepted_artifact_types,
+ },
+ )
+ except Exception:
+ raise ValueError(registry_creation_error)
+ if not response["upsertModel"]["inserted"]:
+ raise ValueError(registry_creation_error)
+
+ return Registry(
+ client,
+ organization,
+ org_entity,
+ name,
+ response["upsertModel"]["project"],
+ )
+
+ @tracked
+ def delete(self) -> None:
+ """Delete the registry. This is irreversible."""
+ try:
+ response = self.client.execute(
+ gql(DELETE_PROJECT_GQL), variable_values={"id": self._id}
+ )
+ result = DeleteProject.model_validate(response)
+ except Exception:
+ raise ValueError(
+ f"Failed to delete registry: {self.name!r} in organization: {self.organization!r}"
+ )
+ if not result.delete_model.success:
+ raise ValueError(
+ f"Failed to delete registry: {self.name!r} in organization: {self.organization!r}"
+ )
+
+ @tracked
+ def load(self) -> None:
+ """Load the registry attributes from the backend to reflect the latest saved state."""
+ load_failure_message = (
+ f"Failed to load registry {self.name!r} "
+ f"in organization {self.organization!r}."
+ )
+ try:
+ response = self.client.execute(
+ gql(FETCH_REGISTRY_GQL),
+ variable_values={
+ "name": self.full_name,
+ "entityName": self.entity,
+ },
+ )
+ except Exception:
+ raise ValueError(load_failure_message)
+ if response["entity"] is None:
+ raise ValueError(load_failure_message)
+ self.attrs = response["entity"]["project"]
+ if self.attrs is None:
+ raise ValueError(load_failure_message)
+ self._update_attributes(self.attrs)
+
+ @tracked
+ def save(self) -> None:
+ """Save registry attributes to the backend."""
+ if not InternalApi()._server_supports(
+ ServerFeature.INCLUDE_ARTIFACT_TYPES_IN_REGISTRY_CREATION
+ ):
+ raise RuntimeError(
+ "saving the registry is not enabled on this wandb server version. "
+ "Please upgrade your server version or contact support at support@wandb.com."
+ )
+
+ if self._no_updating_registry_types():
+ raise ValueError(
+ f"Cannot update artifact types when `allows_all_artifact_types` is {True!r}. Set it to {False!r} first."
+ )
+
+ validate_project_name(self.full_name)
+ visibility_value = registry_visibility_to_gql(self.visibility)
+ newly_added_types = format_gql_artifact_types_input(self.artifact_types.draft)
+ registry_save_error = f"Failed to save and update registry: {self.name} in organization: {self.organization}"
+ full_saved_name = f"{REGISTRY_PREFIX}{self._saved_name}"
+ try:
+ response = self.client.execute(
+ gql(UPSERT_REGISTRY_PROJECT_GQL),
+ variable_values={
+ "description": self.description,
+ "entityName": self.entity,
+ "name": full_saved_name, # this makes it so we are updating the original registry in case the name has changed
+ "access": visibility_value,
+ "allowAllArtifactTypesInRegistry": self.allow_all_artifact_types,
+ "artifactTypes": newly_added_types,
+ },
+ )
+ result = UpsertRegistryProject.model_validate(response)
+ except Exception:
+ raise ValueError(registry_save_error)
+ if result.upsert_model.inserted:
+ # This is not suppose trigger unless the user has messed with the `_saved_name` variable
+ wandb.termlog(
+ f"Created registry {self.name!r} in organization {self.organization!r} on save"
+ )
+ self._update_attributes(response["upsertModel"]["project"])
+
+ # Update the name of the registry if it has changed
+ if self._saved_name != self.name:
+ response = self.client.execute(
+ gql(RENAME_PROJECT_GQL),
+ variable_values={
+ "entityName": self.entity,
+ "oldProjectName": full_saved_name,
+ "newProjectName": self.full_name,
+ },
+ )
+ result = RenameProject.model_validate(response)
+ self._saved_name = self.name
+ if result.rename_project.inserted:
+ # This is not suppose trigger unless the user has messed with the `_saved_name` variable
+ wandb.termlog(f"Created new registry {self.name!r} on save")
+
+ def _no_updating_registry_types(self) -> bool:
+ # artifact types draft means user assigned types to add that are not yet saved
+ return len(self.artifact_types.draft) > 0 and self.allow_all_artifact_types
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/reports.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/reports.py
new file mode 100644
index 0000000000000000000000000000000000000000..7076f9877b807593cb8144589149869c11be13f2
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/reports.py
@@ -0,0 +1,597 @@
+"""W&B Public API for Report objects.
+
+This module provides classes for interacting with W&B reports and
+managing report-related data.
+"""
+
+from __future__ import annotations
+
+import ast
+import json
+import re
+import urllib
+
+from wandb_gql import gql
+
+import wandb
+from wandb.apis import public
+from wandb.apis.attrs import Attrs
+from wandb.apis.paginator import SizedPaginator
+from wandb.sdk.lib import ipython
+
+
+class Reports(SizedPaginator["BetaReport"]):
+ """Reports is a lazy iterator of `BetaReport` objects.
+
+ Args:
+ client (`wandb.apis.internal.Api`): The API client instance to use.
+ project (`wandb.sdk.internal.Project`): The project to fetch reports from.
+ name (str, optional): The name of the report to filter by. If `None`,
+ fetches all reports.
+ entity (str, optional): The entity name for the project. Defaults to
+ the project entity.
+ per_page (int): Number of reports to fetch per page (default is 50).
+ """
+
+ QUERY = gql(
+ """
+ query ProjectViews($project: String!, $entity: String!, $reportCursor: String,
+ $reportLimit: Int!, $viewType: String = "runs", $viewName: String) {
+ project(name: $project, entityName: $entity) {
+ allViews(viewType: $viewType, viewName: $viewName, first:
+ $reportLimit, after: $reportCursor) {
+ edges {
+ node {
+ id
+ name
+ displayName
+ description
+ user {
+ username
+ photoUrl
+ email
+ }
+ spec
+ updatedAt
+ createdAt
+ }
+ cursor
+ }
+ pageInfo {
+ endCursor
+ hasNextPage
+ }
+
+ }
+ }
+ }
+ """
+ )
+
+ def __init__(self, client, project, name=None, entity=None, per_page=50):
+ self.project = project
+ self.name = name
+ variables = {
+ "project": project.name,
+ "entity": project.entity,
+ "viewName": self.name,
+ }
+ super().__init__(client, variables, per_page)
+
+ @property
+ def _length(self):
+ """The number of reports in the project.
+
+
+ """
+ # TODO: Add the count the backend
+ if self.last_response:
+ return len(self.objects)
+ else:
+ return None
+
+ @property
+ def more(self) -> bool:
+ """Returns whether there are more files to fetch.
+
+
+ """
+ if self.last_response:
+ return bool(
+ self.last_response["project"]["allViews"]["pageInfo"]["hasNextPage"]
+ )
+ else:
+ return True
+
+ @property
+ def cursor(self):
+ """Returns the cursor position for pagination of file results.
+
+
+ """
+ if self.last_response:
+ return self.last_response["project"]["allViews"]["edges"][-1]["cursor"]
+ else:
+ return None
+
+ def update_variables(self):
+ """Updates the GraphQL query variables for pagination."""
+ self.variables.update(
+ {"reportCursor": self.cursor, "reportLimit": self.per_page}
+ )
+
+ def convert_objects(self):
+ """Converts GraphQL edges to File objects."""
+ if self.last_response["project"] is None:
+ raise ValueError(
+ f"Project {self.variables['project']} does not exist under entity {self.variables['entity']}"
+ )
+ return [
+ BetaReport(
+ self.client,
+ r["node"],
+ entity=self.project.entity,
+ project=self.project.name,
+ )
+ for r in self.last_response["project"]["allViews"]["edges"]
+ ]
+
+ def __repr__(self):
+ return "".format("/".join(self.project.path))
+
+
+class BetaReport(Attrs):
+ """BetaReport is a class associated with reports created in W&B.
+
+ Provides access to report attributes (name, description, user, spec,
+ timestamps) and methods for retrieving associated runs,
+ sections, and for rendering the report as HTML.
+
+ Attributes:
+ id (string): Unique identifier of the report.
+ display_name (string): Human-readable display name of the report.
+ name (string): The name of the report. Use `display_name` for a more user-friendly name.
+ description (string): Description of the report.
+ user (User): Dictionary containing user info (username, email) who
+ created the report.
+ spec (dict): The spec of the report.
+ url (string): The URL of the report.
+ updated_at (string): Timestamp of last update.
+ created_at (string): Timestamp when the report was created.
+ """
+
+ def __init__(self, client, attrs, entity=None, project=None):
+ self.client = client
+ self.project = project
+ self.entity = entity
+ self.query_generator = public.QueryGenerator()
+ super().__init__(dict(attrs))
+
+ if "spec" in self._attrs:
+ if isinstance(self._attrs["spec"], str):
+ self._attrs["spec"] = json.loads(self._attrs["spec"])
+ else:
+ self._attrs["spec"] = {}
+
+ @property
+ def spec(self):
+ return self._attrs["spec"]
+
+ @property
+ def sections(self):
+ """Get the panel sections (groups) from the report."""
+ return self.spec["panelGroups"]
+
+ def runs(self, section, per_page=50, only_selected=True):
+ """Get runs associated with a section of the report."""
+ run_set_idx = section.get("openRunSet", 0)
+ run_set = section["runSets"][run_set_idx]
+ order = self.query_generator.key_to_server_path(run_set["sort"]["key"])
+ if run_set["sort"].get("ascending"):
+ order = "+" + order
+ else:
+ order = "-" + order
+ filters = self.query_generator.filter_to_mongo(run_set["filters"])
+ if only_selected:
+ # TODO: handle this not always existing
+ filters["$or"][0]["$and"].append(
+ {"name": {"$in": run_set["selections"]["tree"]}}
+ )
+ return public.Runs(
+ self.client,
+ self.entity,
+ self.project,
+ filters=filters,
+ order=order,
+ per_page=per_page,
+ )
+
+ @property
+ def id(self):
+ return self._attrs.get("id")
+
+ @property
+ def name(self):
+ return self._attrs.get("name")
+
+ @property
+ def display_name(self):
+ return self._attrs.get("displayName")
+
+ @property
+ def description(self):
+ return self._attrs.get("description")
+
+ @property
+ def user(self):
+ return self._attrs.get("user")
+
+ @property
+ def updated_at(self):
+ return self._attrs.get("updatedAt")
+
+ @property
+ def created_at(self):
+ return self._attrs.get("createdAt")
+
+ @property
+ def url(self):
+ if (
+ not self.client
+ or not self.entity
+ or not self.project
+ or not self.display_name
+ or not self.id
+ ):
+ return None
+ return self.client.app_url + "/".join(
+ [
+ self.entity,
+ self.project,
+ "reports",
+ "--".join(
+ [
+ # made this more closely match the url creation in the frontend (https://github.com/wandb/core/blob/76943979c8e967f7a62dae8bef0a001a2672584c/frontends/app/src/util/report/urls.ts#L19)
+ urllib.parse.quote(
+ re.sub(
+ r"-+", "-", re.sub(r"\W", "-", self.display_name)
+ ).strip("-")
+ ),
+ self.id.replace("=", ""),
+ ]
+ ),
+ ]
+ )
+
+ def to_html(self, height=1024, hidden=False):
+ """Generate HTML containing an iframe displaying this report."""
+ url = self.url
+ if url is None:
+ return "
Report URL not available
"
+ url = url + "?jupyter=true"
+ style = f"border:none;width:100%;height:{height}px;"
+ prefix = ""
+ if hidden:
+ style += "display:none;"
+ prefix = ipython.toggle_button("report")
+ return prefix + f""
+
+ def _repr_html_(self) -> str:
+ return self.to_html()
+
+
+class PythonMongoishQueryGenerator:
+ """Converts Python-style query expressions to MongoDB-style queries for W&B reports.
+
+
+ """
+
+ SPACER = "----------"
+ DECIMAL_SPACER = ";;;"
+ FRONTEND_NAME_MAPPING = {
+ "ID": "name",
+ "Name": "displayName",
+ "Tags": "tags",
+ "State": "state",
+ "CreatedTimestamp": "createdAt",
+ "Runtime": "duration",
+ "User": "username",
+ "Sweep": "sweep",
+ "Group": "group",
+ "JobType": "jobType",
+ "Hostname": "host",
+ "UsingArtifact": "inputArtifacts",
+ "OutputtingArtifact": "outputArtifacts",
+ "Step": "_step",
+ "Relative Time (Wall)": "_absolute_runtime",
+ "Relative Time (Process)": "_runtime",
+ "Wall Time": "_timestamp",
+ # "GroupedRuns": "__wb_group_by_all"
+ }
+ FRONTEND_NAME_MAPPING_REVERSED = {v: k for k, v in FRONTEND_NAME_MAPPING.items()}
+ AST_OPERATORS = {
+ ast.Lt: "$lt",
+ ast.LtE: "$lte",
+ ast.Gt: "$gt",
+ ast.GtE: "$gte",
+ ast.Eq: "=",
+ ast.Is: "=",
+ ast.NotEq: "$ne",
+ ast.IsNot: "$ne",
+ ast.In: "$in",
+ ast.NotIn: "$nin",
+ ast.And: "$and",
+ ast.Or: "$or",
+ ast.Not: "$not",
+ }
+
+ AST_FIELDS = {
+ ast.Constant: "value",
+ ast.Name: "id",
+ ast.List: "elts",
+ ast.Tuple: "elts",
+ }
+
+ def __init__(self, run_set):
+ self.run_set = run_set
+ self.panel_metrics_helper = PanelMetricsHelper()
+
+ def _handle_compare(self, node):
+ # only left side can be a col
+ left = self.front_to_back(self._handle_fields(node.left))
+ op = self._handle_ops(node.ops[0])
+ right = self._handle_fields(node.comparators[0])
+
+ # Eq has no op for some reason
+ if op == "=":
+ return {left: right}
+ else:
+ return {left: {op: right}}
+
+ def _handle_fields(self, node):
+ result = getattr(node, self.AST_FIELDS.get(type(node)))
+ if isinstance(result, list):
+ return [self._handle_fields(node) for node in result]
+ elif isinstance(result, str):
+ return self._unconvert(result)
+ return result
+
+ def _handle_ops(self, node):
+ return self.AST_OPERATORS.get(type(node))
+
+ def _replace_numeric_dots(self, s):
+ numeric_dots = []
+ for i, (left, mid, right) in enumerate(zip(s, s[1:], s[2:]), 1):
+ if mid == ".":
+ if (
+ left.isdigit()
+ and right.isdigit() # 1.2
+ or left.isdigit()
+ and right == " " # 1.
+ or left == " "
+ and right.isdigit() # .2
+ ):
+ numeric_dots.append(i)
+ # Edge: Catch number ending in dot at end of string
+ if s[-2].isdigit() and s[-1] == ".":
+ numeric_dots.append(len(s) - 1)
+ numeric_dots = [-1] + numeric_dots + [len(s)]
+
+ substrs = []
+ for start, stop in zip(numeric_dots, numeric_dots[1:]):
+ substrs.append(s[start + 1 : stop])
+ substrs.append(self.DECIMAL_SPACER)
+ substrs = substrs[:-1]
+ return "".join(substrs)
+
+ def _convert(self, filterstr):
+ _conversion = (
+ self._replace_numeric_dots(filterstr) # temporarily sub numeric dots
+ .replace(".", self.SPACER) # Allow dotted fields
+ .replace(self.DECIMAL_SPACER, ".") # add them back
+ )
+ return "(" + _conversion + ")"
+
+ def _unconvert(self, field_name):
+ return field_name.replace(self.SPACER, ".") # Allow dotted fields
+
+ def python_to_mongo(self, filterstr):
+ """Convert Python expresion to MongoDB filter.
+
+
+ """
+ try:
+ tree = ast.parse(self._convert(filterstr), mode="eval")
+ except SyntaxError as e:
+ raise ValueError(
+ "Invalid python comparison expression; form something like `my_col == 123`"
+ ) from e
+
+ multiple_filters = hasattr(tree.body, "op")
+
+ if multiple_filters:
+ op = self.AST_OPERATORS.get(type(tree.body.op))
+ values = [self._handle_compare(v) for v in tree.body.values]
+ else:
+ op = "$and"
+ values = [self._handle_compare(tree.body)]
+ return {"$or": [{op: values}]}
+
+ def front_to_back(self, name):
+ """Convert frontend metric names to backend field names.
+
+
+ """
+ name, *rest = name.split(".")
+ rest = "." + ".".join(rest) if rest else ""
+
+ if name in self.FRONTEND_NAME_MAPPING:
+ return self.FRONTEND_NAME_MAPPING[name]
+ elif name in self.FRONTEND_NAME_MAPPING_REVERSED:
+ return name
+ elif name in self.run_set._runs_config:
+ return f"config.{name}.value{rest}"
+ else: # assume summary metrics
+ return f"summary_metrics.{name}{rest}"
+
+ def back_to_front(self, name):
+ """Convert backend field names to frontend metric names.
+
+
+ """
+ if name in self.FRONTEND_NAME_MAPPING_REVERSED:
+ return self.FRONTEND_NAME_MAPPING_REVERSED[name]
+ elif name in self.FRONTEND_NAME_MAPPING:
+ return name
+ elif (
+ name.startswith("config.") and ".value" in name
+ ): # may be brittle: originally "endswith", but that doesn't work with nested keys...
+ # strip is weird sometimes (??)
+ return name.replace("config.", "").replace(".value", "")
+ elif name.startswith("summary_metrics."):
+ return name.replace("summary_metrics.", "")
+ wandb.termerror(f"Unknown token: {name}")
+ return name
+
+ # These are only used for ParallelCoordinatesPlot because it has weird backend names...
+ def pc_front_to_back(self, name):
+ """Convert ParallelCoordinatesPlot to backend field names.
+
+
+ """
+ name, *rest = name.split(".")
+ rest = "." + ".".join(rest) if rest else ""
+ if name is None:
+ return None
+ elif name in self.panel_metrics_helper.FRONTEND_NAME_MAPPING:
+ return "summary:" + self.panel_metrics_helper.FRONTEND_NAME_MAPPING[name]
+ elif name in self.FRONTEND_NAME_MAPPING:
+ return self.FRONTEND_NAME_MAPPING[name]
+ elif name in self.FRONTEND_NAME_MAPPING_REVERSED:
+ return name
+ elif name in self.run_set._runs_config:
+ return f"config:{name}.value{rest}"
+ else: # assume summary metrics
+ return f"summary:{name}{rest}"
+
+ def pc_back_to_front(self, name):
+ """Convert backend backend field names to ParallelCoordinatesPlot names.
+
+
+ """
+ if name is None:
+ return None
+ elif "summary:" in name:
+ name = name.replace("summary:", "")
+ return self.panel_metrics_helper.FRONTEND_NAME_MAPPING_REVERSED.get(
+ name, name
+ )
+ elif name in self.FRONTEND_NAME_MAPPING_REVERSED:
+ return self.FRONTEND_NAME_MAPPING_REVERSED[name]
+ elif name in self.FRONTEND_NAME_MAPPING:
+ return name
+ elif name.startswith("config:") and ".value" in name:
+ return name.replace("config:", "").replace(".value", "")
+ elif name.startswith("summary_metrics."):
+ return name.replace("summary_metrics.", "")
+ return name
+
+
+class PanelMetricsHelper:
+ """Converts Python-style query expressions to MongoDB-style queries for W&B reports.
+
+
+ """
+
+ FRONTEND_NAME_MAPPING = {
+ "Step": "_step",
+ "Relative Time (Wall)": "_absolute_runtime",
+ "Relative Time (Process)": "_runtime",
+ "Wall Time": "_timestamp",
+ }
+ FRONTEND_NAME_MAPPING_REVERSED = {v: k for k, v in FRONTEND_NAME_MAPPING.items()}
+
+ RUN_MAPPING = {"Created Timestamp": "createdAt", "Latest Timestamp": "heartbeatAt"}
+ RUN_MAPPING_REVERSED = {v: k for k, v in RUN_MAPPING.items()}
+
+ def front_to_back(self, name):
+ """Convert frontend metric names to backend field names.
+
+
+ """
+ if name in self.FRONTEND_NAME_MAPPING:
+ return self.FRONTEND_NAME_MAPPING[name]
+ return name
+
+ def back_to_front(self, name):
+ """Convert backend field names to frontend metric names.
+
+
+ """
+ if name in self.FRONTEND_NAME_MAPPING_REVERSED:
+ return self.FRONTEND_NAME_MAPPING_REVERSED[name]
+ return name
+
+ # ScatterPlot and ParallelCoords have weird conventions
+ def special_front_to_back(self, name):
+ """Convert frontend metric names to backend field names.
+
+
+ """
+ if name is None:
+ return name
+
+ name, *rest = name.split(".")
+ rest = "." + ".".join(rest) if rest else ""
+
+ # special case for config
+ if name.startswith("c::"):
+ name = name[3:]
+ return f"config:{name}.value{rest}"
+
+ # special case for summary
+ if name.startswith("s::"):
+ name = name[3:] + rest
+ return f"summary:{name}"
+
+ name = name + rest
+ if name in self.RUN_MAPPING:
+ return "run:" + self.RUN_MAPPING[name]
+ if name in self.FRONTEND_NAME_MAPPING:
+ return "summary:" + self.FRONTEND_NAME_MAPPING[name]
+ if name == "Index":
+ return name
+ return "summary:" + name
+
+ def special_back_to_front(self, name):
+ """Convert backend field names to frontend metric names.
+
+
+ """
+ if name is not None:
+ kind, rest = name.split(":", 1)
+
+ if kind == "config":
+ pieces = rest.split(".")
+ if len(pieces) <= 1:
+ raise ValueError(f"Invalid name: {name}")
+ elif len(pieces) == 2:
+ name = pieces[0]
+ elif len(pieces) >= 3:
+ name = pieces[:1] + pieces[2:]
+ name = ".".join(name)
+ return f"c::{name}"
+
+ elif kind == "summary":
+ name = rest
+ return f"s::{name}"
+
+ if name is None:
+ return name
+ elif "summary:" in name:
+ name = name.replace("summary:", "")
+ return self.FRONTEND_NAME_MAPPING_REVERSED.get(name, name)
+ elif "run:" in name:
+ name = name.replace("run:", "")
+ return self.RUN_MAPPING_REVERSED[name]
+ return name
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/runs.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/runs.py
new file mode 100644
index 0000000000000000000000000000000000000000..b52ecf45ec96883ceb466e5490e362892b5752e2
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/runs.py
@@ -0,0 +1,1438 @@
+"""W&B Public API for Runs.
+
+This module provides classes for interacting with W&B runs and their associated
+data.
+
+Example:
+```python
+from wandb.apis.public import Api
+
+# Get runs matching filters
+runs = Api().runs(
+ path="entity/project", filters={"state": "finished", "config.batch_size": 32}
+)
+
+# Access run data
+for run in runs:
+ print(f"Run: {run.name}")
+ print(f"Config: {run.config}")
+ print(f"Metrics: {run.summary}")
+
+ # Get history with pandas
+ history_df = run.history(keys=["loss", "accuracy"], pandas=True)
+
+ # Work with artifacts
+ for artifact in run.logged_artifacts():
+ print(f"Artifact: {artifact.name}")
+```
+
+Note:
+ This module is part of the W&B Public API and provides read/write access
+ to run data. For logging new runs, use the wandb.init() function from
+ the main wandb package.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import tempfile
+import time
+import urllib
+from typing import TYPE_CHECKING, Any, Collection, Literal, Mapping
+
+from wandb_gql import gql
+
+import wandb
+from wandb import env, util
+from wandb.apis import public
+from wandb.apis.attrs import Attrs
+from wandb.apis.internal import Api as InternalApi
+from wandb.apis.normalize import normalize_exceptions
+from wandb.apis.paginator import SizedPaginator
+from wandb.apis.public.const import RETRY_TIMEDELTA
+from wandb.sdk.lib import ipython, json_util, runid
+from wandb.sdk.lib.paths import LogicalPath
+
+if TYPE_CHECKING:
+ from wandb.apis.public import RetryingClient
+
+WANDB_INTERNAL_KEYS = {"_wandb", "wandb_version"}
+
+RUN_FRAGMENT = """fragment RunFragment on Run {
+ id
+ tags
+ name
+ displayName
+ sweepName
+ state
+ config
+ group
+ jobType
+ commit
+ readOnly
+ createdAt
+ heartbeatAt
+ description
+ notes
+ systemMetrics
+ summaryMetrics
+ historyLineCount
+ user {
+ name
+ username
+ }
+ historyKeys
+}"""
+
+# Lightweight fragment for listing operations - excludes heavy fields
+LIGHTWEIGHT_RUN_FRAGMENT = """fragment LightweightRunFragment on Run {
+ id
+ tags
+ name
+ displayName
+ sweepName
+ state
+ group
+ jobType
+ commit
+ readOnly
+ createdAt
+ heartbeatAt
+ description
+ notes
+ historyLineCount
+ user {
+ name
+ username
+ }
+}"""
+
+# Fragment name constants to avoid string parsing
+RUN_FRAGMENT_NAME = "RunFragment"
+LIGHTWEIGHT_RUN_FRAGMENT_NAME = "LightweightRunFragment"
+
+
+def _create_runs_query(
+ *, lazy: bool, with_internal_id: bool, with_project_id: bool
+) -> gql:
+ """Create GraphQL query for runs with appropriate fragment."""
+ fragment = LIGHTWEIGHT_RUN_FRAGMENT if lazy else RUN_FRAGMENT
+ fragment_name = LIGHTWEIGHT_RUN_FRAGMENT_NAME if lazy else RUN_FRAGMENT_NAME
+
+ return gql(
+ f"""#graphql
+ query Runs($project: String!, $entity: String!, $cursor: String, $perPage: Int = 50, $order: String, $filters: JSONString) {{
+ project(name: $project, entityName: $entity) {{
+ {"internalId" if with_internal_id else ""}
+ runCount(filters: $filters)
+ readOnly
+ runs(filters: $filters, after: $cursor, first: $perPage, order: $order) {{
+ edges {{
+ node {{
+ {"projectId" if with_project_id else ""}
+ ...{fragment_name}
+ }}
+ cursor
+ }}
+ pageInfo {{
+ endCursor
+ hasNextPage
+ }}
+ }}
+ }}
+ }}
+ {fragment}
+ """
+ )
+
+
+@normalize_exceptions
+def _server_provides_internal_id_for_project(client) -> bool:
+ """Returns True if the server allows us to query the internalId field for a project."""
+ query_string = """
+ query ProbeProjectInput {
+ ProjectType: __type(name:"Project") {
+ fields {
+ name
+ }
+ }
+ }
+ """
+
+ # Only perform the query once to avoid extra network calls
+ query = gql(query_string)
+ res = client.execute(query)
+ return "internalId" in [
+ x["name"] for x in (res.get("ProjectType", {}).get("fields", [{}]))
+ ]
+
+
+@normalize_exceptions
+def _server_provides_project_id_for_run(client) -> bool:
+ """Returns True if the server allows us to query the projectId field for a run."""
+ query_string = """
+ query ProbeRunInput {
+ RunType: __type(name:"Run") {
+ fields {
+ name
+ }
+ }
+ }
+ """
+
+ # Only perform the query once to avoid extra network calls
+ query = gql(query_string)
+ res = client.execute(query)
+ return "projectId" in [
+ x["name"] for x in (res.get("RunType", {}).get("fields", [{}]))
+ ]
+
+
+@normalize_exceptions
+def _convert_to_dict(value: Any) -> dict[str, Any]:
+ """Converts a value to a dictionary.
+
+ If the value is already a dictionary, the value is returned unchanged.
+ If the value is a string, bytes, or bytearray, it is parsed as JSON.
+ For any other type, a TypeError is raised.
+ """
+ if value is None:
+ return {}
+
+ if isinstance(value, dict):
+ return value
+
+ if isinstance(value, (str, bytes, bytearray)):
+ try:
+ return json.loads(value)
+ except json.decoder.JSONDecodeError:
+ # ignore invalid utf-8 or control characters
+ return json.loads(value, strict=False)
+
+ raise TypeError(f"Unable to convert {value} to a dict")
+
+
+class Runs(SizedPaginator["Run"]):
+ """A lazy iterator of `Run` objects associated with a project and optional filter.
+
+ Runs are retrieved in pages from the W&B server as needed.
+
+ This is generally used indirectly using the `Api.runs` namespace.
+
+ Args:
+ client: (`wandb.apis.public.RetryingClient`) The API client to use
+ for requests.
+ entity: (str) The entity (username or team) that owns the project.
+ project: (str) The name of the project to fetch runs from.
+ filters: (Optional[Dict[str, Any]]) A dictionary of filters to apply
+ to the runs query.
+ order: (str) Order can be `created_at`, `heartbeat_at`, `config.*.value`, or `summary_metrics.*`.
+ If you prepend order with a + order is ascending (default).
+ If you prepend order with a - order is descending.
+ The default order is run.created_at from oldest to newest.
+ per_page: (int) The number of runs to fetch per request (default is 50).
+ include_sweeps: (bool) Whether to include sweep information in the
+ runs. Defaults to True.
+
+ Examples:
+ ```python
+ from wandb.apis.public.runs import Runs
+ from wandb.apis.public import Api
+
+ # Get all runs from a project that satisfy the filters
+ filters = {"state": "finished", "config.optimizer": "adam"}
+
+ runs = Api().runs(
+ client=api.client,
+ entity="entity",
+ project="project_name",
+ filters=filters,
+ )
+
+ # Iterate over runs and print details
+ for run in runs:
+ print(f"Run name: {run.name}")
+ print(f"Run ID: {run.id}")
+ print(f"Run URL: {run.url}")
+ print(f"Run state: {run.state}")
+ print(f"Run config: {run.config}")
+ print(f"Run summary: {run.summary}")
+ print(f"Run history (samples=5): {run.history(samples=5)}")
+ print("----------")
+
+ # Get histories for all runs with specific metrics
+ histories_df = runs.histories(
+ samples=100, # Number of samples per run
+ keys=["loss", "accuracy"], # Metrics to fetch
+ x_axis="_step", # X-axis metric
+ format="pandas", # Return as pandas DataFrame
+ )
+ ```
+ """
+
+ def __init__(
+ self,
+ client: RetryingClient,
+ entity: str,
+ project: str,
+ filters: dict[str, Any] | None = None,
+ order: str = "+created_at",
+ per_page: int = 50,
+ include_sweeps: bool = True,
+ lazy: bool = True,
+ ):
+ if not order:
+ order = "+created_at"
+
+ self.QUERY = _create_runs_query(
+ lazy=lazy,
+ with_internal_id=_server_provides_internal_id_for_project(client),
+ with_project_id=_server_provides_project_id_for_run(client),
+ )
+
+ self.entity = entity
+ self.project = project
+ self._project_internal_id = None
+ self.filters = filters or {}
+ self.order = order
+ self._sweeps = {}
+ self._include_sweeps = include_sweeps
+ self._lazy = lazy
+ variables = {
+ "project": self.project,
+ "entity": self.entity,
+ "order": self.order,
+ "filters": json.dumps(self.filters),
+ }
+ super().__init__(client, variables, per_page)
+
+ @property
+ def _length(self):
+ """Returns the total number of runs.
+
+
+ """
+ if not self.last_response:
+ self._load_page()
+ return self.last_response["project"]["runCount"]
+
+ @property
+ def more(self) -> bool:
+ """Returns whether there are more runs to fetch.
+
+
+ """
+ if self.last_response:
+ return bool(
+ self.last_response["project"]["runs"]["pageInfo"]["hasNextPage"]
+ )
+ else:
+ return True
+
+ @property
+ def cursor(self):
+ """Returns the cursor position for pagination of runs results.
+
+
+ """
+ if self.last_response:
+ return self.last_response["project"]["runs"]["edges"][-1]["cursor"]
+ else:
+ return None
+
+ def convert_objects(self):
+ """Converts GraphQL edges to Runs objects.
+
+
+ """
+ objs = []
+ if self.last_response is None or self.last_response.get("project") is None:
+ raise ValueError("Could not find project {}".format(self.project))
+ for run_response in self.last_response["project"]["runs"]["edges"]:
+ run = Run(
+ self.client,
+ self.entity,
+ self.project,
+ run_response["node"]["name"],
+ run_response["node"],
+ include_sweeps=self._include_sweeps,
+ lazy=self._lazy,
+ )
+ objs.append(run)
+
+ if self._include_sweeps and run.sweep_name:
+ if run.sweep_name in self._sweeps:
+ sweep = self._sweeps[run.sweep_name]
+ else:
+ sweep = public.Sweep.get(
+ self.client,
+ self.entity,
+ self.project,
+ run.sweep_name,
+ withRuns=False,
+ )
+ self._sweeps[run.sweep_name] = sweep
+
+ if sweep is None:
+ continue
+ run.sweep = sweep
+
+ return objs
+
+ @normalize_exceptions
+ def histories(
+ self,
+ samples: int = 500,
+ keys: list[str] | None = None,
+ x_axis: str = "_step",
+ format: Literal["default", "pandas", "polars"] = "default",
+ stream: Literal["default", "system"] = "default",
+ ):
+ """Return sampled history metrics for all runs that fit the filters conditions.
+
+ Args:
+ samples: The number of samples to return per run
+ keys: Only return metrics for specific keys
+ x_axis: Use this metric as the xAxis defaults to _step
+ format: Format to return data in, options are "default", "pandas",
+ "polars"
+ stream: "default" for metrics, "system" for machine metrics
+ Returns:
+ pandas.DataFrame: If `format="pandas"`, returns a `pandas.DataFrame`
+ of history metrics.
+ polars.DataFrame: If `format="polars"`, returns a `polars.DataFrame`
+ of history metrics.
+ list of dicts: If `format="default"`, returns a list of dicts
+ containing history metrics with a `run_id` key.
+ """
+ if format not in ("default", "pandas", "polars"):
+ raise ValueError(
+ f"Invalid format: {format}. Must be one of 'default', 'pandas', 'polars'"
+ )
+
+ histories = []
+
+ if format == "default":
+ for run in self:
+ history_data = run.history(
+ samples=samples,
+ keys=keys,
+ x_axis=x_axis,
+ pandas=False,
+ stream=stream,
+ )
+ if not history_data:
+ continue
+ for entry in history_data:
+ entry["run_id"] = run.id
+ histories.extend(history_data)
+
+ return histories
+
+ if format == "pandas":
+ pd = util.get_module(
+ "pandas", required="Exporting pandas DataFrame requires pandas"
+ )
+ for run in self:
+ history_data = run.history(
+ samples=samples,
+ keys=keys,
+ x_axis=x_axis,
+ pandas=False,
+ stream=stream,
+ )
+ if not history_data:
+ continue
+ df = pd.DataFrame.from_records(history_data)
+ df["run_id"] = run.id
+ histories.append(df)
+ if not histories:
+ return pd.DataFrame()
+ combined_df = pd.concat(histories)
+ combined_df.reset_index(drop=True, inplace=True)
+ # sort columns for consistency
+ combined_df = combined_df[(sorted(combined_df.columns))]
+
+ return combined_df
+
+ if format == "polars":
+ pl = util.get_module(
+ "polars", required="Exporting polars DataFrame requires polars"
+ )
+ for run in self:
+ history_data = run.history(
+ samples=samples,
+ keys=keys,
+ x_axis=x_axis,
+ pandas=False,
+ stream=stream,
+ )
+ if not history_data:
+ continue
+ df = pl.from_records(history_data)
+ df = df.with_columns(pl.lit(run.id).alias("run_id"))
+ histories.append(df)
+ if not histories:
+ return pl.DataFrame()
+ combined_df = pl.concat(histories, how="vertical")
+ # sort columns for consistency
+ combined_df = combined_df.select(sorted(combined_df.columns))
+
+ return combined_df
+
+ def __repr__(self):
+ return f""
+
+ def upgrade_to_full(self):
+ """Upgrade this Runs collection from lazy to full mode.
+
+ This switches to fetching full run data and
+ upgrades any already-loaded Run objects to have full data.
+ Uses parallel loading for better performance when upgrading multiple runs.
+ """
+ if not self._lazy:
+ return # Already in full mode
+
+ # Switch to full mode
+ self._lazy = False
+
+ # Regenerate query with full fragment
+ self.QUERY = _create_runs_query(
+ lazy=False,
+ with_internal_id=_server_provides_internal_id_for_project(self.client),
+ with_project_id=_server_provides_project_id_for_run(self.client),
+ )
+
+ # Upgrade any existing runs that have been loaded - use parallel loading for performance
+ lazy_runs = [run for run in self.objects if run._lazy]
+ if lazy_runs:
+ from concurrent.futures import ThreadPoolExecutor
+
+ # Limit workers to avoid overwhelming the server
+ max_workers = min(len(lazy_runs), 10)
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
+ futures = [executor.submit(run.load_full_data) for run in lazy_runs]
+ # Wait for all to complete
+ for future in futures:
+ future.result()
+
+
+class Run(Attrs):
+ """A single run associated with an entity and project.
+
+ Args:
+ client: The W&B API client.
+ entity: The entity associated with the run.
+ project: The project associated with the run.
+ run_id: The unique identifier for the run.
+ attrs: The attributes of the run.
+ include_sweeps: Whether to include sweeps in the run.
+
+ Attributes:
+ tags ([str]): a list of tags associated with the run
+ url (str): the url of this run
+ id (str): unique identifier for the run (defaults to eight characters)
+ name (str): the name of the run
+ state (str): one of: running, finished, crashed, killed, preempting, preempted
+ config (dict): a dict of hyperparameters associated with the run
+ created_at (str): ISO timestamp when the run was started
+ system_metrics (dict): the latest system metrics recorded for the run
+ summary (dict): A mutable dict-like property that holds the current summary.
+ Calling update will persist any changes.
+ project (str): the project associated with the run
+ entity (str): the name of the entity associated with the run
+ project_internal_id (int): the internal id of the project
+ user (str): the name of the user who created the run
+ path (str): Unique identifier [entity]/[project]/[run_id]
+ notes (str): Notes about the run
+ read_only (boolean): Whether the run is editable
+ history_keys (str): Keys of the history metrics that have been logged
+ with `wandb.log({key: value})`
+ metadata (str): Metadata about the run from wandb-metadata.json
+ """
+
+ def __init__(
+ self,
+ client: RetryingClient,
+ entity: str,
+ project: str,
+ run_id: str,
+ attrs: Mapping | None = None,
+ include_sweeps: bool = True,
+ lazy: bool = True,
+ ):
+ """Initialize a Run object.
+
+ Run is always initialized by calling api.runs() where api is an instance of
+ wandb.Api.
+ """
+ _attrs = attrs or {}
+ super().__init__(dict(_attrs))
+ self.client = client
+ self._entity = entity
+ self.project = project
+ self._files = {}
+ self._base_dir = env.get_dir(tempfile.gettempdir())
+ self.id = run_id
+ self.sweep = None
+ self._include_sweeps = include_sweeps
+ self._lazy = lazy
+ self._full_data_loaded = False # Track if we've loaded full data
+ self.dir = os.path.join(self._base_dir, *self.path)
+ try:
+ os.makedirs(self.dir)
+ except OSError:
+ pass
+ self._summary = None
+ self._metadata: dict[str, Any] | None = None
+ self._state = _attrs.get("state", "not found")
+ self.server_provides_internal_id_field: bool | None = None
+ self._server_provides_project_id_field: bool | None = None
+ self._is_loaded: bool = False
+
+ self.load(force=not _attrs)
+
+ @property
+ def state(self):
+ """The state of the run. Can be one of: Finished, Failed, Crashed, or Running."""
+ return self._state
+
+ @property
+ def entity(self):
+ """The entity associated with the run."""
+ return self._entity
+
+ @property
+ def username(self):
+ """This API is deprecated. Use `entity` instead."""
+ wandb.termwarn("Run.username is deprecated. Please use Run.entity instead.")
+ return self._entity
+
+ @property
+ def storage_id(self):
+ """The unique storage identifier for the run."""
+ # For compatibility with wandb.Run, which has storage IDs
+ # in self.storage_id and names in self.id.
+
+ return self._attrs.get("id")
+
+ @property
+ def id(self):
+ """The unique identifier for the run."""
+ return self._attrs.get("name")
+
+ @id.setter
+ def id(self, new_id):
+ """Set the unique identifier for the run."""
+ attrs = self._attrs
+ attrs["name"] = new_id
+ return new_id
+
+ @property
+ def name(self):
+ """The name of the run."""
+ return self._attrs.get("displayName")
+
+ @name.setter
+ def name(self, new_name):
+ """Set the name of the run."""
+ self._attrs["displayName"] = new_name
+ return new_name
+
+ @classmethod
+ def create(
+ cls,
+ api: public.Api,
+ run_id: str | None = None,
+ project: str | None = None,
+ entity: str | None = None,
+ state: Literal["running", "pending"] = "running",
+ ):
+ """Create a run for the given project."""
+ api._sentry.message("Invoking Run.create", level="info")
+ run_id = run_id or runid.generate_id()
+ project = project or api.settings.get("project") or "uncategorized"
+ mutation = gql(
+ """
+ mutation UpsertBucket($project: String, $entity: String, $name: String!, $state: String) {
+ upsertBucket(input: {modelName: $project, entityName: $entity, name: $name, state: $state}) {
+ bucket {
+ project {
+ name
+ entity { name }
+ }
+ id
+ name
+ }
+ inserted
+ }
+ }
+ """
+ )
+ variables = {
+ "entity": entity,
+ "project": project,
+ "name": run_id,
+ "state": state,
+ }
+ res = api.client.execute(mutation, variable_values=variables)
+ res = res["upsertBucket"]["bucket"]
+ return Run(
+ api.client,
+ res["project"]["entity"]["name"],
+ res["project"]["name"],
+ res["name"],
+ {
+ "id": res["id"],
+ "config": "{}",
+ "systemMetrics": "{}",
+ "summaryMetrics": "{}",
+ "tags": [],
+ "description": None,
+ "notes": None,
+ "state": state,
+ },
+ lazy=False, # Created runs should have full data available immediately
+ )
+
+ def _load_with_fragment(
+ self, fragment: str, fragment_name: str, force: bool = False
+ ):
+ """Load run data using specified GraphQL fragment."""
+ # Cache the server capability check to avoid repeated network calls
+ if self._server_provides_project_id_field is None:
+ self._server_provides_project_id_field = (
+ _server_provides_project_id_for_run(self.client)
+ )
+
+ query = gql(
+ f"""
+ query Run($project: String!, $entity: String!, $name: String!) {{
+ project(name: $project, entityName: $entity) {{
+ run(name: $name) {{
+ {"projectId" if self._server_provides_project_id_field else ""}
+ ...{fragment_name}
+ }}
+ }}
+ }}
+ {fragment}
+ """
+ )
+
+ if force or not self._attrs:
+ response = self._exec(query)
+ if (
+ response is None
+ or response.get("project") is None
+ or response["project"].get("run") is None
+ ):
+ raise ValueError("Could not find run {}".format(self))
+ self._attrs = response["project"]["run"]
+
+ self._state = self._attrs["state"]
+ if self._attrs.get("user"):
+ self.user = public.User(self.client, self._attrs["user"])
+
+ if self._include_sweeps and self.sweep_name and not self.sweep:
+ # There may be a lot of runs. Don't bother pulling them all
+ # just for the sake of this one.
+ self.sweep = public.Sweep.get(
+ self.client,
+ self.entity,
+ self.project,
+ self.sweep_name,
+ withRuns=False,
+ )
+
+ if not self._is_loaded:
+ # Always set _project_internal_id if projectId is available, regardless of fragment type
+ if "projectId" in self._attrs:
+ self._project_internal_id = int(self._attrs["projectId"])
+ else:
+ self._project_internal_id = None
+
+ # Only call _load_from_attrs when using the full fragment or when the fields are actually present
+ if fragment_name == RUN_FRAGMENT_NAME or (
+ "config" in self._attrs
+ or "summaryMetrics" in self._attrs
+ or "systemMetrics" in self._attrs
+ ):
+ self._load_from_attrs()
+ self._is_loaded = True
+
+ return self._attrs
+
+ def _load_from_attrs(self):
+ self._state = self._attrs.get("state", None)
+
+ # Only convert fields if they exist in _attrs
+ if "config" in self._attrs:
+ self._attrs["config"] = _convert_to_dict(self._attrs.get("config"))
+ if "summaryMetrics" in self._attrs:
+ self._attrs["summaryMetrics"] = _convert_to_dict(
+ self._attrs.get("summaryMetrics")
+ )
+ if "systemMetrics" in self._attrs:
+ self._attrs["systemMetrics"] = _convert_to_dict(
+ self._attrs.get("systemMetrics")
+ )
+
+ # Only check for sweeps if sweep_name is available (not in lazy mode or if it exists)
+ if self._include_sweeps and self._attrs.get("sweepName") and not self.sweep:
+ # There may be a lot of runs. Don't bother pulling them all
+ self.sweep = public.Sweep(
+ self.client,
+ self.entity,
+ self.project,
+ self._attrs["sweepName"],
+ withRuns=False,
+ )
+
+ config_user, config_raw = {}, {}
+ if self._attrs.get("config"):
+ try:
+ # config is already converted to dict by _convert_to_dict
+ for key, value in self._attrs.get("config", {}).items():
+ config = config_raw if key in WANDB_INTERNAL_KEYS else config_user
+ if isinstance(value, dict) and "value" in value:
+ config[key] = value["value"]
+ else:
+ config[key] = value
+ except (TypeError, AttributeError):
+ # Handle case where config is malformed or not a dict
+ pass
+
+ config_raw.update(config_user)
+ self._attrs["config"] = config_user
+ self._attrs["rawconfig"] = config_raw
+
+ return self._attrs
+
+ def load(self, force=False):
+ """Load run data using appropriate fragment based on lazy mode."""
+ if self._lazy:
+ return self._load_with_fragment(
+ LIGHTWEIGHT_RUN_FRAGMENT, LIGHTWEIGHT_RUN_FRAGMENT_NAME, force
+ )
+ else:
+ return self._load_with_fragment(RUN_FRAGMENT, RUN_FRAGMENT_NAME, force)
+
+ @normalize_exceptions
+ def wait_until_finished(self):
+ """Check the state of the run until it is finished."""
+ query = gql(
+ """
+ query RunState($project: String!, $entity: String!, $name: String!) {
+ project(name: $project, entityName: $entity) {
+ run(name: $name) {
+ state
+ }
+ }
+ }
+ """
+ )
+ while True:
+ res = self._exec(query)
+ state = res["project"]["run"]["state"]
+ if state in ["finished", "crashed", "failed"]:
+ self._attrs["state"] = state
+ self._state = state
+ return
+ time.sleep(5)
+
+ @normalize_exceptions
+ def update(self):
+ """Persist changes to the run object to the wandb backend."""
+ mutation = gql(
+ """
+ mutation UpsertBucket($id: String!, $description: String, $display_name: String, $notes: String, $tags: [String!], $config: JSONString!, $groupName: String, $jobType: String) {{
+ upsertBucket(input: {{id: $id, description: $description, displayName: $display_name, notes: $notes, tags: $tags, config: $config, groupName: $groupName, jobType: $jobType}}) {{
+ bucket {{
+ ...RunFragment
+ }}
+ }}
+ }}
+ {}
+ """.format(RUN_FRAGMENT)
+ )
+ _ = self._exec(
+ mutation,
+ id=self.storage_id,
+ tags=self.tags,
+ description=self.description,
+ notes=self.notes,
+ display_name=self.display_name,
+ config=self.json_config,
+ groupName=self.group,
+ jobType=self.job_type,
+ )
+ self.summary.update()
+
+ @normalize_exceptions
+ def delete(self, delete_artifacts=False):
+ """Delete the given run from the wandb backend.
+
+ Args:
+ delete_artifacts (bool, optional): Whether to delete the artifacts
+ associated with the run.
+ """
+ mutation = gql(
+ """
+ mutation DeleteRun(
+ $id: ID!,
+ {}
+ ) {{
+ deleteRun(input: {{
+ id: $id,
+ {}
+ }}) {{
+ clientMutationId
+ }}
+ }}
+ """.format(
+ "$deleteArtifacts: Boolean" if delete_artifacts else "",
+ "deleteArtifacts: $deleteArtifacts" if delete_artifacts else "",
+ )
+ )
+
+ self.client.execute(
+ mutation,
+ variable_values={
+ "id": self.storage_id,
+ "deleteArtifacts": delete_artifacts,
+ },
+ )
+
+ def save(self):
+ """Persist changes to the run object to the W&B backend."""
+ self.update()
+
+ @property
+ def json_config(self):
+ """Return the run config as a JSON string.
+
+
+ """
+ config = {}
+ if "_wandb" in self.rawconfig:
+ config["_wandb"] = {"value": self.rawconfig["_wandb"], "desc": None}
+ for k, v in self.config.items():
+ config[k] = {"value": v, "desc": None}
+ return json.dumps(config)
+
+ def _exec(self, query, **kwargs):
+ """Execute a query against the cloud backend."""
+ variables = {"entity": self.entity, "project": self.project, "name": self.id}
+ variables.update(kwargs)
+ return self.client.execute(query, variable_values=variables)
+
+ def _sampled_history(self, keys, x_axis="_step", samples=500):
+ spec = {"keys": [x_axis] + keys, "samples": samples}
+ query = gql(
+ """
+ query RunSampledHistory($project: String!, $entity: String!, $name: String!, $specs: [JSONString!]!) {
+ project(name: $project, entityName: $entity) {
+ run(name: $name) { sampledHistory(specs: $specs) }
+ }
+ }
+ """
+ )
+
+ response = self._exec(query, specs=[json.dumps(spec)])
+ # sampledHistory returns one list per spec, we only send one spec
+ return response["project"]["run"]["sampledHistory"][0]
+
+ def _full_history(self, samples=500, stream="default"):
+ node = "history" if stream == "default" else "events"
+ query = gql(
+ """
+ query RunFullHistory($project: String!, $entity: String!, $name: String!, $samples: Int) {{
+ project(name: $project, entityName: $entity) {{
+ run(name: $name) {{ {}(samples: $samples) }}
+ }}
+ }}
+ """.format(node)
+ )
+
+ response = self._exec(query, samples=samples)
+ return [json.loads(line) for line in response["project"]["run"][node]]
+
+ @normalize_exceptions
+ def files(
+ self,
+ names: list[str] | None = None,
+ pattern: str | None = None,
+ per_page: int = 50,
+ ):
+ """Returns a `Files` object for all files in the run which match the given criteria.
+
+ You can specify a list of exact file names to match, or a pattern to match against.
+ If both are provided, the pattern will be ignored.
+
+ Args:
+ names (list): names of the requested files, if empty returns all files
+ pattern (str, optional): Pattern to match when returning files from W&B.
+ This pattern uses mySQL's LIKE syntax,
+ so matching all files that end with .json would be "%.json".
+ If both names and pattern are provided, a ValueError will be raised.
+ per_page (int): number of results per page.
+
+ Returns:
+ A `Files` object, which is an iterator over `File` objects.
+ """
+ return public.Files(
+ self.client,
+ self,
+ names or [],
+ pattern=pattern,
+ per_page=per_page,
+ )
+
+ @normalize_exceptions
+ def file(self, name):
+ """Return the path of a file with a given name in the artifact.
+
+ Args:
+ name (str): name of requested file.
+
+ Returns:
+ A `File` matching the name argument.
+ """
+ return public.Files(self.client, self, [name])[0]
+
+ @normalize_exceptions
+ def upload_file(self, path, root="."):
+ """Upload a local file to W&B, associating it with this run.
+
+ Args:
+ path (str): Path to the file to upload. Can be absolute or relative.
+ root (str): The root path to save the file relative to. For example,
+ if you want to have the file saved in the run as "my_dir/file.txt"
+ and you're currently in "my_dir" you would set root to "../".
+ Defaults to current directory (".").
+
+ Returns:
+ A `File` object representing the uploaded file.
+ """
+ api = InternalApi(
+ default_settings={"entity": self.entity, "project": self.project},
+ retry_timedelta=RETRY_TIMEDELTA,
+ )
+ api.set_current_run_id(self.id)
+ root = os.path.abspath(root)
+ name = os.path.relpath(path, root)
+ upload_path = util.make_file_path_upload_safe(name)
+ with open(os.path.join(root, name), "rb") as f:
+ api.push({LogicalPath(upload_path): f})
+ return public.Files(self.client, self, [name])[0]
+
+ @normalize_exceptions
+ def history(
+ self, samples=500, keys=None, x_axis="_step", pandas=True, stream="default"
+ ):
+ """Return sampled history metrics for a run.
+
+ This is simpler and faster if you are ok with the history records being sampled.
+
+ Args:
+ samples : (int, optional) The number of samples to return
+ pandas : (bool, optional) Return a pandas dataframe
+ keys : (list, optional) Only return metrics for specific keys
+ x_axis : (str, optional) Use this metric as the xAxis defaults to _step
+ stream : (str, optional) "default" for metrics, "system" for machine metrics
+
+ Returns:
+ pandas.DataFrame: If pandas=True returns a `pandas.DataFrame` of history
+ metrics.
+ list of dicts: If pandas=False returns a list of dicts of history metrics.
+ """
+ if keys is not None and not isinstance(keys, list):
+ wandb.termerror("keys must be specified in a list")
+ return []
+ if keys is not None and len(keys) > 0 and not isinstance(keys[0], str):
+ wandb.termerror("keys argument must be a list of strings")
+ return []
+
+ if keys and stream != "default":
+ wandb.termerror("stream must be default when specifying keys")
+ return []
+ elif keys:
+ lines = self._sampled_history(keys=keys, x_axis=x_axis, samples=samples)
+ else:
+ lines = self._full_history(samples=samples, stream=stream)
+ if pandas:
+ pd = util.get_module("pandas")
+ if pd:
+ lines = pd.DataFrame.from_records(lines)
+ else:
+ wandb.termwarn("Unable to load pandas, call history with pandas=False")
+ return lines
+
+ @normalize_exceptions
+ def scan_history(self, keys=None, page_size=1000, min_step=None, max_step=None):
+ """Returns an iterable collection of all history records for a run.
+
+ Args:
+ keys ([str], optional): only fetch these keys, and only fetch rows that have all of keys defined.
+ page_size (int, optional): size of pages to fetch from the api.
+ min_step (int, optional): the minimum number of pages to scan at a time.
+ max_step (int, optional): the maximum number of pages to scan at a time.
+
+ Returns:
+ An iterable collection over history records (dict).
+
+ Example:
+ Export all the loss values for an example run
+
+ ```python
+ run = api.run("entity/project-name/run-id")
+ history = run.scan_history(keys=["Loss"])
+ losses = [row["Loss"] for row in history]
+ ```
+ """
+ if keys is not None and not isinstance(keys, list):
+ wandb.termerror("keys must be specified in a list")
+ return []
+ if keys is not None and len(keys) > 0 and not isinstance(keys[0], str):
+ wandb.termerror("keys argument must be a list of strings")
+ return []
+
+ last_step = self.lastHistoryStep
+ # set defaults for min/max step
+ if min_step is None:
+ min_step = 0
+ if max_step is None:
+ max_step = last_step + 1
+ # if the max step is past the actual last step, clamp it down
+ if max_step > last_step:
+ max_step = last_step + 1
+ if keys is None:
+ return public.HistoryScan(
+ run=self,
+ client=self.client,
+ page_size=page_size,
+ min_step=min_step,
+ max_step=max_step,
+ )
+ else:
+ return public.SampledHistoryScan(
+ run=self,
+ client=self.client,
+ keys=keys,
+ page_size=page_size,
+ min_step=min_step,
+ max_step=max_step,
+ )
+
+ @normalize_exceptions
+ def logged_artifacts(self, per_page: int = 100) -> public.RunArtifacts:
+ """Fetches all artifacts logged by this run.
+
+ Retrieves all output artifacts that were logged during the run. Returns a
+ paginated result that can be iterated over or collected into a single list.
+
+ Args:
+ per_page: Number of artifacts to fetch per API request.
+
+ Returns:
+ An iterable collection of all Artifact objects logged as outputs during this run.
+
+ Example:
+ ```python
+ import wandb
+ import tempfile
+
+ with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".txt") as tmp:
+ tmp.write("This is a test artifact")
+ tmp_path = tmp.name
+ run = wandb.init(project="artifact-example")
+ artifact = wandb.Artifact("test_artifact", type="dataset")
+ artifact.add_file(tmp_path)
+ run.log_artifact(artifact)
+ run.finish()
+
+ api = wandb.Api()
+
+ finished_run = api.run(f"{run.entity}/{run.project}/{run.id}")
+
+ for logged_artifact in finished_run.logged_artifacts():
+ print(logged_artifact.name)
+ ```
+
+ """
+ return public.RunArtifacts(self.client, self, mode="logged", per_page=per_page)
+
+ @normalize_exceptions
+ def used_artifacts(self, per_page: int = 100) -> public.RunArtifacts:
+ """Fetches artifacts explicitly used by this run.
+
+ Retrieves only the input artifacts that were explicitly declared as used
+ during the run, typically via `run.use_artifact()`. Returns a paginated
+ result that can be iterated over or collected into a single list.
+
+ Args:
+ per_page: Number of artifacts to fetch per API request.
+
+ Returns:
+ An iterable collection of Artifact objects explicitly used as inputs in this run.
+
+ Example:
+ ```python
+ import wandb
+
+ run = wandb.init(project="artifact-example")
+ run.use_artifact("test_artifact:latest")
+ run.finish()
+
+ api = wandb.Api()
+ finished_run = api.run(f"{run.entity}/{run.project}/{run.id}")
+ for used_artifact in finished_run.used_artifacts():
+ print(used_artifact.name)
+ test_artifact
+ ```
+ """
+ return public.RunArtifacts(self.client, self, mode="used", per_page=per_page)
+
+ @normalize_exceptions
+ def use_artifact(self, artifact, use_as=None):
+ """Declare an artifact as an input to a run.
+
+ Args:
+ artifact (`Artifact`): An artifact returned from
+ `wandb.Api().artifact(name)`
+ use_as (string, optional): A string identifying
+ how the artifact is used in the script. Used
+ to easily differentiate artifacts used in a
+ run, when using the beta wandb launch
+ feature's artifact swapping functionality.
+
+ Returns:
+ An `Artifact` object.
+ """
+ api = InternalApi(
+ default_settings={"entity": self.entity, "project": self.project},
+ retry_timedelta=RETRY_TIMEDELTA,
+ )
+ api.set_current_run_id(self.id)
+
+ if isinstance(artifact, wandb.Artifact) and not artifact.is_draft():
+ api.use_artifact(
+ artifact.id,
+ use_as=use_as or artifact.name,
+ artifact_entity_name=artifact.entity,
+ artifact_project_name=artifact.project,
+ )
+ return artifact
+ elif isinstance(artifact, wandb.Artifact) and artifact.is_draft():
+ raise ValueError(
+ "Only existing artifacts are accepted by this api. "
+ "Manually create one with `wandb artifact put`"
+ )
+ else:
+ raise ValueError("You must pass a wandb.Api().artifact() to use_artifact")
+
+ @normalize_exceptions
+ def log_artifact(
+ self,
+ artifact: wandb.Artifact,
+ aliases: Collection[str] | None = None,
+ tags: Collection[str] | None = None,
+ ):
+ """Declare an artifact as output of a run.
+
+ Args:
+ artifact (`Artifact`): An artifact returned from
+ `wandb.Api().artifact(name)`.
+ aliases (list, optional): Aliases to apply to this artifact.
+ tags: (list, optional) Tags to apply to this artifact, if any.
+
+ Returns:
+ A `Artifact` object.
+ """
+ api = InternalApi(
+ default_settings={"entity": self.entity, "project": self.project},
+ retry_timedelta=RETRY_TIMEDELTA,
+ )
+ api.set_current_run_id(self.id)
+
+ if not isinstance(artifact, wandb.Artifact):
+ raise TypeError("You must pass a wandb.Api().artifact() to use_artifact")
+ if artifact.is_draft():
+ raise ValueError(
+ "Only existing artifacts are accepted by this api. "
+ "Manually create one with `wandb artifact put`"
+ )
+ if (
+ self.entity != artifact.source_entity
+ or self.project != artifact.source_project
+ ):
+ raise ValueError("A run can't log an artifact to a different project.")
+
+ artifact_collection_name = artifact.source_name.split(":")[0]
+ api.create_artifact(
+ artifact.type,
+ artifact_collection_name,
+ artifact.digest,
+ aliases=aliases,
+ tags=tags,
+ )
+ return artifact
+
+ def load_full_data(self, force: bool = False) -> dict[str, Any]:
+ """Load full run data including heavy fields like config, systemMetrics, summaryMetrics.
+
+ This method is useful when you initially used lazy=True for listing runs,
+ but need access to the full data for specific runs.
+
+ Args:
+ force: Force reload even if data is already loaded
+
+ Returns:
+ The loaded run attributes
+ """
+ if not self._lazy and not force:
+ # Already in full mode, no need to reload
+ return self._attrs
+
+ # Load full data and mark as loaded
+ result = self._load_with_fragment(RUN_FRAGMENT, RUN_FRAGMENT_NAME, force=True)
+ self._full_data_loaded = True
+ return result
+
+ @property
+ def config(self):
+ """Get run config. Auto-loads full data if in lazy mode."""
+ if self._lazy and not self._full_data_loaded and "config" not in self._attrs:
+ self.load_full_data()
+ return self._attrs.get("config", {})
+
+ @property
+ def summary(self):
+ """Get run summary metrics. Auto-loads full data if in lazy mode."""
+ if (
+ self._lazy
+ and not self._full_data_loaded
+ and "summaryMetrics" not in self._attrs
+ ):
+ self.load_full_data()
+ if self._summary is None:
+ from wandb.old.summary import HTTPSummary
+
+ # TODO: fix the outdir issue
+ self._summary = HTTPSummary(self, self.client, summary=self.summary_metrics)
+ return self._summary
+
+ @property
+ def system_metrics(self):
+ """Get run system metrics. Auto-loads full data if in lazy mode."""
+ if (
+ self._lazy
+ and not self._full_data_loaded
+ and "systemMetrics" not in self._attrs
+ ):
+ self.load_full_data()
+ return self._attrs.get("systemMetrics", {})
+
+ @property
+ def summary_metrics(self):
+ """Get run summary metrics. Auto-loads full data if in lazy mode."""
+ if (
+ self._lazy
+ and not self._full_data_loaded
+ and "summaryMetrics" not in self._attrs
+ ):
+ self.load_full_data()
+ return self._attrs.get("summaryMetrics", {})
+
+ @property
+ def rawconfig(self):
+ """Get raw run config including internal keys. Auto-loads full data if in lazy mode."""
+ if self._lazy and not self._full_data_loaded and "rawconfig" not in self._attrs:
+ self.load_full_data()
+ return self._attrs.get("rawconfig", {})
+
+ @property
+ def sweep_name(self):
+ """Get sweep name. Always available since sweepName is in lightweight fragment."""
+ # sweepName is included in lightweight fragment, so no need to load full data
+ return self._attrs.get("sweepName")
+
+ @property
+ def path(self):
+ """The path of the run. The path is a list containing the entity, project, and run_id."""
+ return [
+ urllib.parse.quote_plus(str(self.entity)),
+ urllib.parse.quote_plus(str(self.project)),
+ urllib.parse.quote_plus(str(self.id)),
+ ]
+
+ @property
+ def url(self):
+ """The URL of the run.
+
+ The run URL is generated from the entity, project, and run_id. For
+ SaaS users, it takes the form of `https://wandb.ai/entity/project/run_id`.
+ """
+ path = self.path
+ path.insert(2, "runs")
+ return self.client.app_url + "/".join(path)
+
+ @property
+ def metadata(self):
+ """Metadata about the run from wandb-metadata.json.
+
+ Metadata includes the run's description, tags, start time, memory
+ usage and more.
+ """
+ if self._metadata is None:
+ try:
+ f = self.file("wandb-metadata.json")
+ session = self.client._client.transport.session
+ response = session.get(f.url, timeout=5)
+ response.raise_for_status()
+ contents = response.content
+ self._metadata = json_util.loads(contents)
+ except: # noqa: E722
+ # file doesn't exist, or can't be downloaded, or can't be parsed
+ pass
+ return self._metadata
+
+ @property
+ def lastHistoryStep(self): # noqa: N802
+ """Returns the last step logged in the run's history."""
+ query = gql(
+ """
+ query RunHistoryKeys($project: String!, $entity: String!, $name: String!) {
+ project(name: $project, entityName: $entity) {
+ run(name: $name) { historyKeys }
+ }
+ }
+ """
+ )
+ response = self._exec(query)
+ if (
+ response is None
+ or response.get("project") is None
+ or response["project"].get("run") is None
+ or response["project"]["run"].get("historyKeys") is None
+ ):
+ return -1
+ history_keys = response["project"]["run"]["historyKeys"]
+ return history_keys["lastStep"] if "lastStep" in history_keys else -1
+
+ def to_html(self, height=420, hidden=False):
+ """Generate HTML containing an iframe displaying this run."""
+ url = self.url + "?jupyter=true"
+ style = f"border:none;width:100%;height:{height}px;"
+ prefix = ""
+ if hidden:
+ style += "display:none;"
+ prefix = ipython.toggle_button()
+ return prefix + f""
+
+ def _repr_html_(self) -> str:
+ return self.to_html()
+
+ def __repr__(self):
+ return "".format("/".join(self.path), self.state)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/sweeps.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/sweeps.py
new file mode 100644
index 0000000000000000000000000000000000000000..188c4fb08026659f40d406c11246c63aca4d2aba
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/sweeps.py
@@ -0,0 +1,441 @@
+"""W&B Public API for Sweeps.
+
+This module provides classes for interacting with W&B hyperparameter
+optimization sweeps.
+
+Example:
+```python
+from wandb.apis.public import Api
+
+# Get a specific sweep
+sweep = Api().sweep("entity/project/sweep_id")
+
+# Access sweep properties
+print(f"Sweep: {sweep.name}")
+print(f"State: {sweep.state}")
+print(f"Best Loss: {sweep.best_loss}")
+
+# Get best performing run
+best_run = sweep.best_run()
+print(f"Best Run: {best_run.name}")
+print(f"Metrics: {best_run.summary}")
+```
+
+Note:
+ This module is part of the W&B Public API and provides read-only access
+ to sweep data. For creating and controlling sweeps, use the wandb.sweep()
+ and wandb.agent() functions from the main wandb package.
+"""
+
+from __future__ import annotations
+
+import urllib
+
+from wandb_gql import gql
+
+import wandb
+from wandb import util
+from wandb.apis import public
+from wandb.apis.attrs import Attrs
+from wandb.apis.paginator import SizedPaginator
+from wandb.apis.public.api import RetryingClient
+from wandb.sdk.lib import ipython
+
+SWEEP_FRAGMENT = """fragment SweepFragment on Sweep {
+ id
+ name
+ method
+ state
+ description
+ displayName
+ bestLoss
+ config
+ createdAt
+ updatedAt
+ runCount
+}
+"""
+
+
+class Sweeps(SizedPaginator["Sweep"]):
+ """A lazy iterator over a collection of `Sweep` objects.
+
+ Examples:
+ ```python
+ from wandb.apis.public import Api
+
+ sweeps = Api().project(name="project_name", entity="entity").sweeps()
+
+ # Iterate over sweeps and print details
+ for sweep in sweeps:
+ print(f"Sweep name: {sweep.name}")
+ print(f"Sweep ID: {sweep.id}")
+ print(f"Sweep URL: {sweep.url}")
+ print("----------")
+ ```
+ """
+
+ QUERY = gql(
+ f"""#graphql
+ query GetSweeps($project: String!, $entity: String!, $cursor: String, $perPage: Int = 50) {{
+ project(name: $project, entityName: $entity) {{
+ totalSweeps
+ sweeps(after: $cursor, first: $perPage) {{
+ edges {{
+ node {{
+ ...SweepFragment
+ }}
+ cursor
+ }}
+ pageInfo {{
+ endCursor
+ hasNextPage
+ }}
+ }}
+ }}
+ }}
+ {SWEEP_FRAGMENT}
+ """
+ )
+
+ def __init__(
+ self,
+ client: RetryingClient,
+ entity: str,
+ project: str,
+ per_page: int = 50,
+ ) -> Sweeps:
+ """An iterable collection of `Sweep` objects.
+
+ Args:
+ client: The API client used to query W&B.
+ entity: The entity which owns the sweeps.
+ project: The project which contains the sweeps.
+ per_page: The number of sweeps to fetch per request to the API.
+ """
+ self.client = client
+ self.entity = entity
+ self.project = project
+ variables = {
+ "project": self.project,
+ "entity": self.entity,
+ }
+ super().__init__(client, variables, per_page)
+
+ @property
+ def _length(self):
+ """The total number of sweeps in the project.
+
+
+ """
+ if not self.last_response:
+ self._load_page()
+
+ return (
+ self.last_response["project"]["totalSweeps"]
+ if self.last_response["project"]["totalSweeps"] is not None
+ else 0
+ )
+
+ @property
+ def more(self):
+ """Returns whether there are more sweeps to fetch.
+
+
+ """
+ if self.last_response:
+ return bool(
+ self.last_response["project"]["sweeps"]["pageInfo"]["hasNextPage"]
+ )
+ else:
+ return True
+
+ @property
+ def cursor(self):
+ """Returns the cursor for the next page of sweeps.
+
+
+ """
+ if self.last_response:
+ return self.last_response["project"]["sweeps"]["pageInfo"]["endCursor"]
+ else:
+ return None
+
+ def update_variables(self):
+ """Updates the variables for the next page of sweeps.
+
+
+ """
+ self.variables.update({"perPage": self.per_page, "cursor": self.cursor})
+
+ def convert_objects(self):
+ """Converts the last GraphQL response into a list of `Sweep` objects.
+
+
+ """
+ if self.last_response is None or self.last_response.get("project") is None:
+ raise ValueError("Could not find project {}".format(self.project))
+
+ if self.last_response["project"]["totalSweeps"] < 1:
+ return []
+
+ return [
+ # match format of existing public sweep apis
+ public.Sweep(
+ self.client,
+ self.entity,
+ self.project,
+ e["node"]["name"],
+ )
+ for e in self.last_response["project"]["sweeps"]["edges"]
+ ]
+
+ def __repr__(self):
+ return f""
+
+
+class Sweep(Attrs):
+ """The set of runs associated with the sweep.
+
+ Attributes:
+ runs (Runs): List of runs
+ id (str): Sweep ID
+ project (str): The name of the project the sweep belongs to
+ config (dict): Dictionary containing the sweep configuration
+ state (str): The state of the sweep. Can be "Finished", "Failed",
+ "Crashed", or "Running".
+ expected_run_count (int): The number of expected runs for the sweep
+ """
+
+ QUERY = gql(
+ """
+ query Sweep($project: String, $entity: String, $name: String!) {
+ project(name: $project, entityName: $entity) {
+ sweep(sweepName: $name) {
+ id
+ name
+ displayName
+ state
+ runCountExpected
+ bestLoss
+ config
+ }
+ }
+ }
+ """
+ )
+
+ LEGACY_QUERY = gql(
+ """
+ query Sweep($project: String, $entity: String, $name: String!) {
+ project(name: $project, entityName: $entity) {
+ sweep(sweepName: $name) {
+ id
+ name
+ state
+ bestLoss
+ config
+ }
+ }
+ }
+ """
+ )
+
+ def __init__(self, client, entity, project, sweep_id, attrs=None):
+ # TODO: Add agents / flesh this out.
+ super().__init__(dict(attrs or {}))
+ self.client = client
+ self._entity = entity
+ self.project = project
+ self.id = sweep_id
+ self.runs = []
+
+ self.load(force=not attrs)
+
+ @property
+ def entity(self):
+ """The entity associated with the sweep."""
+ return self._entity
+
+ @property
+ def username(self):
+ """Deprecated. Use `Sweep.entity` instead."""
+ wandb.termwarn("Sweep.username is deprecated. please use Sweep.entity instead.")
+ return self._entity
+
+ @property
+ def config(self):
+ """The sweep configuration used for the sweep."""
+ return util.load_yaml(self._attrs["config"])
+
+ def load(self, force: bool = False):
+ """Fetch and update sweep data logged to the run from GraphQL database.
+
+
+ """
+ if force or not self._attrs:
+ sweep = self.get(self.client, self.entity, self.project, self.id)
+ if sweep is None:
+ raise ValueError("Could not find sweep {}".format(self))
+ self._attrs = sweep._attrs
+ self.runs = sweep.runs
+
+ return self._attrs
+
+ @property
+ def order(self):
+ """Return the order key for the sweep."""
+ if self._attrs.get("config") and self.config.get("metric"):
+ sort_order = self.config["metric"].get("goal", "minimize")
+ prefix = "+" if sort_order == "minimize" else "-"
+ return public.QueryGenerator.format_order_key(
+ prefix + self.config["metric"]["name"]
+ )
+
+ def best_run(self, order=None):
+ """Return the best run sorted by the metric defined in config or the order passed in."""
+ if order is None:
+ order = self.order
+ else:
+ order = public.QueryGenerator.format_order_key(order)
+ if order is None:
+ wandb.termwarn(
+ "No order specified and couldn't find metric in sweep config, returning most recent run"
+ )
+ else:
+ wandb.termlog("Sorting runs by {}".format(order))
+ filters = {"$and": [{"sweep": self.id}]}
+ try:
+ return public.Runs(
+ self.client,
+ self.entity,
+ self.project,
+ order=order,
+ filters=filters,
+ per_page=1,
+ )[0]
+ except IndexError:
+ return None
+
+ @property
+ def expected_run_count(self) -> int | None:
+ """Return the number of expected runs in the sweep or None for infinite runs."""
+ return self._attrs.get("runCountExpected")
+
+ @property
+ def path(self):
+ """Returns the path of the project.
+
+ The path is a list containing the entity, project name, and sweep ID."""
+ return [
+ urllib.parse.quote_plus(str(self.entity)),
+ urllib.parse.quote_plus(str(self.project)),
+ urllib.parse.quote_plus(str(self.id)),
+ ]
+
+ @property
+ def url(self):
+ """The URL of the sweep.
+
+ The sweep URL is generated from the entity, project, the term
+ "sweeps", and the sweep ID.run_id. For
+ SaaS users, it takes the form
+ of `https://wandb.ai/entity/project/sweeps/sweeps_ID`.
+ """
+ path = self.path
+ path.insert(2, "sweeps")
+ return self.client.app_url + "/".join(path)
+
+ @property
+ def name(self):
+ """The name of the sweep.
+
+ Returns the first name that exists in the following priority order:
+
+ 1. User-edited display name
+ 2. Name configured at creation time
+ 3. Sweep ID
+ """
+ return self._attrs.get("displayName") or self.config.get("name") or self.id
+
+ @classmethod
+ def get(
+ cls,
+ client: RetryingClient,
+ entity: str | None = None,
+ project: str | None = None,
+ sid: str | None = None,
+ order: str | None = None,
+ query: str | None = None,
+ **kwargs,
+ ):
+ """Execute a query against the cloud backend.
+
+ Args:
+ client: The client to use to execute the query.
+ entity: The entity (username or team) that owns the project.
+ project: The name of the project to fetch sweep from.
+ sid: The sweep ID to query.
+ order: The order in which the sweep's runs are returned.
+ query: The query to use to execute the query.
+ **kwargs: Additional keyword arguments to pass to the query.
+ """
+ if not order:
+ order = "+created_at"
+
+ if query is None:
+ query = cls.QUERY
+
+ variables = {
+ "entity": entity,
+ "project": project,
+ "name": sid,
+ }
+ variables.update(kwargs)
+
+ response = None
+ try:
+ response = client.execute(query, variable_values=variables)
+ except Exception:
+ # Don't handle exception, rely on legacy query
+ # TODO(gst): Implement updated introspection workaround
+ query = cls.LEGACY_QUERY
+ response = client.execute(query, variable_values=variables)
+
+ if (
+ not response
+ or not response.get("project")
+ or not response["project"].get("sweep")
+ ):
+ return None
+
+ sweep_response = response["project"]["sweep"]
+ sweep = cls(client, entity, project, sid, attrs=sweep_response)
+ sweep.runs = public.Runs(
+ client,
+ entity,
+ project,
+ order=order,
+ per_page=10,
+ filters={"$and": [{"sweep": sweep.id}]},
+ )
+
+ return sweep
+
+ def to_html(self, height=420, hidden=False):
+ """Generate HTML containing an iframe displaying this sweep."""
+ url = self.url + "?jupyter=true"
+ style = f"border:none;width:100%;height:{height}px;"
+ prefix = ""
+ if hidden:
+ style += "display:none;"
+ prefix = ipython.toggle_button("sweep")
+ return prefix + f""
+
+ def _repr_html_(self) -> str:
+ return self.to_html()
+
+ def __repr__(self):
+ return "".format(
+ "/".join(self.path), self._attrs.get("state", "Unknown State")
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/teams.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/teams.py
new file mode 100644
index 0000000000000000000000000000000000000000..efa7b65afbc23d0482a9437861bcd7f53278880a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/teams.py
@@ -0,0 +1,237 @@
+"""W&B Public API for managing teams and team members.
+
+This module provides classes for managing W&B teams and their members.
+
+Note:
+ This module is part of the W&B Public API and provides methods to manage
+ teams and their members. Team management operations require appropriate
+ permissions.
+"""
+
+from __future__ import annotations
+
+import requests
+from wandb_gql import gql
+
+from wandb.apis.attrs import Attrs
+
+
+class Member(Attrs):
+ """A member of a team.
+
+ Args:
+ client (`wandb.apis.internal.Api`): The client instance to use
+ team (str): The name of the team this member belongs to
+ attrs (dict): The member attributes
+ """
+
+ DELETE_MEMBER_MUTATION = gql(
+ """
+ mutation DeleteInvite($id: String, $entityName: String) {
+ deleteInvite(input: {id: $id, entityName: $entityName}) {
+ success
+ }
+ }
+ """
+ )
+
+ def __init__(self, client, team, attrs):
+ super().__init__(attrs)
+ self._client = client
+ self.team = team
+
+ def delete(self):
+ """Remove a member from a team.
+
+ Returns:
+ Boolean indicating success
+ """
+ try:
+ return self._client.execute(
+ self.DELETE_MEMBER_MUTATION, {"id": self.id, "entityName": self.team}
+ )["deleteInvite"]["success"]
+ except requests.exceptions.HTTPError:
+ return False
+
+ def __repr__(self):
+ return f""
+
+
+class Team(Attrs):
+ """A class that represents a W&B team.
+
+ This class provides methods to manage W&B teams, including creating teams,
+ inviting members, and managing service accounts. It inherits from Attrs
+ to handle team attributes.
+
+ Args:
+ client (`wandb.apis.public.Api`): The api instance to use
+ name (str): The name of the team
+ attrs (dict): Optional dictionary of team attributes
+
+ Note:
+ Team management requires appropriate permissions.
+ """
+
+ CREATE_TEAM_MUTATION = gql(
+ """
+ mutation CreateTeam($teamName: String!, $teamAdminUserName: String) {
+ createTeam(input: {teamName: $teamName, teamAdminUserName: $teamAdminUserName}) {
+ entity {
+ id
+ name
+ available
+ photoUrl
+ limits
+ }
+ }
+ }
+ """
+ )
+ CREATE_INVITE_MUTATION = gql(
+ """
+ mutation CreateInvite($entityName: String!, $email: String, $username: String, $admin: Boolean) {
+ createInvite(input: {entityName: $entityName, email: $email, username: $username, admin: $admin}) {
+ invite {
+ id
+ name
+ email
+ createdAt
+ toUser {
+ name
+ }
+ }
+ }
+ }
+ """
+ )
+ TEAM_QUERY = gql(
+ """
+ query Entity($name: String!) {
+ entity(name: $name) {
+ id
+ name
+ available
+ photoUrl
+ readOnly
+ readOnlyAdmin
+ isTeam
+ privateOnly
+ storageBytes
+ codeSavingEnabled
+ defaultAccess
+ isPaid
+ members {
+ id
+ admin
+ pending
+ email
+ username
+ name
+ photoUrl
+ accountType
+ apiKey
+ }
+ }
+ }
+ """
+ )
+ CREATE_SERVICE_ACCOUNT_MUTATION = gql(
+ """
+ mutation CreateServiceAccount($entityName: String!, $description: String!) {
+ createServiceAccount(
+ input: {description: $description, entityName: $entityName}
+ ) {
+ user {
+ id
+ }
+ }
+ }
+ """
+ )
+
+ def __init__(self, client, name, attrs=None):
+ super().__init__(attrs or {})
+ self._client = client
+ self.name = name
+ self.load()
+
+ @classmethod
+ def create(cls, api, team, admin_username=None):
+ """Create a new team.
+
+ Args:
+ api: (`Api`) The api instance to use
+ team: (str) The name of the team
+ admin_username: (str) optional username of the admin user of the team, defaults to the current user.
+
+ Returns:
+ A `Team` object
+ """
+ try:
+ api.client.execute(
+ cls.CREATE_TEAM_MUTATION,
+ {"teamName": team, "teamAdminUserName": admin_username},
+ )
+ except requests.exceptions.HTTPError:
+ pass
+ return Team(api.client, team)
+
+ def invite(self, username_or_email, admin=False):
+ """Invite a user to a team.
+
+ Args:
+ username_or_email: (str) The username or email address of the user
+ you want to invite.
+ admin: (bool) Whether to make this user a team admin.
+ Defaults to `False`.
+
+ Returns:
+ `True` on success, `False` if user was already invited or didn't exist.
+ """
+ variables = {"entityName": self.name, "admin": admin}
+ if "@" in username_or_email:
+ variables["email"] = username_or_email
+ else:
+ variables["username"] = username_or_email
+ try:
+ self._client.execute(self.CREATE_INVITE_MUTATION, variables)
+ except requests.exceptions.HTTPError:
+ return False
+ return True
+
+ def create_service_account(self, description):
+ """Create a service account for the team.
+
+ Args:
+ description: (str) A description for this service account
+
+ Returns:
+ The service account `Member` object, or None on failure
+ """
+ try:
+ self._client.execute(
+ self.CREATE_SERVICE_ACCOUNT_MUTATION,
+ {"description": description, "entityName": self.name},
+ )
+ self.load(True)
+ return self.members[-1]
+ except requests.exceptions.HTTPError:
+ return None
+
+ def load(self, force=False):
+ """Return members that belong to a team.
+
+
+ """
+ if force or not self._attrs:
+ response = self._client.execute(self.TEAM_QUERY, {"name": self.name})
+ self._attrs = response["entity"]
+ self._attrs["members"] = [
+ Member(self._client, self.name, member)
+ for member in self._attrs["members"]
+ ]
+ return self._attrs
+
+ def __repr__(self):
+ return f""
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/users.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/users.py
new file mode 100644
index 0000000000000000000000000000000000000000..44b9d870de67dcf95051051cec118ba0bdd65de2
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/users.py
@@ -0,0 +1,179 @@
+"""W&B Public API for managing users and API keys.
+
+This module provides classes for managing W&B users and their API keys.
+
+Note:
+ This module is part of the W&B Public API and provides methods to manage
+ users and their authentication. Some operations require admin privileges.
+"""
+
+from __future__ import annotations
+
+import requests
+from wandb_gql import gql
+
+import wandb
+from wandb.apis.attrs import Attrs
+
+
+class User(Attrs):
+ """A class representing a W&B user with authentication and management capabilities.
+
+ This class provides methods to manage W&B users, including creating users,
+ managing API keys, and accessing team memberships. It inherits from Attrs
+ to handle user attributes.
+
+ Args:
+ client: (`wandb.apis.internal.Api`) The client instance to use
+ attrs: (dict) The user attributes
+
+ Note:
+ Some operations require admin privileges
+ """
+
+ CREATE_USER_MUTATION = gql(
+ """
+ mutation CreateUserFromAdmin($email: String!, $admin: Boolean) {
+ createUser(input: {email: $email, admin: $admin}) {
+ user {
+ id
+ name
+ username
+ email
+ admin
+ }
+ }
+ }
+ """
+ )
+
+ DELETE_API_KEY_MUTATION = gql(
+ """
+ mutation DeleteApiKey($id: String!) {
+ deleteApiKey(input: {id: $id}) {
+ success
+ }
+ }
+ """
+ )
+ GENERATE_API_KEY_MUTATION = gql(
+ """
+ mutation GenerateApiKey($description: String) {
+ generateApiKey(input: {description: $description}) {
+ apiKey {
+ id
+ name
+ }
+ }
+ }
+ """
+ )
+
+ def __init__(self, client, attrs):
+ super().__init__(attrs)
+ self._client = client
+ self._user_api = None
+
+ @property
+ def user_api(self):
+ """An instance of the api using credentials from the user."""
+ if self._user_api is None and len(self.api_keys) > 0:
+ self._user_api = wandb.Api(api_key=self.api_keys[0])
+ return self._user_api
+
+ @classmethod
+ def create(cls, api, email, admin=False):
+ """Create a new user.
+
+ Args:
+ api (`Api`): The api instance to use
+ email (str): The name of the team
+ admin (bool): Whether this user should be a global instance admin
+
+ Returns:
+ A `User` object
+ """
+ res = api.client.execute(
+ cls.CREATE_USER_MUTATION,
+ {"email": email, "admin": admin},
+ )
+ return User(api.client, res["createUser"]["user"])
+
+ @property
+ def api_keys(self):
+ """List of API key names associated with the user.
+
+ Returns:
+ list[str]: Names of API keys associated with the user. Empty list if user
+ has no API keys or if API key data hasn't been loaded.
+ """
+ if self._attrs.get("apiKeys") is None:
+ return []
+ return [k["node"]["name"] for k in self._attrs["apiKeys"]["edges"]]
+
+ @property
+ def teams(self):
+ """List of team names that the user is a member of.
+
+ Returns:
+ list (list): Names of teams the user belongs to. Empty list if user has no
+ team memberships or if teams data hasn't been loaded.
+ """
+ if self._attrs.get("teams") is None:
+ return []
+ return [k["node"]["name"] for k in self._attrs["teams"]["edges"]]
+
+ def delete_api_key(self, api_key):
+ """Delete a user's api key.
+
+ Args:
+ api_key (str): The name of the API key to delete. This should be
+ one of the names returned by the `api_keys` property.
+
+ Returns:
+ Boolean indicating success
+
+ Raises:
+ ValueError if the api_key couldn't be found
+ """
+ idx = self.api_keys.index(api_key)
+ try:
+ self._client.execute(
+ self.DELETE_API_KEY_MUTATION,
+ {"id": self._attrs["apiKeys"]["edges"][idx]["node"]["id"]},
+ )
+ except requests.exceptions.HTTPError:
+ return False
+ return True
+
+ def generate_api_key(self, description=None):
+ """Generate a new api key.
+
+ Args:
+ description (str, optional): A description for the new API key. This can be
+ used to identify the purpose of the API key.
+
+ Returns:
+ The new api key, or None on failure
+ """
+ try:
+ # We must make this call using credentials from the original user
+ key = self.user_api.client.execute(
+ self.GENERATE_API_KEY_MUTATION, {"description": description}
+ )["generateApiKey"]["apiKey"]
+ self._attrs["apiKeys"]["edges"].append({"node": key})
+ return key["name"]
+ except (requests.exceptions.HTTPError, AttributeError):
+ return None
+
+ def __repr__(self):
+ if "email" in self._attrs:
+ return f""
+ elif "username" in self._attrs:
+ return f""
+ elif "id" in self._attrs:
+ return f""
+ elif "name" in self._attrs:
+ return f""
+ else:
+ return ""
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/utils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6abd302bcbfef4b64725700c7560b30029a1a93
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/public/utils.py
@@ -0,0 +1,211 @@
+from __future__ import annotations
+
+import re
+from enum import Enum
+from typing import Any, Iterable, Mapping
+from urllib.parse import urlparse
+
+from wandb_gql import gql
+from wandb_graphql.language import ast, visitor
+
+from wandb._iterutils import one
+from wandb.sdk.artifacts._validators import is_artifact_registry_project
+from wandb.sdk.internal.internal_api import Api as InternalApi
+
+
+def parse_s3_url_to_s3_uri(url) -> str:
+ """Convert an S3 HTTP(S) URL to an S3 URI.
+
+ Arguments:
+ url (str): The S3 URL to convert, in the format
+ 'http(s)://.s3..amazonaws.com/'.
+ or 'http(s)://.s3.amazonaws.com/'
+
+ Returns:
+ str: The corresponding S3 URI in the format 's3:///'.
+
+ Raises:
+ ValueError: If the provided URL is not a valid S3 URL.
+ """
+ # Regular expression to match S3 URL pattern
+ s3_pattern = r"^https?://.*s3.*amazonaws\.com.*"
+ parsed_url = urlparse(url)
+
+ # Check if it's an S3 URL
+ match = re.match(s3_pattern, parsed_url.geturl())
+ if not match:
+ raise ValueError("Invalid S3 URL")
+
+ # Extract bucket name and key
+ bucket_name, *_ = parsed_url.netloc.split(".")
+ key = parsed_url.path.lstrip("/")
+
+ # Construct the S3 URI
+ s3_uri = f"s3://{bucket_name}/{key}"
+
+ return s3_uri
+
+
+class PathType(Enum):
+ """We have lots of different paths users pass in to fetch artifacts, projects, etc.
+
+ This enum is used for specifying what format the path is in given a string path.
+ """
+
+ PROJECT = "PROJECT"
+ ARTIFACT = "ARTIFACT"
+
+
+def parse_org_from_registry_path(path: str, path_type: PathType) -> str:
+ """Parse the org from a registry path.
+
+ Essentially fetching the "entity" from the path but for Registries the entity is actually the org.
+
+ Args:
+ path (str): The path to parse. Can be a project path / or or an
+ artifact path like // or / or
+ path_type (PathType): The type of path to parse.
+ """
+ parts = path.split("/")
+ expected_parts = 3 if path_type == PathType.ARTIFACT else 2
+
+ if len(parts) >= expected_parts:
+ org, project = parts[:2]
+ if is_artifact_registry_project(project):
+ return org
+ return ""
+
+
+def fetch_org_from_settings_or_entity(
+ settings: dict, default_entity: str | None = None
+) -> str:
+ """Fetch the org from either the settings or deriving it from the entity.
+
+ Returns the org from the settings if available. If no org is passed in or set, the entity is used to fetch the org.
+
+ Args:
+ organization (str | None): The organization to fetch the org for.
+ settings (dict): The settings to fetch the org for.
+ default_entity (str | None): The default entity to fetch the org for.
+ """
+ if (organization := settings.get("organization")) is None:
+ # Fetch the org via the Entity. Won't work if default entity is a personal entity and belongs to multiple orgs
+ entity = settings.get("entity") or default_entity
+ if entity is None:
+ raise ValueError(
+ "No entity specified and can't fetch organization from the entity"
+ )
+ entity_orgs = InternalApi()._fetch_orgs_and_org_entities_from_entity(entity)
+ entity_org = one(
+ entity_orgs,
+ too_short=ValueError(
+ "No organizations found for entity. Please specify an organization in the settings."
+ ),
+ too_long=ValueError(
+ "Multiple organizations found for entity. Please specify an organization in the settings."
+ ),
+ )
+ organization = entity_org.display_name
+ return organization
+
+
+class _GQLCompatRewriter(visitor.Visitor):
+ """GraphQL AST visitor to rewrite queries/mutations to be compatible with older server versions."""
+
+ omit_variables: set[str]
+ omit_fragments: set[str]
+ omit_fields: set[str]
+ rename_fields: dict[str, str]
+
+ def __init__(
+ self,
+ omit_variables: Iterable[str] | None = None,
+ omit_fragments: Iterable[str] | None = None,
+ omit_fields: Iterable[str] | None = None,
+ rename_fields: Mapping[str, str] | None = None,
+ ):
+ self.omit_variables = set(omit_variables or ())
+ self.omit_fragments = set(omit_fragments or ())
+ self.omit_fields = set(omit_fields or ())
+ self.rename_fields = dict(rename_fields or {})
+
+ def enter_VariableDefinition(self, node: ast.VariableDefinition, *_, **__) -> Any: # noqa: N802
+ if node.variable.name.value in self.omit_variables:
+ return visitor.REMOVE
+
+ def enter_ObjectField(self, node: ast.ObjectField, *_, **__) -> Any: # noqa: N802
+ # For context, note that e.g.:
+ #
+ # {description: $description
+ # ...}
+ #
+ # Is parsed as:
+ #
+ # ObjectValue(fields=[
+ # ObjectField(name=Name(value='description'), value=Variable(name=Name(value='description'))),
+ # ...])
+ if (
+ isinstance(var := node.value, ast.Variable)
+ and var.name.value in self.omit_variables
+ ):
+ return visitor.REMOVE
+
+ def enter_Argument(self, node: ast.Argument, *_, **__) -> Any: # noqa: N802
+ if node.name.value in self.omit_variables:
+ return visitor.REMOVE
+
+ def enter_FragmentDefinition(self, node: ast.FragmentDefinition, *_, **__) -> Any: # noqa: N802
+ if node.name.value in self.omit_fragments:
+ return visitor.REMOVE
+
+ def enter_FragmentSpread(self, node: ast.FragmentSpread, *_, **__) -> Any: # noqa: N802
+ if node.name.value in self.omit_fragments:
+ return visitor.REMOVE
+
+ def enter_Field(self, node: ast.Field, *_, **__) -> Any: # noqa: N802
+ if node.name.value in self.omit_fields:
+ return visitor.REMOVE
+ if new_name := self.rename_fields.get(node.name.value):
+ node.name.value = new_name
+ return node
+
+ def leave_Field(self, node: ast.Field, *_, **__) -> Any: # noqa: N802
+ # If the field had a selection set, but now it's empty, remove the field entirely
+ if (node.selection_set is not None) and (not node.selection_set.selections):
+ return visitor.REMOVE
+
+
+def gql_compat(
+ request_string: str,
+ omit_variables: Iterable[str] | None = None,
+ omit_fragments: Iterable[str] | None = None,
+ omit_fields: Iterable[str] | None = None,
+ rename_fields: Mapping[str, str] | None = None,
+) -> ast.Document:
+ """Rewrite a GraphQL request string to ensure compatibility with older server versions.
+
+ Args:
+ request_string (str): The GraphQL request string to rewrite.
+ omit_variables (Iterable[str] | None): Names of variables to remove from the request string.
+ omit_fragments (Iterable[str] | None): Names of fragments to remove from the request string.
+ omit_fields (Iterable[str] | None): Names of fields to remove from the request string.
+ rename_fields (Mapping[str, str] | None):
+ A mapping of fields to rename in the request string, given as `{old_name -> new_name}`.
+
+ Returns:
+ str: Modified GraphQL request string with fragments on omitted types removed.
+ """
+ # Parse the request into a GraphQL AST
+ doc = gql(request_string)
+
+ if not (omit_variables or omit_fragments or omit_fields or rename_fields):
+ return doc
+
+ # Visit the AST with our visitor to filter out unwanted fragments
+ rewriter = _GQLCompatRewriter(
+ omit_variables=omit_variables,
+ omit_fragments=omit_fragments,
+ omit_fields=omit_fields,
+ rename_fields=rename_fields,
+ )
+ return visitor.visit(doc, rewriter)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/reports/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/reports/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d2b9ad9385524f2b868e498d3030de028fac546
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/reports/__init__.py
@@ -0,0 +1 @@
+from .v2 import * # noqa: F403
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/reports/v1/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/reports/v1/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bd41baac9f44dd1f7dc5145779d33fe95d10763
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/reports/v1/__init__.py
@@ -0,0 +1,8 @@
+import wandb
+
+try:
+ from wandb_workspaces.reports.v1 import * # noqa: F403
+except ImportError:
+ wandb.termerror(
+ "Failed to import wandb_workspaces. To edit reports programmatically, please install it using `pip install wandb[workspaces]`."
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/reports/v2/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/reports/v2/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..532129620940c7deb87ae483a08059cb792d15f4
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/reports/v2/__init__.py
@@ -0,0 +1,8 @@
+import wandb
+
+try:
+ from wandb_workspaces.reports.v2 import * # noqa: F403
+except ImportError:
+ wandb.termerror(
+ "Failed to import wandb_workspaces. To edit reports programmatically, please install it using `pip install wandb[workspaces]`."
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/workspaces/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/workspaces/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..269a35473d08b01200c593d2c8958c85349a0749
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/apis/workspaces/__init__.py
@@ -0,0 +1,8 @@
+import wandb
+
+try:
+ from wandb_workspaces.workspaces import * # noqa: F403
+except ImportError:
+ wandb.termerror(
+ "Failed to import wandb_workspaces. To edit workspaces programmatically, please install it using `pip install wandb[workspaces]`."
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a95cdd8ed5027012d90e141b2343fab6de2f811
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/__init__.py
@@ -0,0 +1,73 @@
+import wandb
+from wandb._pydantic import IS_PYDANTIC_V2
+
+from .actions import ActionType, DoNothing, SendNotification, SendWebhook
+from .automations import Automation, NewAutomation
+from .events import (
+ ArtifactEvent,
+ EventType,
+ MetricChangeFilter,
+ MetricThresholdFilter,
+ OnAddArtifactAlias,
+ OnCreateArtifact,
+ OnLinkArtifact,
+ OnRunMetric,
+ RunEvent,
+)
+from .integrations import Integration, SlackIntegration, WebhookIntegration
+from .scopes import ArtifactCollectionScope, ProjectScope, ScopeType
+
+# ----------------------------------------------------------------------------
+# WARNINGS on import
+if not IS_PYDANTIC_V2:
+ # Raises an error in Pydantic v1 environments, where the Automations API
+ # has not been tested and is unlikely to work as expected.
+ #
+ # Remove this when we either:
+ # - Drop support for Pydantic v1
+ # - Are able to implement (limited) Pydantic v1 support
+ raise ImportError(
+ "The W&B Automations API requires Pydantic v2. "
+ "We recommend upgrading `pydantic` to use this feature."
+ )
+
+else:
+ # If Pydantic v2 is available, we can use the full Automations API
+ # but communicate to users that the API is still experimental and
+ # may change rapidly.
+ wandb.termwarn(
+ "The W&B Automations API is experimental and the implementation is subject to change."
+ "Review the release notes before upgrading. We recommend pinning your "
+ f"package version to `{wandb.__package__}=={wandb.__version__}` to reduce the risk of disruption.",
+ repeat=False,
+ )
+# ----------------------------------------------------------------------------
+
+__all__ = [
+ # Scopes
+ "ScopeType", # doc:exclude
+ "ArtifactCollectionScope", # doc:exclude
+ "ProjectScope", # doc:exclude
+ # Events
+ "EventType", # doc:exclude
+ "OnAddArtifactAlias",
+ "OnCreateArtifact",
+ "OnLinkArtifact",
+ "OnRunMetric",
+ "ArtifactEvent", # doc:exclude
+ "RunEvent", # doc:exclude
+ "MetricThresholdFilter",
+ "MetricChangeFilter",
+ # Actions
+ "ActionType", # doc:exclude
+ "SendNotification",
+ "SendWebhook",
+ "DoNothing",
+ # Automations
+ "Automation",
+ "NewAutomation",
+ # Integrations
+ "Integration", # doc:exclude
+ "SlackIntegration", # doc:exclude
+ "WebhookIntegration", # doc:exclude
+]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_filters/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_filters/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..56d551d4ed507da432151e8eb90167495fdb5acf
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_filters/__init__.py
@@ -0,0 +1,40 @@
+from .expressions import FilterExpr, MongoLikeFilter
+from .operators import (
+ And,
+ Contains,
+ Eq,
+ Exists,
+ Gt,
+ Gte,
+ In,
+ Lt,
+ Lte,
+ Ne,
+ Nor,
+ Not,
+ NotIn,
+ Op,
+ Or,
+ Regex,
+)
+
+__all__ = [
+ "And",
+ "Or",
+ "Nor",
+ "Not",
+ "Op",
+ "Gt",
+ "Lt",
+ "Gte",
+ "Lte",
+ "Eq",
+ "Ne",
+ "In",
+ "NotIn",
+ "Contains",
+ "Exists",
+ "Regex",
+ "FilterExpr",
+ "MongoLikeFilter",
+]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_filters/expressions.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_filters/expressions.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9c9fa254d67ccbc37efc983cbad2bab54ab936c
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_filters/expressions.py
@@ -0,0 +1,182 @@
+"""Pydantic-compatible representations of MongoDB expressions."""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from typing import Any, Union
+
+from pydantic import ConfigDict, model_serializer
+from typing_extensions import Self, TypeAlias, get_args
+
+from wandb._pydantic import CompatBaseModel, model_validator
+from wandb._strutils import nameof
+
+from .operators import (
+ Contains,
+ Eq,
+ Exists,
+ Gt,
+ Gte,
+ In,
+ Lt,
+ Lte,
+ Ne,
+ NotIn,
+ Op,
+ Regex,
+ RichReprResult,
+ Scalar,
+ ScalarTypes,
+ SupportsLogicalOpSyntax,
+)
+
+
+class FilterableField:
+ """A descriptor that can be used to define a "filterable" field on a class.
+
+ Internal helper to support syntactic sugar for defining event filters.
+ """
+
+ _python_name: str #: The name of the field this descriptor was assigned to in the Python class.
+ _server_name: str | None #: If set, the actual server-side field name to filter on.
+
+ def __init__(self, server_name: str | None = None):
+ self._server_name = server_name
+
+ def __set_name__(self, owner: type, name: str) -> None:
+ self._python_name = name
+
+ def __get__(self, obj: Any, objtype: type) -> Self:
+ # By default, if we didn't explicitly provide a backend name for
+ # filtering, assume the field has the same name in the backend as
+ # the python attribute.
+ return self
+
+ @property
+ def _name(self) -> str:
+ return self._server_name or self._python_name
+
+ def __str__(self) -> str:
+ return self._name
+
+ def __repr__(self) -> str:
+ return f"{nameof(type(self))}({self._name!r})"
+
+ # Methods to define filter expressions through chaining
+ def matches_regex(self, pattern: str) -> FilterExpr:
+ return FilterExpr(field=self._name, op=Regex(regex_=pattern))
+
+ def contains(self, text: str) -> FilterExpr:
+ return FilterExpr(field=self._name, op=Contains(contains_=text))
+
+ def exists(self, exists: bool = True) -> FilterExpr:
+ return FilterExpr(field=self._name, op=Exists(exists_=exists))
+
+ def lt(self, value: Scalar) -> FilterExpr:
+ return FilterExpr(field=self._name, op=Lt(lt_=value))
+
+ def gt(self, value: Scalar) -> FilterExpr:
+ return FilterExpr(field=self._name, op=Gt(gt_=value))
+
+ def lte(self, value: Scalar) -> FilterExpr:
+ return FilterExpr(field=self._name, op=Lte(lte_=value))
+
+ def gte(self, value: Scalar) -> FilterExpr:
+ return FilterExpr(field=self._name, op=Gte(gte_=value))
+
+ def ne(self, value: Scalar) -> FilterExpr:
+ return FilterExpr(field=self._name, op=Ne(ne_=value))
+
+ def eq(self, value: Scalar) -> FilterExpr:
+ return FilterExpr(field=self._name, op=Eq(eq_=value))
+
+ def in_(self, values: Iterable[Scalar]) -> FilterExpr:
+ return FilterExpr(field=self._name, op=In(in_=values))
+
+ def not_in(self, values: Iterable[Scalar]) -> FilterExpr:
+ return FilterExpr(field=self._name, op=NotIn(nin_=values))
+
+ # Override the default behavior of comparison operators: <, >=, ==, etc
+ def __lt__(self, other: Any) -> FilterExpr:
+ if isinstance(other, ScalarTypes):
+ return self.lt(other) # type: ignore[arg-type]
+ raise TypeError(f"Invalid operand type in filter expression: {type(other)!r}")
+
+ def __gt__(self, other: Any) -> FilterExpr:
+ if isinstance(other, ScalarTypes):
+ return self.gt(other) # type: ignore[arg-type]
+ raise TypeError(f"Invalid operand type in filter expression: {type(other)!r}")
+
+ def __le__(self, other: Any) -> FilterExpr:
+ if isinstance(other, ScalarTypes):
+ return self.lte(other) # type: ignore[arg-type]
+ raise TypeError(f"Invalid operand type in filter expression: {type(other)!r}")
+
+ def __ge__(self, other: Any) -> FilterExpr:
+ if isinstance(other, ScalarTypes):
+ return self.gte(other) # type: ignore[arg-type]
+ raise TypeError(f"Invalid operand type in filter expression: {type(other)!r}")
+
+ # Operator behavior is intentionally overridden to allow defining
+ # filter expressions like `field == "value"`. See similar overrides
+ # of built-in dunder methods in sqlalchemy, polars, pandas, numpy, etc.
+ #
+ # sqlalchemy example for illustrative purposes:
+ # https://github.com/sqlalchemy/sqlalchemy/blob/f21ae633486380a26dc0b67b70ae1c0efc6b4dc4/lib/sqlalchemy/orm/descriptor_props.py#L808-L812
+ def __eq__(self, other: Any) -> FilterExpr:
+ if isinstance(other, ScalarTypes):
+ return self.eq(other) # type: ignore[arg-type]
+ raise TypeError(f"Invalid operand type in filter expression: {type(other)!r}")
+
+ def __ne__(self, other: Any) -> FilterExpr:
+ if isinstance(other, ScalarTypes):
+ return self.ne(other) # type: ignore[arg-type]
+ raise TypeError(f"Invalid operand type in filter expression: {type(other)!r}")
+
+
+# ------------------------------------------------------------------------------
+class FilterExpr(CompatBaseModel, SupportsLogicalOpSyntax):
+ """A MongoDB filter expression on a specific field."""
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ field: str
+ op: Op
+
+ def __repr__(self) -> str:
+ return f"{nameof(type(self))}({self.field!s}: {self.op!r})"
+
+ def __rich_repr__(self) -> RichReprResult:
+ # https://rich.readthedocs.io/en/stable/pretty.html
+ yield self.field, self.op
+
+ @model_validator(mode="before")
+ @classmethod
+ def _validate(cls, data: Any) -> Any:
+ """Parse a MongoDB dict representation of the filter expression."""
+ if (
+ isinstance(data, dict)
+ and len(data) == 1
+ and not any(key.startswith("$") for key in data)
+ ):
+ # This looks like a MongoDB filter dict. E.g.:
+ # - in: `{"display_name": {"$contains": "my-run"}}`
+ # - out: `FilterExpr(field="display_name", op=Contains(contains_="my-run"))`
+ ((field, op),) = data.items()
+ return {"field": field, "op": op}
+ return data
+
+ @model_serializer(mode="plain")
+ def _serialize(self) -> dict[str, Any]:
+ """Return a MongoDB dict representation of the expression."""
+ from pydantic_core import to_jsonable_python # Only valid in pydantic v2
+
+ return {self.field: to_jsonable_python(self.op, by_alias=True, round_trip=True)}
+
+
+# for type annotations
+MongoLikeFilter: TypeAlias = Union[Op, FilterExpr]
+# for runtime type checks
+MongoLikeFilterTypes: tuple[type, ...] = get_args(MongoLikeFilter)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_filters/operators.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_filters/operators.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d85846c718b7a21a95f16b5f3f749b3a19067bd
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_filters/operators.py
@@ -0,0 +1,259 @@
+"""Types that represent operators in MongoDB filter expressions."""
+
+from __future__ import annotations
+
+from typing import Any, Dict, Iterable, Tuple, TypeVar, Union
+
+from pydantic import ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr
+from typing_extensions import TypeAlias, get_args
+
+from wandb._pydantic import GQLBase
+from wandb._strutils import nameof
+
+# for type annotations
+Scalar = Union[StrictStr, StrictInt, StrictFloat, StrictBool]
+# for runtime type checks
+ScalarTypes: tuple[type, ...] = tuple(t.__origin__ for t in get_args(Scalar))
+
+# See: https://rich.readthedocs.io/en/stable/pretty.html#rich-repr-protocol
+RichReprResult: TypeAlias = Iterable[
+ Union[
+ Any,
+ Tuple[Any],
+ Tuple[str, Any],
+ Tuple[str, Any, Any],
+ ]
+]
+
+T = TypeVar("T")
+TupleOf: TypeAlias = Tuple[T, ...]
+
+
+# NOTE: Wherever class descriptions that are not docstrings, this is deliberate.
+# This is done to ensure the descriptions are omitted from generated API docs.
+
+
+# Mixin to support syntactic sugar for MongoDB expressions with (bitwise) logical operators,
+# e.g. `a | b` -> `{"$or": [a, b]}` or `~a` -> `{"$not": a}`.
+class SupportsLogicalOpSyntax:
+ def __or__(self, other: Any) -> Or:
+ """Syntactic sugar for: `a | b` -> `Or(a, b)`."""
+ return Or(or_=[self, other])
+
+ def __and__(self, other: Any) -> And:
+ """Syntactic sugar for: `a & b` -> `And(a, b)`."""
+ from .expressions import FilterExpr
+
+ if isinstance(other, (BaseOp, FilterExpr)):
+ return And(and_=[self, other])
+ return NotImplemented
+
+ def __invert__(self) -> Not:
+ """Syntactic sugar for: `~a` -> `Not(a)`."""
+ return Not(not_=self)
+
+
+# Base class for parsed MongoDB filter/query operators, e.g. `{"$and": [...]}`.
+class BaseOp(GQLBase, SupportsLogicalOpSyntax):
+ model_config = ConfigDict(
+ extra="forbid",
+ frozen=True, # Make pseudo-immutable for easier comparison and hashing
+ )
+
+ def __repr__(self) -> str:
+ # Display operand as a positional arg
+ values_repr = ", ".join(map(repr, self.model_dump().values()))
+ return f"{nameof(type(self))}({values_repr})"
+
+ def __rich_repr__(self) -> RichReprResult:
+ # Display field values as positional args:
+ # https://rich.readthedocs.io/en/stable/pretty.html
+ yield from ((None, v) for v in self.model_dump().values())
+
+
+# Logical operator(s)
+# https://www.mongodb.com/docs/manual/reference/operator/query/and/
+# https://www.mongodb.com/docs/manual/reference/operator/query/or/
+# https://www.mongodb.com/docs/manual/reference/operator/query/nor/
+# https://www.mongodb.com/docs/manual/reference/operator/query/not/
+class And(BaseOp):
+ and_: TupleOf[Any] = Field(default=(), alias="$and")
+
+
+class Or(BaseOp):
+ or_: TupleOf[Any] = Field(default=(), alias="$or")
+
+ def __invert__(self) -> Nor:
+ """Syntactic sugar for: `~Or(a, b)` -> `Nor(a, b)`."""
+ return Nor(nor_=self.or_)
+
+
+class Nor(BaseOp):
+ nor_: TupleOf[Any] = Field(default=(), alias="$nor")
+
+ def __invert__(self) -> Or:
+ """Syntactic sugar for: `~Nor(a, b)` -> `Or(a, b)`."""
+ return Or(or_=self.nor_)
+
+
+class Not(BaseOp):
+ not_: Any = Field(alias="$not")
+
+ def __invert__(self) -> Any:
+ """Syntactic sugar for: `~Not(a)` -> `a`."""
+ return self.not_
+
+
+# Comparison operator(s)
+# https://www.mongodb.com/docs/manual/reference/operator/query/lt/
+# https://www.mongodb.com/docs/manual/reference/operator/query/gt/
+# https://www.mongodb.com/docs/manual/reference/operator/query/lte/
+# https://www.mongodb.com/docs/manual/reference/operator/query/gte/
+# https://www.mongodb.com/docs/manual/reference/operator/query/eq/
+# https://www.mongodb.com/docs/manual/reference/operator/query/ne/
+# https://www.mongodb.com/docs/manual/reference/operator/query/in/
+# https://www.mongodb.com/docs/manual/reference/operator/query/nin/
+class Lt(BaseOp):
+ lt_: Scalar = Field(alias="$lt")
+
+ def __invert__(self) -> Gte:
+ """Syntactic sugar for: `~Lt(a)` -> `Gte(a)`."""
+ return Gte(gte_=self.lt_)
+
+
+class Gt(BaseOp):
+ gt_: Scalar = Field(alias="$gt")
+
+ def __invert__(self) -> Lte:
+ """Syntactic sugar for: `~Gt(a)` -> `Lte(a)`."""
+ return Lte(lte_=self.gt_)
+
+
+class Lte(BaseOp):
+ lte_: Scalar = Field(alias="$lte")
+
+ def __invert__(self) -> Gt:
+ """Syntactic sugar for: `~Lte(a)` -> `Gt(a)`."""
+ return Gt(gt_=self.lte_)
+
+
+class Gte(BaseOp):
+ gte_: Scalar = Field(alias="$gte")
+
+ def __invert__(self) -> Lt:
+ """Syntactic sugar for: `~Gte(a)` -> `Lt(a)`."""
+ return Lt(lt_=self.gte_)
+
+
+class Eq(BaseOp):
+ eq_: Scalar = Field(alias="$eq")
+
+ def __invert__(self) -> Ne:
+ """Syntactic sugar for: `~Eq(a)` -> `Ne(a)`."""
+ return Ne(ne_=self.eq_)
+
+
+class Ne(BaseOp):
+ ne_: Scalar = Field(alias="$ne")
+
+ def __invert__(self) -> Eq:
+ """Syntactic sugar for: `~Ne(a)` -> `Eq(a)`."""
+ return Eq(eq_=self.ne_)
+
+
+class In(BaseOp):
+ in_: TupleOf[Scalar] = Field(default=(), alias="$in")
+
+ def __invert__(self) -> NotIn:
+ """Syntactic sugar for: `~In(a)` -> `NotIn(a)`."""
+ return NotIn(nin_=self.in_)
+
+
+class NotIn(BaseOp):
+ nin_: TupleOf[Scalar] = Field(default=(), alias="$nin")
+
+ def __invert__(self) -> In:
+ """Syntactic sugar for: `~NotIn(a)` -> `In(a)`."""
+ return In(in_=self.nin_)
+
+
+# Element operator(s)
+# https://www.mongodb.com/docs/manual/reference/operator/query/exists/
+class Exists(BaseOp):
+ exists_: bool = Field(alias="$exists")
+
+
+# Evaluation operator(s)
+# https://www.mongodb.com/docs/manual/reference/operator/query/regex/
+#
+# Note: "$contains" is NOT a formal MongoDB operator, but the backend recognizes and
+# executes it as a substring-match filter.
+class Regex(BaseOp):
+ regex_: str = Field(alias="$regex") #: The regex expression to match against.
+
+
+class Contains(BaseOp):
+ contains_: str = Field(alias="$contains") #: The substring to match against.
+
+
+And.model_rebuild()
+Or.model_rebuild()
+Not.model_rebuild()
+Lt.model_rebuild()
+Gt.model_rebuild()
+Lte.model_rebuild()
+Gte.model_rebuild()
+Eq.model_rebuild()
+Ne.model_rebuild()
+In.model_rebuild()
+NotIn.model_rebuild()
+Exists.model_rebuild()
+Regex.model_rebuild()
+Contains.model_rebuild()
+
+
+# ------------------------------------------------------------------------------
+# Convenience helpers, constants, and utils for supported MongoDB operators
+# ------------------------------------------------------------------------------
+KEY_TO_OP: dict[str, type[BaseOp]] = {
+ "$and": And,
+ "$or": Or,
+ "$nor": Nor,
+ "$not": Not,
+ "$lt": Lt,
+ "$gt": Gt,
+ "$lte": Lte,
+ "$gte": Gte,
+ "$eq": Eq,
+ "$ne": Ne,
+ "$in": In,
+ "$nin": NotIn,
+ "$exists": Exists,
+ "$regex": Regex,
+ "$contains": Contains,
+}
+
+
+KnownOp = Union[
+ And,
+ Or,
+ Nor,
+ Not,
+ Lt,
+ Gt,
+ Lte,
+ Gte,
+ Eq,
+ Ne,
+ In,
+ NotIn,
+ Exists,
+ Regex,
+ Contains,
+]
+UnknownOp = Dict[str, Any]
+
+# for type annotations
+Op = Union[KnownOp, UnknownOp]
+# for runtime type checks
+OpTypes: tuple[type, ...] = (*get_args(KnownOp), dict)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_filters/run_metrics.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_filters/run_metrics.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ddeb46bb7bf418138107e03a9c39051c471650c
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_filters/run_metrics.py
@@ -0,0 +1,330 @@
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING, Any, Final, Literal, Optional, Union, overload
+
+from pydantic import (
+ Field,
+ PositiveFloat,
+ PositiveInt,
+ StrictFloat,
+ StrictInt,
+ field_validator,
+)
+from typing_extensions import Annotated, TypeAlias, override
+
+from wandb._pydantic import GQLBase
+from wandb.automations._validators import LenientStrEnum
+
+from .expressions import FilterExpr
+from .operators import BaseOp, RichReprResult
+
+if TYPE_CHECKING:
+ from wandb.automations.events import RunMetricFilter
+
+# Maps MongoDB comparison operators -> Python literal (str) representations
+MONGO2PY_OPS: Final[dict[str, str]] = {
+ "$eq": "==",
+ "$ne": "!=",
+ "$gt": ">",
+ "$lt": "<",
+ "$gte": ">=",
+ "$lte": "<=",
+}
+# Reverse mapping from Python literal (str) -> MongoDB operator key
+PY2MONGO_OPS: Final[dict[str, str]] = {v: k for k, v in MONGO2PY_OPS.items()}
+
+# Type hint for positive numbers (int or float)
+PosNum: TypeAlias = Union[PositiveInt, PositiveFloat]
+
+
+class Agg(LenientStrEnum): # from: Aggregation
+ """Supported run metric aggregation operations."""
+
+ MAX = "MAX"
+ MIN = "MIN"
+ AVERAGE = "AVERAGE"
+
+ # Shorter aliases for convenience
+ AVG = AVERAGE
+
+
+class ChangeType(LenientStrEnum): # from: RunMetricChangeType
+ """Describes the metric change as absolute (arithmetic difference) or relative (decimal percentage)."""
+
+ ABSOLUTE = "ABSOLUTE"
+ RELATIVE = "RELATIVE"
+
+ # Shorter aliases for convenience
+ ABS = ABSOLUTE
+ REL = RELATIVE
+
+
+class ChangeDir(LenientStrEnum): # from: RunMetricChangeDirection
+ """Describes the direction of the metric change."""
+
+ INCREASE = "INCREASE"
+ DECREASE = "DECREASE"
+ ANY = "ANY"
+
+ # Shorter aliases for convenience
+ INC = INCREASE
+ DEC = DECREASE
+
+
+class BaseMetricFilter(GQLBase, ABC, extra="forbid"):
+ name: str
+ """Name of the observed metric."""
+
+ agg: Optional[Agg]
+ """Aggregate operation, if any, to apply over the window size."""
+
+ window: PositiveInt
+ """Size of the window over which the metric is aggregated (ignored if `agg is None`)."""
+
+ # ------------------------------------------------------------------------------
+ cmp: Optional[str]
+ """Comparison between the metric expression (left) vs. the threshold or target value (right)."""
+
+ # ------------------------------------------------------------------------------
+ threshold: Union[StrictInt, StrictFloat]
+ """Threshold value to compare against."""
+
+ def __and__(self, other: Any) -> RunMetricFilter:
+ """Implements `(metric_filter & run_filter) -> RunMetricFilter`."""
+ from wandb.automations.events import RunMetricFilter
+
+ if isinstance(run_filter := other, (BaseOp, FilterExpr)):
+ # Assume `other` is a run filter, and we are building a RunMetricEvent.
+ # For the metric filter, delegate to the inner validator(s) to further wrap/nest as appropriate.
+ return RunMetricFilter(run=run_filter, metric=self)
+ return NotImplemented
+
+ def __rand__(self, other: BaseOp | FilterExpr) -> RunMetricFilter:
+ """Ensures `&` is commutative: `(run_filter & metric_filter) == (metric_filter & run_filter)`."""
+ return self.__and__(other)
+
+ @abstractmethod
+ def __repr__(self) -> str:
+ """The text representation of the metric filter."""
+ raise NotImplementedError
+
+ @override
+ def __rich_repr__(self) -> RichReprResult:
+ """The representation of the metric filter when using `rich` for pretty-printing."""
+ # See: https://rich.readthedocs.io/en/stable/pretty.html#rich-repr-protocol
+ yield None, repr(self)
+
+
+class MetricThresholdFilter(BaseMetricFilter): # from: RunMetricThresholdFilter
+ """Defines a filter that compares a run metric against a user-defined threshold value."""
+
+ name: str
+ agg: Annotated[Optional[Agg], Field(alias="agg_op")] = None
+ window: Annotated[PositiveInt, Field(alias="window_size")] = 1
+
+ cmp: Annotated[Literal["$gte", "$gt", "$lt", "$lte"], Field(alias="cmp_op")]
+ """Comparison operator used to compare the metric value (left) vs. the threshold value (right)."""
+
+ threshold: Union[StrictInt, StrictFloat]
+
+ @field_validator("cmp", mode="before")
+ def _validate_cmp(cls, v: Any) -> Any:
+ # Be helpful: e.g. ">" -> "$gt"
+ return PY2MONGO_OPS.get(v.strip(), v) if isinstance(v, str) else v
+
+ def __repr__(self) -> str:
+ metric = f"{self.agg.value}({self.name})" if self.agg else self.name
+ op = MONGO2PY_OPS.get(self.cmp, self.cmp)
+ return repr(rf"{metric} {op} {self.threshold}")
+
+
+class MetricChangeFilter(BaseMetricFilter): # from: RunMetricChangeFilter
+ """Defines a filter that compares a change in a run metric against a user-defined threshold.
+
+ The change is calculated over "tumbling" windows, i.e. the difference
+ between the current window and the non-overlapping prior window.
+ """
+
+ name: str
+ agg: Annotated[Optional[Agg], Field(alias="agg_op")] = None
+ window: Annotated[PositiveInt, Field(alias="current_window_size")] = 1
+
+ # `prior_window` is only for `RUN_METRIC_CHANGE` events
+ prior_window: Annotated[
+ PositiveInt,
+ # By default, set `window -> prior_window` if the latter wasn't provided.
+ Field(alias="prior_window_size", default_factory=lambda data: data["window"]),
+ ]
+ """Size of the prior window over which the metric is aggregated (ignored if `agg is None`).
+
+ If omitted, defaults to the size of the current window.
+ """
+
+ # ------------------------------------------------------------------------------
+ # NOTE:
+ # - The "comparison" operator isn't actually part of the backend schema,
+ # but it's defined here for consistency -- and ignored otherwise.
+ # - In the backend, it's effectively "$gte" or "$lte", depending on the sign
+ # (change_dir), though again, this is not explicit in the schema.
+ cmp: Annotated[None, Field(frozen=True, exclude=True, repr=False)] = None
+ """Ignored."""
+
+ # ------------------------------------------------------------------------------
+ change_type: Annotated[ChangeType, Field(alias="change_type")]
+ change_dir: Annotated[ChangeDir, Field(alias="change_dir")]
+ threshold: Annotated[PosNum, Field(alias="change_amount")]
+
+ def __repr__(self) -> str:
+ metric = f"{self.agg.value}({self.name})" if self.agg else self.name
+ verb = (
+ "changes"
+ if (self.change_dir is ChangeDir.ANY)
+ else f"{self.change_dir.value.lower()}s"
+ )
+
+ fmt_spec = ".2%" if (self.change_type is ChangeType.REL) else ""
+ amt = f"{self.threshold:{fmt_spec}}"
+ return repr(rf"{metric} {verb} {amt}")
+
+
+class BaseMetricOperand(GQLBase, extra="forbid"):
+ def gt(self, value: int | float, /) -> MetricThresholdFilter:
+ """Defines a `MetricThresholdFilter` that observes for `metric_expr > threshold`."""
+ return self > value
+
+ def lt(self, value: int | float, /) -> MetricThresholdFilter:
+ """Defines a `MetricThresholdFilter` that observes for `metric_expr < threshold`."""
+ return self < value
+
+ def gte(self, value: int | float, /) -> MetricThresholdFilter:
+ """Defines a `MetricThresholdFilter` that observes for `metric_expr >= threshold`."""
+ return self >= value
+
+ def lte(self, value: int | float, /) -> MetricThresholdFilter:
+ """Defines a `MetricThresholdFilter` that observes for `metric_expr <= threshold`."""
+ return self <= value
+
+ # Overloads to implement:
+ # - `(metric_operand > threshold) -> MetricThresholdFilter`
+ # - `(metric_operand < threshold) -> MetricThresholdFilter`
+ # - `(metric_operand >= threshold) -> MetricThresholdFilter`
+ # - `(metric_operand <= threshold) -> MetricThresholdFilter`
+ def __gt__(self, other: Any) -> MetricThresholdFilter:
+ if isinstance(other, (int, float)):
+ return MetricThresholdFilter(**dict(self), cmp="$gt", threshold=other)
+ return NotImplemented
+
+ def __lt__(self, other: Any) -> MetricThresholdFilter:
+ if isinstance(other, (int, float)):
+ return MetricThresholdFilter(**dict(self), cmp="$lt", threshold=other)
+ return NotImplemented
+
+ def __ge__(self, other: Any) -> MetricThresholdFilter:
+ if isinstance(other, (int, float)):
+ return MetricThresholdFilter(**dict(self), cmp="$gte", threshold=other)
+ return NotImplemented
+
+ def __le__(self, other: Any) -> MetricThresholdFilter:
+ if isinstance(other, (int, float)):
+ return MetricThresholdFilter(**dict(self), cmp="$lte", threshold=other)
+ return NotImplemented
+
+ @overload
+ def changes_by(self, *, diff: PosNum, frac: None) -> MetricChangeFilter: ...
+ @overload
+ def changes_by(self, *, diff: None, frac: PosNum) -> MetricChangeFilter: ...
+ @overload # NOTE: This overload is for internal use only.
+ def changes_by(
+ self, *, diff: PosNum | None, frac: PosNum | None, _dir: ChangeDir
+ ) -> MetricChangeFilter: ...
+ def changes_by(
+ self,
+ *,
+ diff: PosNum | None = None,
+ frac: PosNum | None = None,
+ _dir: ChangeDir = ChangeDir.ANY,
+ ) -> MetricChangeFilter:
+ """Defines a filter that observes for any change (increase OR decrease) in a run metric.
+
+ Exactly one of the keyword arguments `frac` or `diff` must be provided.
+
+ Args:
+ diff:
+ If given, the arithmetic difference that must be observed
+ in the metric. Must be a positive number.
+ frac:
+ If given, the fractional (relative) change that must be observed
+ in the metric. Must be a positive number. E.g. `frac=0.1`
+ denotes a 10% relative increase OR decrease.
+ """
+ # Enforce mutually exclusive keyword args
+ if (frac is None) is (diff is None):
+ raise ValueError("Must provide exactly one of `frac` or `diff`")
+
+ # Enforce positive values
+ if (frac is not None) and (frac <= 0):
+ raise ValueError(f"Expected positive quantity, got: {frac=}")
+ if (diff is not None) and (diff <= 0):
+ raise ValueError(f"Expected positive quantity, got: {diff=}")
+
+ if diff is None:
+ change_kws = dict(change_type=ChangeType.REL, threshold=frac)
+ return MetricChangeFilter(**dict(self), change_dir=_dir, **change_kws)
+ else:
+ change_kws = dict(change_type=ChangeType.ABS, threshold=diff)
+ return MetricChangeFilter(**dict(self), change_dir=_dir, **change_kws)
+
+ @overload
+ def increases_by(self, *, diff: PosNum, frac: None) -> MetricChangeFilter: ...
+ @overload
+ def increases_by(self, *, diff: None, frac: PosNum) -> MetricChangeFilter: ...
+ def increases_by(
+ self, *, diff: PosNum | None = None, frac: PosNum | None = None
+ ) -> MetricChangeFilter:
+ """Defines a filter that observes for an increase in the numerical value of a run metric.
+
+ Arguments are the same as for `.changes_by()`.
+ """
+ return self.changes_by(diff=diff, frac=frac, _dir=ChangeDir.INC)
+
+ @overload
+ def decreases_by(self, *, diff: PosNum, frac: None) -> MetricChangeFilter: ...
+ @overload
+ def decreases_by(self, *, diff: None, frac: PosNum) -> MetricChangeFilter: ...
+ def decreases_by(
+ self, *, diff: PosNum | None = None, frac: PosNum | None = None
+ ) -> MetricChangeFilter:
+ """Defines a filter that observes for a decrease in the numerical value of a run metric.
+
+ Arguments are the same as for `.changes_by()`.
+ """
+ return self.changes_by(diff=diff, frac=frac, _dir=ChangeDir.DEC)
+
+
+class MetricVal(BaseMetricOperand):
+ """Represents a single, unaggregated metric value when defining a metric filter."""
+
+ name: str
+
+ # Allow users to convert this single-value metric into an aggregated metric expression.
+ def max(self, window: int) -> MetricAgg:
+ return MetricAgg(name=self.name, agg=Agg.MAX, window=window)
+
+ def min(self, window: int) -> MetricAgg:
+ return MetricAgg(name=self.name, agg=Agg.MIN, window=window)
+
+ def avg(self, window: int) -> MetricAgg:
+ return MetricAgg(name=self.name, agg=Agg.AVG, window=window)
+
+ # Aliased method for users familiar with e.g. torch/tf/numpy/pandas/polars/etc.
+ def mean(self, window: int) -> MetricAgg:
+ return self.avg(window=window)
+
+
+class MetricAgg(BaseMetricOperand):
+ """Represents an aggregated metric value when defining a metric filter."""
+
+ name: str
+ agg: Annotated[Agg, Field(alias="agg_op")]
+ window: Annotated[PositiveInt, Field(alias="window_size")]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d74919bddbcce44a62afca06711c1acb0c9bd09b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/__init__.py
@@ -0,0 +1,104 @@
+# Generated by ariadne-codegen
+
+__all__ = [
+ "CREATE_AUTOMATION_GQL",
+ "CREATE_GENERIC_WEBHOOK_INTEGRATION_GQL",
+ "DELETE_AUTOMATION_GQL",
+ "GENERIC_WEBHOOK_INTEGRATIONS_BY_ENTITY_GQL",
+ "GET_AUTOMATIONS_BY_ENTITY_GQL",
+ "GET_AUTOMATIONS_GQL",
+ "INTEGRATIONS_BY_ENTITY_GQL",
+ "SLACK_INTEGRATIONS_BY_ENTITY_GQL",
+ "UPDATE_AUTOMATION_GQL",
+ "GetAutomations",
+ "GetAutomationsByEntity",
+ "CreateAutomation",
+ "UpdateAutomation",
+ "DeleteAutomation",
+ "IntegrationsByEntity",
+ "SlackIntegrationsByEntity",
+ "GenericWebhookIntegrationsByEntity",
+ "CreateGenericWebhookIntegration",
+ "CreateFilterTriggerInput",
+ "CreateGenericWebhookIntegrationInput",
+ "GenericWebhookActionInput",
+ "NoOpTriggeredActionInput",
+ "NotificationActionInput",
+ "QueueJobActionInput",
+ "TriggeredActionConfig",
+ "UpdateFilterTriggerInput",
+ "ArtifactPortfolioScopeFields",
+ "ArtifactSequenceScopeFields",
+ "FilterEventFields",
+ "GenericWebhookActionFields",
+ "GenericWebhookIntegrationConnectionFields",
+ "GenericWebhookIntegrationFields",
+ "IntegrationConnectionFields",
+ "NoOpActionFields",
+ "NotificationActionFields",
+ "PageInfoFields",
+ "ProjectConnectionFields",
+ "ProjectScopeFields",
+ "QueueJobActionFields",
+ "SlackIntegrationConnectionFields",
+ "SlackIntegrationFields",
+ "TriggerFields",
+ "AlertSeverity",
+ "EventTriggeringConditionType",
+ "TriggerScopeType",
+ "TriggeredActionType",
+]
+from .create_automation import CreateAutomation
+from .create_generic_webhook_integration import CreateGenericWebhookIntegration
+from .delete_automation import DeleteAutomation
+from .enums import (
+ AlertSeverity,
+ EventTriggeringConditionType,
+ TriggeredActionType,
+ TriggerScopeType,
+)
+from .fragments import (
+ ArtifactPortfolioScopeFields,
+ ArtifactSequenceScopeFields,
+ FilterEventFields,
+ GenericWebhookActionFields,
+ GenericWebhookIntegrationConnectionFields,
+ GenericWebhookIntegrationFields,
+ IntegrationConnectionFields,
+ NoOpActionFields,
+ NotificationActionFields,
+ PageInfoFields,
+ ProjectConnectionFields,
+ ProjectScopeFields,
+ QueueJobActionFields,
+ SlackIntegrationConnectionFields,
+ SlackIntegrationFields,
+ TriggerFields,
+)
+from .generic_webhook_integrations_by_entity import GenericWebhookIntegrationsByEntity
+from .get_automations import GetAutomations
+from .get_automations_by_entity import GetAutomationsByEntity
+from .input_types import (
+ CreateFilterTriggerInput,
+ CreateGenericWebhookIntegrationInput,
+ GenericWebhookActionInput,
+ NoOpTriggeredActionInput,
+ NotificationActionInput,
+ QueueJobActionInput,
+ TriggeredActionConfig,
+ UpdateFilterTriggerInput,
+)
+from .integrations_by_entity import IntegrationsByEntity
+from .operations import (
+ CREATE_AUTOMATION_GQL,
+ CREATE_GENERIC_WEBHOOK_INTEGRATION_GQL,
+ DELETE_AUTOMATION_GQL,
+ GENERIC_WEBHOOK_INTEGRATIONS_BY_ENTITY_GQL,
+ GET_AUTOMATIONS_BY_ENTITY_GQL,
+ GET_AUTOMATIONS_GQL,
+ INTEGRATIONS_BY_ENTITY_GQL,
+ SLACK_INTEGRATIONS_BY_ENTITY_GQL,
+ UPDATE_AUTOMATION_GQL,
+)
+from .slack_integrations_by_entity import SlackIntegrationsByEntity
+from .update_automation import UpdateAutomation
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/create_automation.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/create_automation.py
new file mode 100644
index 0000000000000000000000000000000000000000..63c551908b961291bd0ef87e79e90bae24e66686
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/create_automation.py
@@ -0,0 +1,17 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/automations/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from wandb._pydantic import GQLBase
+
+from .fragments import CreateAutomationResult
+
+
+class CreateAutomation(GQLBase):
+ result: Optional[CreateAutomationResult]
+
+
+CreateAutomation.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/create_generic_webhook_integration.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/create_generic_webhook_integration.py
new file mode 100644
index 0000000000000000000000000000000000000000..10d287e098468f7a2b58d2314d755f1488cc9e71
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/create_generic_webhook_integration.py
@@ -0,0 +1,37 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/automations/
+
+from __future__ import annotations
+
+from typing import Literal, Optional, Union
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase, Typename
+
+from .fragments import GenericWebhookIntegrationFields
+
+
+class CreateGenericWebhookIntegration(GQLBase):
+ create_generic_webhook_integration: Optional[
+ CreateGenericWebhookIntegrationCreateGenericWebhookIntegration
+ ] = Field(alias="createGenericWebhookIntegration")
+
+
+class CreateGenericWebhookIntegrationCreateGenericWebhookIntegration(GQLBase):
+ integration: Union[
+ CreateGenericWebhookIntegrationCreateGenericWebhookIntegrationIntegrationIntegration,
+ GenericWebhookIntegrationFields,
+ ] = Field(discriminator="typename__")
+
+
+class CreateGenericWebhookIntegrationCreateGenericWebhookIntegrationIntegrationIntegration(
+ GQLBase
+):
+ typename__: Typename[
+ Literal["GitHubOAuthIntegration", "Integration", "SlackIntegration"]
+ ]
+
+
+CreateGenericWebhookIntegration.model_rebuild()
+CreateGenericWebhookIntegrationCreateGenericWebhookIntegration.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/delete_automation.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/delete_automation.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c055b77ce4f49fc3d0a1dbce182697819b69588
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/delete_automation.py
@@ -0,0 +1,15 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/automations/
+
+from __future__ import annotations
+
+from wandb._pydantic import GQLBase
+
+from .fragments import DeleteAutomationResult
+
+
+class DeleteAutomation(GQLBase):
+ result: DeleteAutomationResult
+
+
+DeleteAutomation.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/enums.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/enums.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8e4ef7dfb5c9128366fc82d6e34246b17ce1fb2
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/enums.py
@@ -0,0 +1,35 @@
+# Generated by ariadne-codegen
+# Source: core/api/graphql/schemas/schema-latest.graphql
+
+from __future__ import annotations
+
+from enum import Enum
+
+
+class AlertSeverity(str, Enum):
+ INFO = "INFO"
+ WARN = "WARN"
+ ERROR = "ERROR"
+
+
+class TriggerScopeType(str, Enum):
+ PROJECT = "PROJECT"
+ ARTIFACT_COLLECTION = "ARTIFACT_COLLECTION"
+
+
+class EventTriggeringConditionType(str, Enum):
+ CREATE_ARTIFACT = "CREATE_ARTIFACT"
+ UPDATE_ARTIFACT_ALIAS = "UPDATE_ARTIFACT_ALIAS"
+ ADD_ARTIFACT_ALIAS = "ADD_ARTIFACT_ALIAS"
+ ADD_ARTIFACT_TAG = "ADD_ARTIFACT_TAG"
+ LINK_MODEL = "LINK_MODEL"
+ RUN_METRIC = "RUN_METRIC"
+ RUN_METRIC_CHANGE = "RUN_METRIC_CHANGE"
+ RUN_STATE = "RUN_STATE"
+
+
+class TriggeredActionType(str, Enum):
+ QUEUE_JOB = "QUEUE_JOB"
+ NOTIFICATION = "NOTIFICATION"
+ GENERIC_WEBHOOK = "GENERIC_WEBHOOK"
+ NO_OP = "NO_OP"
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/fragments.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/fragments.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a78cf559dbf110bb26571148378a50226d2f8bb
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/fragments.py
@@ -0,0 +1,293 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/automations/
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import List, Literal, Optional, Union
+
+from pydantic import Field
+from typing_extensions import Annotated
+
+from wandb._pydantic import GQLBase, GQLId, Typename
+
+from .enums import AlertSeverity, EventTriggeringConditionType
+
+
+class ArtifactPortfolioScopeFields(GQLBase):
+ typename__: Typename[Literal["ArtifactPortfolio"]] = "ArtifactPortfolio"
+ id: GQLId
+ name: str
+
+
+class ArtifactSequenceScopeFields(GQLBase):
+ typename__: Typename[Literal["ArtifactSequence"]] = "ArtifactSequence"
+ id: GQLId
+ name: str
+
+
+class CreateAutomationResult(GQLBase):
+ typename__: Typename[Literal["CreateFilterTriggerPayload"]] = (
+ "CreateFilterTriggerPayload"
+ )
+ trigger: Optional[TriggerFields]
+
+
+class DeleteAutomationResult(GQLBase):
+ typename__: Typename[Literal["DeleteTriggerPayload"]] = "DeleteTriggerPayload"
+ success: bool
+
+
+class FilterEventFields(GQLBase):
+ typename__: Typename[Literal["FilterEventTriggeringCondition"]] = (
+ "FilterEventTriggeringCondition"
+ )
+ event_type: EventTriggeringConditionType = Field(alias="eventType")
+ filter: str
+
+
+class GenericWebhookActionFields(GQLBase):
+ typename__: Typename[Literal["GenericWebhookTriggeredAction"]] = (
+ "GenericWebhookTriggeredAction"
+ )
+ integration: Union[
+ GenericWebhookActionFieldsIntegrationIntegration,
+ GenericWebhookIntegrationFields,
+ ] = Field(discriminator="typename__")
+ request_payload: Optional[str] = Field(alias="requestPayload")
+
+
+class GenericWebhookActionFieldsIntegrationIntegration(GQLBase):
+ typename__: Typename[
+ Literal["GitHubOAuthIntegration", "Integration", "SlackIntegration"]
+ ]
+
+
+class GenericWebhookIntegrationConnectionFields(GQLBase):
+ typename__: Typename[Literal["IntegrationConnection"]] = "IntegrationConnection"
+ page_info: PageInfoFields = Field(alias="pageInfo")
+ edges: List[GenericWebhookIntegrationConnectionFieldsEdges]
+
+
+class GenericWebhookIntegrationConnectionFieldsEdges(GQLBase):
+ cursor: str
+ node: Optional[
+ Annotated[
+ Union[
+ GenericWebhookIntegrationConnectionFieldsEdgesNodeIntegration,
+ GenericWebhookIntegrationFields,
+ ],
+ Field(discriminator="typename__"),
+ ]
+ ]
+
+
+class GenericWebhookIntegrationConnectionFieldsEdgesNodeIntegration(GQLBase):
+ typename__: Typename[
+ Literal["GitHubOAuthIntegration", "Integration", "SlackIntegration"]
+ ]
+
+
+class GenericWebhookIntegrationFields(GQLBase):
+ typename__: Typename[Literal["GenericWebhookIntegration"]] = (
+ "GenericWebhookIntegration"
+ )
+ id: GQLId
+ name: str
+ url_endpoint: str = Field(alias="urlEndpoint")
+
+
+class IntegrationConnectionFields(GQLBase):
+ typename__: Typename[Literal["IntegrationConnection"]] = "IntegrationConnection"
+ page_info: PageInfoFields = Field(alias="pageInfo")
+ edges: List[IntegrationConnectionFieldsEdges]
+
+
+class IntegrationConnectionFieldsEdges(GQLBase):
+ cursor: str
+ node: Optional[
+ Annotated[
+ Union[
+ IntegrationConnectionFieldsEdgesNodeIntegration,
+ GenericWebhookIntegrationFields,
+ SlackIntegrationFields,
+ ],
+ Field(discriminator="typename__"),
+ ]
+ ]
+
+
+class IntegrationConnectionFieldsEdgesNodeIntegration(GQLBase):
+ typename__: Typename[Literal["GitHubOAuthIntegration", "Integration"]]
+
+
+class NoOpActionFields(GQLBase):
+ typename__: Typename[Literal["NoOpTriggeredAction"]] = "NoOpTriggeredAction"
+ no_op: Optional[bool] = Field(alias="noOp")
+
+
+class NotificationActionFields(GQLBase):
+ typename__: Typename[Literal["NotificationTriggeredAction"]] = (
+ "NotificationTriggeredAction"
+ )
+ integration: Union[
+ NotificationActionFieldsIntegrationIntegration, SlackIntegrationFields
+ ] = Field(discriminator="typename__")
+ title: Optional[str]
+ message: Optional[str]
+ severity: Optional[AlertSeverity]
+
+
+class NotificationActionFieldsIntegrationIntegration(GQLBase):
+ typename__: Typename[
+ Literal["GenericWebhookIntegration", "GitHubOAuthIntegration", "Integration"]
+ ]
+
+
+class PageInfoFields(GQLBase):
+ end_cursor: Optional[str] = Field(alias="endCursor")
+ has_next_page: bool = Field(alias="hasNextPage")
+
+
+class ProjectConnectionFields(GQLBase):
+ typename__: Typename[Literal["ProjectConnection"]] = "ProjectConnection"
+ page_info: PageInfoFields = Field(alias="pageInfo")
+ edges: List[ProjectConnectionFieldsEdges]
+
+
+class ProjectConnectionFieldsEdges(GQLBase):
+ cursor: str
+ node: Optional[ProjectConnectionFieldsEdgesNode]
+
+
+class ProjectConnectionFieldsEdgesNode(GQLBase):
+ triggers: List[TriggerFields]
+
+
+class ProjectScopeFields(GQLBase):
+ typename__: Typename[Literal["Project"]] = "Project"
+ id: GQLId
+ name: str
+
+
+class QueueJobActionFields(GQLBase):
+ typename__: Typename[Literal["QueueJobTriggeredAction"]] = "QueueJobTriggeredAction"
+ queue: Optional[QueueJobActionFieldsQueue]
+ template: str
+
+
+class QueueJobActionFieldsQueue(GQLBase):
+ id: GQLId
+ name: str
+
+
+class SlackIntegrationConnectionFields(GQLBase):
+ typename__: Typename[Literal["IntegrationConnection"]] = "IntegrationConnection"
+ page_info: PageInfoFields = Field(alias="pageInfo")
+ edges: List[SlackIntegrationConnectionFieldsEdges]
+
+
+class SlackIntegrationConnectionFieldsEdges(GQLBase):
+ cursor: str
+ node: Optional[
+ Annotated[
+ Union[
+ SlackIntegrationConnectionFieldsEdgesNodeIntegration,
+ SlackIntegrationFields,
+ ],
+ Field(discriminator="typename__"),
+ ]
+ ]
+
+
+class SlackIntegrationConnectionFieldsEdgesNodeIntegration(GQLBase):
+ typename__: Typename[
+ Literal["GenericWebhookIntegration", "GitHubOAuthIntegration", "Integration"]
+ ]
+
+
+class SlackIntegrationFields(GQLBase):
+ typename__: Typename[Literal["SlackIntegration"]] = "SlackIntegration"
+ id: GQLId
+ team_name: str = Field(alias="teamName")
+ channel_name: str = Field(alias="channelName")
+
+
+class TriggerFields(GQLBase):
+ typename__: Typename[Literal["Trigger"]] = "Trigger"
+ id: GQLId
+ created_at: datetime = Field(alias="createdAt")
+ updated_at: Optional[datetime] = Field(alias="updatedAt")
+ name: str
+ description: Optional[str]
+ enabled: bool
+ scope: Union[
+ ProjectScopeFields, ArtifactSequenceScopeFields, ArtifactPortfolioScopeFields
+ ] = Field(discriminator="typename__")
+ event: FilterEventFields
+ action: Union[
+ QueueJobActionFields,
+ NotificationActionFields,
+ GenericWebhookActionFields,
+ NoOpActionFields,
+ ] = Field(discriminator="typename__")
+
+
+class UpdateAutomationResult(GQLBase):
+ typename__: Typename[Literal["UpdateFilterTriggerPayload"]] = (
+ "UpdateFilterTriggerPayload"
+ )
+ trigger: Optional[TriggerFields]
+
+
+ArtifactPortfolioScopeFields.model_rebuild()
+ArtifactSequenceScopeFields.model_rebuild()
+CreateAutomationResult.model_rebuild()
+DeleteAutomationResult.model_rebuild()
+FilterEventFields.model_rebuild()
+GenericWebhookActionFields.model_rebuild()
+GenericWebhookActionFieldsIntegrationIntegration.model_rebuild()
+GenericWebhookIntegrationConnectionFields.model_rebuild()
+GenericWebhookIntegrationConnectionFieldsEdges.model_rebuild()
+GenericWebhookIntegrationConnectionFieldsEdgesNodeIntegration.model_rebuild()
+GenericWebhookIntegrationFields.model_rebuild()
+IntegrationConnectionFields.model_rebuild()
+IntegrationConnectionFieldsEdges.model_rebuild()
+IntegrationConnectionFieldsEdgesNodeIntegration.model_rebuild()
+NoOpActionFields.model_rebuild()
+NotificationActionFields.model_rebuild()
+NotificationActionFieldsIntegrationIntegration.model_rebuild()
+PageInfoFields.model_rebuild()
+ProjectConnectionFields.model_rebuild()
+ProjectConnectionFieldsEdges.model_rebuild()
+ProjectConnectionFieldsEdgesNode.model_rebuild()
+ProjectScopeFields.model_rebuild()
+QueueJobActionFields.model_rebuild()
+QueueJobActionFieldsQueue.model_rebuild()
+SlackIntegrationConnectionFields.model_rebuild()
+SlackIntegrationConnectionFieldsEdges.model_rebuild()
+SlackIntegrationConnectionFieldsEdgesNodeIntegration.model_rebuild()
+SlackIntegrationFields.model_rebuild()
+TriggerFields.model_rebuild()
+UpdateAutomationResult.model_rebuild()
+ArtifactPortfolioScopeFields.model_rebuild()
+ArtifactSequenceScopeFields.model_rebuild()
+FilterEventFields.model_rebuild()
+GenericWebhookActionFields.model_rebuild()
+GenericWebhookIntegrationFields.model_rebuild()
+GenericWebhookIntegrationFields.model_rebuild()
+GenericWebhookIntegrationFields.model_rebuild()
+NoOpActionFields.model_rebuild()
+NotificationActionFields.model_rebuild()
+PageInfoFields.model_rebuild()
+PageInfoFields.model_rebuild()
+PageInfoFields.model_rebuild()
+PageInfoFields.model_rebuild()
+ProjectScopeFields.model_rebuild()
+QueueJobActionFields.model_rebuild()
+SlackIntegrationFields.model_rebuild()
+SlackIntegrationFields.model_rebuild()
+SlackIntegrationFields.model_rebuild()
+TriggerFields.model_rebuild()
+TriggerFields.model_rebuild()
+TriggerFields.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/generic_webhook_integrations_by_entity.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/generic_webhook_integrations_by_entity.py
new file mode 100644
index 0000000000000000000000000000000000000000..4374455b8da8c051a43df1e189ce986c64d9d64c
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/generic_webhook_integrations_by_entity.py
@@ -0,0 +1,22 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/automations/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from wandb._pydantic import GQLBase
+
+from .fragments import GenericWebhookIntegrationConnectionFields
+
+
+class GenericWebhookIntegrationsByEntity(GQLBase):
+ entity: Optional[GenericWebhookIntegrationsByEntityEntity]
+
+
+class GenericWebhookIntegrationsByEntityEntity(GQLBase):
+ integrations: Optional[GenericWebhookIntegrationConnectionFields]
+
+
+GenericWebhookIntegrationsByEntity.model_rebuild()
+GenericWebhookIntegrationsByEntityEntity.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/get_automations.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/get_automations.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9be5c3fe2f55010e134e140342a9032fd07ae7d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/get_automations.py
@@ -0,0 +1,24 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/automations/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+from .fragments import ProjectConnectionFields
+
+
+class GetAutomations(GQLBase):
+ search_scope: Optional[GetAutomationsSearchScope] = Field(alias="searchScope")
+
+
+class GetAutomationsSearchScope(GQLBase):
+ projects: Optional[ProjectConnectionFields]
+
+
+GetAutomations.model_rebuild()
+GetAutomationsSearchScope.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/get_automations_by_entity.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/get_automations_by_entity.py
new file mode 100644
index 0000000000000000000000000000000000000000..2be7ecdce1186fbf902fe2342fcd0feca35ce603
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/get_automations_by_entity.py
@@ -0,0 +1,26 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/automations/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+from .fragments import ProjectConnectionFields
+
+
+class GetAutomationsByEntity(GQLBase):
+ search_scope: Optional[GetAutomationsByEntitySearchScope] = Field(
+ alias="searchScope"
+ )
+
+
+class GetAutomationsByEntitySearchScope(GQLBase):
+ projects: Optional[ProjectConnectionFields]
+
+
+GetAutomationsByEntity.model_rebuild()
+GetAutomationsByEntitySearchScope.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/input_types.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/input_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..968d461fd06d9639f8960b8114ce0c7d1219b708
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/input_types.py
@@ -0,0 +1,104 @@
+# Generated by ariadne-codegen
+# Source: core/api/graphql/schemas/schema-latest.graphql
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase, GQLId
+
+from .enums import (
+ AlertSeverity,
+ EventTriggeringConditionType,
+ TriggeredActionType,
+ TriggerScopeType,
+)
+
+
+class CreateGenericWebhookIntegrationInput(GQLBase):
+ entity_name: str = Field(alias="entityName")
+ url_endpoint: str = Field(alias="urlEndpoint")
+ name: str
+ secret_ref: Optional[str] = Field(alias="secretRef", default=None)
+ access_token_ref: Optional[str] = Field(alias="accessTokenRef", default=None)
+ client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None)
+
+
+class QueueJobActionInput(GQLBase):
+ queue_id: GQLId = Field(alias="queueID")
+ template: str
+
+
+class NotificationActionInput(GQLBase):
+ integration_id: GQLId = Field(alias="integrationID")
+ title: Optional[str] = None
+ message: Optional[str] = None
+ severity: Optional[AlertSeverity] = None
+
+
+class GenericWebhookActionInput(GQLBase):
+ integration_id: GQLId = Field(alias="integrationID")
+ request_payload: Optional[str] = Field(alias="requestPayload", default=None)
+
+
+class NoOpTriggeredActionInput(GQLBase):
+ no_op: Optional[bool] = Field(alias="noOp", default=None)
+
+
+class TriggeredActionConfig(GQLBase):
+ queue_job_action_input: Optional[QueueJobActionInput] = Field(
+ alias="queueJobActionInput", default=None
+ )
+ notification_action_input: Optional[NotificationActionInput] = Field(
+ alias="notificationActionInput", default=None
+ )
+ generic_webhook_action_input: Optional[GenericWebhookActionInput] = Field(
+ alias="genericWebhookActionInput", default=None
+ )
+ no_op_action_input: Optional[NoOpTriggeredActionInput] = Field(
+ alias="noOpActionInput", default=None
+ )
+
+
+class CreateFilterTriggerInput(GQLBase):
+ name: str
+ description: Optional[str] = None
+ triggering_event_type: EventTriggeringConditionType = Field(
+ alias="triggeringEventType"
+ )
+ scope_type: TriggerScopeType = Field(alias="scopeType")
+ scope_id: GQLId = Field(alias="scopeID")
+ event_filter: str = Field(alias="eventFilter")
+ triggered_action_type: TriggeredActionType = Field(alias="triggeredActionType")
+ triggered_action_config: TriggeredActionConfig = Field(
+ alias="triggeredActionConfig"
+ )
+ enabled: bool
+ client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None)
+
+
+class UpdateFilterTriggerInput(GQLBase):
+ id: GQLId
+ name: Optional[str] = None
+ description: Optional[str] = None
+ triggering_event_type: Optional[EventTriggeringConditionType] = Field(
+ alias="triggeringEventType", default=None
+ )
+ scope_type: Optional[TriggerScopeType] = Field(alias="scopeType", default=None)
+ scope_id: Optional[GQLId] = Field(alias="scopeID", default=None)
+ event_filter: Optional[str] = Field(alias="eventFilter", default=None)
+ triggered_action_type: Optional[TriggeredActionType] = Field(
+ alias="triggeredActionType", default=None
+ )
+ triggered_action_config: Optional[TriggeredActionConfig] = Field(
+ alias="triggeredActionConfig", default=None
+ )
+ enabled: Optional[bool] = None
+ client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None)
+
+
+TriggeredActionConfig.model_rebuild()
+CreateFilterTriggerInput.model_rebuild()
+UpdateFilterTriggerInput.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/integrations_by_entity.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/integrations_by_entity.py
new file mode 100644
index 0000000000000000000000000000000000000000..993c0ad33149e3fd184fc7eddf461d929df0d3ce
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/integrations_by_entity.py
@@ -0,0 +1,22 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/automations/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from wandb._pydantic import GQLBase
+
+from .fragments import IntegrationConnectionFields
+
+
+class IntegrationsByEntity(GQLBase):
+ entity: Optional[IntegrationsByEntityEntity]
+
+
+class IntegrationsByEntityEntity(GQLBase):
+ integrations: Optional[IntegrationConnectionFields]
+
+
+IntegrationsByEntity.model_rebuild()
+IntegrationsByEntityEntity.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/operations.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/operations.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d67acd8d6541180d8ab7a99f8f876364592a338
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/operations.py
@@ -0,0 +1,647 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/automations/
+
+__all__ = [
+ "CREATE_AUTOMATION_GQL",
+ "CREATE_GENERIC_WEBHOOK_INTEGRATION_GQL",
+ "DELETE_AUTOMATION_GQL",
+ "GENERIC_WEBHOOK_INTEGRATIONS_BY_ENTITY_GQL",
+ "GET_AUTOMATIONS_BY_ENTITY_GQL",
+ "GET_AUTOMATIONS_GQL",
+ "INTEGRATIONS_BY_ENTITY_GQL",
+ "SLACK_INTEGRATIONS_BY_ENTITY_GQL",
+ "UPDATE_AUTOMATION_GQL",
+]
+
+GET_AUTOMATIONS_GQL = """
+query GetAutomations($cursor: String, $perPage: Int) {
+ searchScope: viewer {
+ projects(after: $cursor, first: $perPage) {
+ ...ProjectConnectionFields
+ }
+ }
+}
+
+fragment ArtifactPortfolioScopeFields on ArtifactPortfolio {
+ __typename
+ id
+ name
+}
+
+fragment ArtifactSequenceScopeFields on ArtifactSequence {
+ __typename
+ id
+ name
+}
+
+fragment FilterEventFields on FilterEventTriggeringCondition {
+ __typename
+ eventType
+ filter
+}
+
+fragment GenericWebhookActionFields on GenericWebhookTriggeredAction {
+ __typename
+ integration {
+ __typename
+ ...GenericWebhookIntegrationFields
+ }
+ requestPayload
+}
+
+fragment GenericWebhookIntegrationFields on GenericWebhookIntegration {
+ __typename
+ id
+ name
+ urlEndpoint
+}
+
+fragment NoOpActionFields on NoOpTriggeredAction {
+ __typename
+ noOp
+}
+
+fragment NotificationActionFields on NotificationTriggeredAction {
+ __typename
+ integration {
+ __typename
+ ...SlackIntegrationFields
+ }
+ title
+ message
+ severity
+}
+
+fragment PageInfoFields on PageInfo {
+ endCursor
+ hasNextPage
+}
+
+fragment ProjectConnectionFields on ProjectConnection {
+ __typename
+ pageInfo {
+ ...PageInfoFields
+ }
+ edges {
+ cursor
+ node {
+ triggers {
+ ...TriggerFields
+ }
+ }
+ }
+}
+
+fragment ProjectScopeFields on Project {
+ __typename
+ id
+ name
+}
+
+fragment QueueJobActionFields on QueueJobTriggeredAction {
+ __typename
+ queue {
+ id
+ name
+ }
+ template
+}
+
+fragment SlackIntegrationFields on SlackIntegration {
+ __typename
+ id
+ teamName
+ channelName
+}
+
+fragment TriggerFields on Trigger {
+ __typename
+ id
+ createdAt
+ updatedAt
+ name
+ description
+ enabled
+ scope {
+ __typename
+ ...ProjectScopeFields
+ ...ArtifactPortfolioScopeFields
+ ...ArtifactSequenceScopeFields
+ }
+ event: triggeringCondition {
+ __typename
+ ...FilterEventFields
+ }
+ action: triggeredAction {
+ __typename
+ ...QueueJobActionFields
+ ...NotificationActionFields
+ ...GenericWebhookActionFields
+ ...NoOpActionFields
+ }
+}
+"""
+
+GET_AUTOMATIONS_BY_ENTITY_GQL = """
+query GetAutomationsByEntity($entityName: String!, $cursor: String, $perPage: Int) {
+ searchScope: entity(name: $entityName) {
+ projects(after: $cursor, first: $perPage) {
+ ...ProjectConnectionFields
+ }
+ }
+}
+
+fragment ArtifactPortfolioScopeFields on ArtifactPortfolio {
+ __typename
+ id
+ name
+}
+
+fragment ArtifactSequenceScopeFields on ArtifactSequence {
+ __typename
+ id
+ name
+}
+
+fragment FilterEventFields on FilterEventTriggeringCondition {
+ __typename
+ eventType
+ filter
+}
+
+fragment GenericWebhookActionFields on GenericWebhookTriggeredAction {
+ __typename
+ integration {
+ __typename
+ ...GenericWebhookIntegrationFields
+ }
+ requestPayload
+}
+
+fragment GenericWebhookIntegrationFields on GenericWebhookIntegration {
+ __typename
+ id
+ name
+ urlEndpoint
+}
+
+fragment NoOpActionFields on NoOpTriggeredAction {
+ __typename
+ noOp
+}
+
+fragment NotificationActionFields on NotificationTriggeredAction {
+ __typename
+ integration {
+ __typename
+ ...SlackIntegrationFields
+ }
+ title
+ message
+ severity
+}
+
+fragment PageInfoFields on PageInfo {
+ endCursor
+ hasNextPage
+}
+
+fragment ProjectConnectionFields on ProjectConnection {
+ __typename
+ pageInfo {
+ ...PageInfoFields
+ }
+ edges {
+ cursor
+ node {
+ triggers {
+ ...TriggerFields
+ }
+ }
+ }
+}
+
+fragment ProjectScopeFields on Project {
+ __typename
+ id
+ name
+}
+
+fragment QueueJobActionFields on QueueJobTriggeredAction {
+ __typename
+ queue {
+ id
+ name
+ }
+ template
+}
+
+fragment SlackIntegrationFields on SlackIntegration {
+ __typename
+ id
+ teamName
+ channelName
+}
+
+fragment TriggerFields on Trigger {
+ __typename
+ id
+ createdAt
+ updatedAt
+ name
+ description
+ enabled
+ scope {
+ __typename
+ ...ProjectScopeFields
+ ...ArtifactPortfolioScopeFields
+ ...ArtifactSequenceScopeFields
+ }
+ event: triggeringCondition {
+ __typename
+ ...FilterEventFields
+ }
+ action: triggeredAction {
+ __typename
+ ...QueueJobActionFields
+ ...NotificationActionFields
+ ...GenericWebhookActionFields
+ ...NoOpActionFields
+ }
+}
+"""
+
+CREATE_AUTOMATION_GQL = """
+mutation CreateAutomation($params: CreateFilterTriggerInput!) {
+ result: createFilterTrigger(input: $params) {
+ ...CreateAutomationResult
+ }
+}
+
+fragment ArtifactPortfolioScopeFields on ArtifactPortfolio {
+ __typename
+ id
+ name
+}
+
+fragment ArtifactSequenceScopeFields on ArtifactSequence {
+ __typename
+ id
+ name
+}
+
+fragment CreateAutomationResult on CreateFilterTriggerPayload {
+ __typename
+ trigger {
+ ...TriggerFields
+ }
+}
+
+fragment FilterEventFields on FilterEventTriggeringCondition {
+ __typename
+ eventType
+ filter
+}
+
+fragment GenericWebhookActionFields on GenericWebhookTriggeredAction {
+ __typename
+ integration {
+ __typename
+ ...GenericWebhookIntegrationFields
+ }
+ requestPayload
+}
+
+fragment GenericWebhookIntegrationFields on GenericWebhookIntegration {
+ __typename
+ id
+ name
+ urlEndpoint
+}
+
+fragment NoOpActionFields on NoOpTriggeredAction {
+ __typename
+ noOp
+}
+
+fragment NotificationActionFields on NotificationTriggeredAction {
+ __typename
+ integration {
+ __typename
+ ...SlackIntegrationFields
+ }
+ title
+ message
+ severity
+}
+
+fragment ProjectScopeFields on Project {
+ __typename
+ id
+ name
+}
+
+fragment QueueJobActionFields on QueueJobTriggeredAction {
+ __typename
+ queue {
+ id
+ name
+ }
+ template
+}
+
+fragment SlackIntegrationFields on SlackIntegration {
+ __typename
+ id
+ teamName
+ channelName
+}
+
+fragment TriggerFields on Trigger {
+ __typename
+ id
+ createdAt
+ updatedAt
+ name
+ description
+ enabled
+ scope {
+ __typename
+ ...ProjectScopeFields
+ ...ArtifactPortfolioScopeFields
+ ...ArtifactSequenceScopeFields
+ }
+ event: triggeringCondition {
+ __typename
+ ...FilterEventFields
+ }
+ action: triggeredAction {
+ __typename
+ ...QueueJobActionFields
+ ...NotificationActionFields
+ ...GenericWebhookActionFields
+ ...NoOpActionFields
+ }
+}
+"""
+
+UPDATE_AUTOMATION_GQL = """
+mutation UpdateAutomation($params: UpdateFilterTriggerInput!) {
+ result: updateFilterTrigger(input: $params) {
+ ...UpdateAutomationResult
+ }
+}
+
+fragment ArtifactPortfolioScopeFields on ArtifactPortfolio {
+ __typename
+ id
+ name
+}
+
+fragment ArtifactSequenceScopeFields on ArtifactSequence {
+ __typename
+ id
+ name
+}
+
+fragment FilterEventFields on FilterEventTriggeringCondition {
+ __typename
+ eventType
+ filter
+}
+
+fragment GenericWebhookActionFields on GenericWebhookTriggeredAction {
+ __typename
+ integration {
+ __typename
+ ...GenericWebhookIntegrationFields
+ }
+ requestPayload
+}
+
+fragment GenericWebhookIntegrationFields on GenericWebhookIntegration {
+ __typename
+ id
+ name
+ urlEndpoint
+}
+
+fragment NoOpActionFields on NoOpTriggeredAction {
+ __typename
+ noOp
+}
+
+fragment NotificationActionFields on NotificationTriggeredAction {
+ __typename
+ integration {
+ __typename
+ ...SlackIntegrationFields
+ }
+ title
+ message
+ severity
+}
+
+fragment ProjectScopeFields on Project {
+ __typename
+ id
+ name
+}
+
+fragment QueueJobActionFields on QueueJobTriggeredAction {
+ __typename
+ queue {
+ id
+ name
+ }
+ template
+}
+
+fragment SlackIntegrationFields on SlackIntegration {
+ __typename
+ id
+ teamName
+ channelName
+}
+
+fragment TriggerFields on Trigger {
+ __typename
+ id
+ createdAt
+ updatedAt
+ name
+ description
+ enabled
+ scope {
+ __typename
+ ...ProjectScopeFields
+ ...ArtifactPortfolioScopeFields
+ ...ArtifactSequenceScopeFields
+ }
+ event: triggeringCondition {
+ __typename
+ ...FilterEventFields
+ }
+ action: triggeredAction {
+ __typename
+ ...QueueJobActionFields
+ ...NotificationActionFields
+ ...GenericWebhookActionFields
+ ...NoOpActionFields
+ }
+}
+
+fragment UpdateAutomationResult on UpdateFilterTriggerPayload {
+ __typename
+ trigger {
+ ...TriggerFields
+ }
+}
+"""
+
+DELETE_AUTOMATION_GQL = """
+mutation DeleteAutomation($id: ID!) {
+ result: deleteTrigger(input: {triggerID: $id}) {
+ ...DeleteAutomationResult
+ }
+}
+
+fragment DeleteAutomationResult on DeleteTriggerPayload {
+ __typename
+ success
+}
+"""
+
+INTEGRATIONS_BY_ENTITY_GQL = """
+query IntegrationsByEntity($entityName: String!, $cursor: String, $perPage: Int) {
+ entity(name: $entityName) {
+ integrations(after: $cursor, first: $perPage) {
+ ...IntegrationConnectionFields
+ }
+ }
+}
+
+fragment GenericWebhookIntegrationFields on GenericWebhookIntegration {
+ __typename
+ id
+ name
+ urlEndpoint
+}
+
+fragment IntegrationConnectionFields on IntegrationConnection {
+ __typename
+ pageInfo {
+ ...PageInfoFields
+ }
+ edges {
+ cursor
+ node {
+ __typename
+ ...SlackIntegrationFields
+ ...GenericWebhookIntegrationFields
+ }
+ }
+}
+
+fragment PageInfoFields on PageInfo {
+ endCursor
+ hasNextPage
+}
+
+fragment SlackIntegrationFields on SlackIntegration {
+ __typename
+ id
+ teamName
+ channelName
+}
+"""
+
+SLACK_INTEGRATIONS_BY_ENTITY_GQL = """
+query SlackIntegrationsByEntity($entityName: String!, $cursor: String, $perPage: Int) {
+ entity(name: $entityName) {
+ integrations(after: $cursor, first: $perPage) {
+ ...SlackIntegrationConnectionFields
+ }
+ }
+}
+
+fragment PageInfoFields on PageInfo {
+ endCursor
+ hasNextPage
+}
+
+fragment SlackIntegrationConnectionFields on IntegrationConnection {
+ __typename
+ pageInfo {
+ ...PageInfoFields
+ }
+ edges {
+ cursor
+ node {
+ __typename
+ ...SlackIntegrationFields
+ }
+ }
+}
+
+fragment SlackIntegrationFields on SlackIntegration {
+ __typename
+ id
+ teamName
+ channelName
+}
+"""
+
+GENERIC_WEBHOOK_INTEGRATIONS_BY_ENTITY_GQL = """
+query GenericWebhookIntegrationsByEntity($entityName: String!, $cursor: String, $perPage: Int) {
+ entity(name: $entityName) {
+ integrations(after: $cursor, first: $perPage) {
+ ...GenericWebhookIntegrationConnectionFields
+ }
+ }
+}
+
+fragment GenericWebhookIntegrationConnectionFields on IntegrationConnection {
+ __typename
+ pageInfo {
+ ...PageInfoFields
+ }
+ edges {
+ cursor
+ node {
+ __typename
+ ...GenericWebhookIntegrationFields
+ }
+ }
+}
+
+fragment GenericWebhookIntegrationFields on GenericWebhookIntegration {
+ __typename
+ id
+ name
+ urlEndpoint
+}
+
+fragment PageInfoFields on PageInfo {
+ endCursor
+ hasNextPage
+}
+"""
+
+CREATE_GENERIC_WEBHOOK_INTEGRATION_GQL = """
+mutation CreateGenericWebhookIntegration($params: CreateGenericWebhookIntegrationInput!) {
+ createGenericWebhookIntegration(input: $params) {
+ integration {
+ __typename
+ ...GenericWebhookIntegrationFields
+ }
+ }
+}
+
+fragment GenericWebhookIntegrationFields on GenericWebhookIntegration {
+ __typename
+ id
+ name
+ urlEndpoint
+}
+"""
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/slack_integrations_by_entity.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/slack_integrations_by_entity.py
new file mode 100644
index 0000000000000000000000000000000000000000..6576c2d585135b6171572682f4d69fef498e1a07
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/slack_integrations_by_entity.py
@@ -0,0 +1,22 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/automations/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from wandb._pydantic import GQLBase
+
+from .fragments import SlackIntegrationConnectionFields
+
+
+class SlackIntegrationsByEntity(GQLBase):
+ entity: Optional[SlackIntegrationsByEntityEntity]
+
+
+class SlackIntegrationsByEntityEntity(GQLBase):
+ integrations: Optional[SlackIntegrationConnectionFields]
+
+
+SlackIntegrationsByEntity.model_rebuild()
+SlackIntegrationsByEntityEntity.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/update_automation.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/update_automation.py
new file mode 100644
index 0000000000000000000000000000000000000000..12eb1be3549da444ca5532a0c02bede8e4def571
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_generated/update_automation.py
@@ -0,0 +1,17 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/automations/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from wandb._pydantic import GQLBase
+
+from .fragments import UpdateAutomationResult
+
+
+class UpdateAutomation(GQLBase):
+ result: Optional[UpdateAutomationResult]
+
+
+UpdateAutomation.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_utils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..c2b874d152496b7cd16b59fbabc65542cd95f7f6
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_utils.py
@@ -0,0 +1,235 @@
+from __future__ import annotations
+
+from typing import Any, Collection, Final, Optional, Protocol, TypedDict
+
+from pydantic import Field
+from typing_extensions import Annotated, Self, Unpack
+
+from wandb._pydantic import GQLBase, GQLId, computed_field, model_validator, to_json
+
+from ._filters import MongoLikeFilter
+from ._generated import (
+ CreateFilterTriggerInput,
+ QueueJobActionInput,
+ TriggeredActionConfig,
+ UpdateFilterTriggerInput,
+)
+from ._validators import to_input_action
+from .actions import (
+ ActionType,
+ DoNothing,
+ InputAction,
+ SavedAction,
+ SendNotification,
+ SendWebhook,
+)
+from .automations import Automation, NewAutomation
+from .events import EventType, InputEvent, RunMetricFilter, _WrappedSavedEventFilter
+from .scopes import AutomationScope, ScopeType
+
+EXCLUDED_INPUT_EVENTS: Final[Collection[EventType]] = frozenset(
+ {
+ EventType.UPDATE_ARTIFACT_ALIAS,
+ }
+)
+"""Event types that should not be assigned when creating/updating automations."""
+
+EXCLUDED_INPUT_ACTIONS: Final[Collection[ActionType]] = frozenset(
+ {
+ ActionType.QUEUE_JOB,
+ }
+)
+"""Action types that should not be assigned when creating/updating automations."""
+
+ALWAYS_SUPPORTED_EVENTS: Final[Collection[EventType]] = frozenset(
+ {
+ EventType.CREATE_ARTIFACT,
+ EventType.LINK_ARTIFACT,
+ EventType.ADD_ARTIFACT_ALIAS,
+ }
+)
+"""Event types that we can safely assume all contemporary server versions support."""
+
+ALWAYS_SUPPORTED_ACTIONS: Final[Collection[ActionType]] = frozenset(
+ {
+ ActionType.NOTIFICATION,
+ ActionType.GENERIC_WEBHOOK,
+ }
+)
+"""Action types that we can safely assume all contemporary server versions support."""
+
+
+class HasId(Protocol):
+ id: str
+
+
+def extract_id(obj: HasId | str) -> str:
+ return obj.id if hasattr(obj, "id") else obj
+
+
+# ---------------------------------------------------------------------------
+ACTION_CONFIG_KEYS: dict[ActionType, str] = {
+ ActionType.NOTIFICATION: "notification_action_input",
+ ActionType.GENERIC_WEBHOOK: "generic_webhook_action_input",
+ ActionType.NO_OP: "no_op_action_input",
+ ActionType.QUEUE_JOB: "queue_job_action_input",
+}
+
+
+class InputActionConfig(TriggeredActionConfig):
+ """A `TriggeredActionConfig` that prepares the action config for saving an automation."""
+
+ # NOTE: `QueueJobActionInput` for defining a Launch job is deprecated,
+ # so while it's allowed here to update EXISTING mutations, we don't
+ # currently expose it through the public API to create NEW automations.
+ queue_job_action_input: Optional[QueueJobActionInput] = None
+
+ notification_action_input: Optional[SendNotification] = None
+ generic_webhook_action_input: Optional[SendWebhook] = None
+ no_op_action_input: Optional[DoNothing] = None
+
+
+def prepare_action_config_input(obj: SavedAction | InputAction) -> dict[str, Any]:
+ """Prepare the `TriggeredActionConfig` input, nesting the action input inside the appropriate key.
+
+ This is necessary to conform to the schemas for:
+ - CreateFilterTriggerInput
+ - UpdateFilterTriggerInput
+ """
+ # Delegate to inner validators to convert SavedAction -> InputAction types, if needed.
+ obj = to_input_action(obj)
+ return InputActionConfig(**{ACTION_CONFIG_KEYS[obj.action_type]: obj}).model_dump()
+
+
+def prepare_event_filter_input(
+ obj: _WrappedSavedEventFilter | MongoLikeFilter | RunMetricFilter,
+) -> str:
+ """Prepare the `EventFilter` input, unnesting the filter if needed and serializing to JSON.
+
+ This is necessary to conform to the schemas for:
+ - CreateFilterTriggerInput
+ - UpdateFilterTriggerInput
+ """
+ # Input event filters are nested one level deeper than saved event filters.
+ # Note that this is NOT the case for run/run metric filters.
+ #
+ # Yes, this is confusing. It's also necessary to conform to under-the-hood
+ # schemas and logic in the backend.
+ filter_to_serialize = (
+ obj.filter if isinstance(obj, _WrappedSavedEventFilter) else obj
+ )
+ return to_json(filter_to_serialize)
+
+
+class WriteAutomationsKwargs(TypedDict, total=False):
+ """Keyword arguments that can be passed to create or update an automation."""
+
+ name: str
+ description: str
+ enabled: bool
+ scope: AutomationScope
+ event: InputEvent
+ action: InputAction
+
+
+class ValidatedCreateInput(GQLBase, extra="forbid", frozen=True):
+ """Validated automation parameters, prepared for creating a new automation.
+
+ Note: Users should never need to instantiate this class directly.
+ """
+
+ name: str
+ description: Optional[str] = None
+ enabled: bool = True
+
+ # ------------------------------------------------------------------------------
+ # Set on instantiation, but used to derive other fields and deliberately
+ # EXCLUDED from the final GraphQL request vars
+ event: Annotated[InputEvent, Field(exclude=True)]
+ action: Annotated[InputAction, Field(exclude=True)]
+
+ # ------------------------------------------------------------------------------
+ # Derived fields to match the input schemas
+ @computed_field
+ def scope_type(self) -> ScopeType:
+ return self.event.scope.scope_type
+
+ @computed_field
+ def scope_id(self) -> GQLId:
+ return self.event.scope.id
+
+ @computed_field
+ def triggering_event_type(self) -> EventType:
+ return self.event.event_type
+
+ @computed_field
+ def event_filter(self) -> str:
+ return prepare_event_filter_input(self.event.filter)
+
+ @computed_field
+ def triggered_action_type(self) -> ActionType:
+ return self.action.action_type
+
+ @computed_field
+ def triggered_action_config(self) -> dict[str, Any]:
+ return prepare_action_config_input(self.action)
+
+ # ------------------------------------------------------------------------------
+ # Custom validation
+ @model_validator(mode="after")
+ def _forbid_legacy_event_types(self) -> Self:
+ if (type_ := self.event.event_type) in EXCLUDED_INPUT_EVENTS:
+ raise ValueError(f"{type_!r} events cannot be assigned to automations.")
+ return self
+
+ @model_validator(mode="after")
+ def _forbid_legacy_action_types(self) -> Self:
+ if (type_ := self.action.action_type) in EXCLUDED_INPUT_ACTIONS:
+ raise ValueError(f"{type_!r} actions cannot be assigned to automations.")
+ return self
+
+
+def prepare_to_create(
+ obj: NewAutomation | None = None,
+ /,
+ **kwargs: Unpack[WriteAutomationsKwargs],
+) -> CreateFilterTriggerInput:
+ """Prepares the payload to create an automation in a GraphQL request."""
+ # Validate all input variables, and prepare as expected by the GraphQL request.
+ # - if an object is provided, override its fields with any keyword args
+ # - otherwise, instantiate from the keyword args
+
+ # NOTE: `exclude_none=True` drops fields that are still `None`.
+ #
+ # This assumes that `None` is good enough for now as a sentinel
+ # "unset" value. If this proves insufficient, revisit in the future,
+ # as it should be reasonably easy to implement a custom sentinel
+ # type later on.
+ obj_dict = {**obj.model_dump(exclude_none=True), **kwargs} if obj else kwargs
+ validated = ValidatedCreateInput(**obj_dict)
+ return CreateFilterTriggerInput.model_validate(validated)
+
+
+def prepare_to_update(
+ obj: Automation | None = None,
+ /,
+ **kwargs: Unpack[WriteAutomationsKwargs],
+) -> UpdateFilterTriggerInput:
+ """Prepares the payload to update an automation in a GraphQL request."""
+ # Validate all values:
+ # - if an object is provided, override its fields with any keyword args
+ # - otherwise, instantiate from the keyword args
+ v_obj = Automation(**{**dict(obj or {}), **kwargs})
+
+ return UpdateFilterTriggerInput(
+ id=v_obj.id,
+ name=v_obj.name,
+ description=v_obj.description,
+ enabled=v_obj.enabled,
+ scope_type=v_obj.scope.scope_type,
+ scope_id=v_obj.scope.id,
+ triggering_event_type=v_obj.event.event_type,
+ event_filter=prepare_event_filter_input(v_obj.event.filter),
+ triggered_action_type=v_obj.action.action_type,
+ triggered_action_config=prepare_action_config_input(v_obj.action),
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_validators.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_validators.py
new file mode 100644
index 0000000000000000000000000000000000000000..53aba390a439848d29645055294f312323ba429f
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/_validators.py
@@ -0,0 +1,185 @@
+from __future__ import annotations
+
+from enum import Enum
+from functools import singledispatch
+from itertools import chain
+from typing import Any, TypeVar
+
+from pydantic import BeforeValidator, Json, PlainSerializer
+from pydantic_core import PydanticUseDefault
+from typing_extensions import Annotated
+
+from wandb._pydantic import to_json
+
+from ._filters import And, FilterExpr, In, Nor, Not, NotIn, Op, Or
+
+T = TypeVar("T")
+
+
+def ensure_json(v: Any) -> Any:
+ """In case the incoming value isn't serialized JSON, reserialize it.
+
+ This lets us use `Json[...]` fields with values that are already deserialized.
+ """
+ # NOTE: Assumes that the deserialized type is not itself a string.
+ # Revisit this if we need to support deserialized types that are str/bytes.
+ return v if isinstance(v, (str, bytes)) else to_json(v)
+
+
+# Allow lenient instantiation/validation: incoming data may already be deserialized.
+SerializedToJson = Annotated[
+ Json[T], BeforeValidator(ensure_json), PlainSerializer(to_json)
+]
+
+
+class LenientStrEnum(str, Enum):
+ """A string enum allowing for case-insensitive lookups by value.
+
+ May include other internal customizations if needed.
+
+ Note: This is a bespoke, internal implementation and NOT intended as a
+ backport of `enum.StrEnum` from Python 3.11+.
+ """
+
+ def __repr__(self) -> str:
+ return self.name
+
+ @classmethod
+ def _missing_(cls, value: object) -> Any:
+ # Accept case-insensitive enum values
+ if isinstance(value, str):
+ v = value.lower()
+ return next((e for e in cls if e.value.lower() == v), None)
+ return None
+
+
+def default_if_none(v: Any) -> Any:
+ """A before-validator validator that coerces `None` to the default field value instead."""
+ # https://docs.pydantic.dev/2.11/api/pydantic_core/#pydantic_core.PydanticUseDefault
+ if v is None:
+ raise PydanticUseDefault
+ return v
+
+
+def upper_if_str(v: Any) -> Any:
+ return v.strip().upper() if isinstance(v, str) else v
+
+
+# ----------------------------------------------------------------------------
+def to_scope(v: Any) -> Any:
+ """Convert eligible objects, including pre-existing `wandb` types, to an automation scope."""
+ from wandb.apis.public import ArtifactCollection, Project
+
+ from .scopes import ProjectScope, _ArtifactPortfolioScope, _ArtifactSequenceScope
+
+ if isinstance(v, Project):
+ return ProjectScope(id=v.id, name=v.name)
+ if isinstance(v, ArtifactCollection):
+ cls = _ArtifactSequenceScope if v.is_sequence() else _ArtifactPortfolioScope
+ return cls(id=v.id, name=v.name)
+ return v
+
+
+def to_saved_action(v: Any) -> Any:
+ """If necessary (and possible), convert the object to a saved action."""
+ from .actions import (
+ DoNothing,
+ SavedNoOpAction,
+ SavedNotificationAction,
+ SavedWebhookAction,
+ SendNotification,
+ SendWebhook,
+ )
+
+ if isinstance(v, SendNotification):
+ return SavedNotificationAction(
+ integration={"id": v.integration_id},
+ **v.model_dump(exclude={"integration_id"}),
+ )
+ if isinstance(v, SendWebhook):
+ return SavedWebhookAction(
+ integration={"id": v.integration_id},
+ **v.model_dump(exclude={"integration_id"}),
+ )
+ if isinstance(v, DoNothing):
+ return SavedNoOpAction.model_validate(v)
+
+ return v
+
+
+def to_input_action(v: Any) -> Any:
+ """If necessary (and possible), convert the object to an input action."""
+ from .actions import (
+ DoNothing,
+ SavedNoOpAction,
+ SavedNotificationAction,
+ SavedWebhookAction,
+ SendNotification,
+ SendWebhook,
+ )
+
+ if isinstance(v, SavedNotificationAction):
+ return SendNotification(
+ integration_id=v.integration.id,
+ **v.model_dump(exclude={"integration"}),
+ )
+ if isinstance(v, SavedWebhookAction):
+ return SendWebhook(
+ integration_id=v.integration.id,
+ **v.model_dump(exclude={"integration"}),
+ )
+ if isinstance(v, SavedNoOpAction):
+ return DoNothing.model_validate(v)
+
+ return v
+
+
+# ----------------------------------------------------------------------------
+@singledispatch
+def simplify_op(op: Op | FilterExpr) -> Op | FilterExpr:
+ """Simplify a MongoDB filter by removing and unnesting redundant operators."""
+ return op
+
+
+@simplify_op.register
+def _(op: And) -> Op:
+ # {"$and": []} -> {"$and": []}
+ if not (args := op.and_):
+ return op
+
+ # {"$and": [op]} -> op
+ if len(args) == 1:
+ return simplify_op(args[0])
+
+ # {"$and": [op, {"$and": [op2, ...]}]} -> {"$and": [op, op2, ...]}
+ flattened = chain.from_iterable(x.and_ if isinstance(x, And) else [x] for x in args)
+ return And(and_=map(simplify_op, flattened))
+
+
+@simplify_op.register
+def _(op: Or) -> Op:
+ # {"$or": []} -> {"$or": []}
+ if not (args := op.or_):
+ return op
+
+ # {"$or": [op]} -> op
+ if len(args) == 1:
+ return simplify_op(args[0])
+
+ # {"$or": [op, {"$or": [op2, ...]}]} -> {"$or": [op, op2, ...]}
+ flattened = chain.from_iterable(x.or_ if isinstance(x, Or) else [x] for x in args)
+ return Or(or_=map(simplify_op, flattened))
+
+
+@simplify_op.register
+def _(op: Not) -> Op:
+ inner = op.not_
+
+ # {"$not": {"$not": op}} -> op
+ # {"$not": {"$or": [op, ...]}} -> {"$nor": [op, ...]}
+ # {"$not": {"$nor": [op, ...]}} -> {"$or": [op, ...]}
+ # {"$not": {"$in": [op, ...]}} -> {"$nin": [op, ...]}
+ # {"$not": {"$nin": [op, ...]}} -> {"$in": [op, ...]}
+ if isinstance(inner, (Not, Or, Nor, In, NotIn)):
+ return simplify_op(~inner)
+ return Not(not_=simplify_op(inner))
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/actions.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/actions.py
new file mode 100644
index 0000000000000000000000000000000000000000..110970355d41d42f82d9ba541e449b07bb7010a5
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/actions.py
@@ -0,0 +1,220 @@
+"""Actions that are triggered by W&B Automations."""
+
+from __future__ import annotations
+
+from typing import Any, Literal, Optional, Union
+
+from pydantic import BeforeValidator, Field
+from typing_extensions import Annotated, Self, get_args
+
+from wandb._pydantic import GQLBase, GQLId, Typename
+from wandb._strutils import nameof
+
+from ._generated import (
+ AlertSeverity,
+ GenericWebhookActionFields,
+ GenericWebhookActionInput,
+ NoOpActionFields,
+ NoOpTriggeredActionInput,
+ NotificationActionFields,
+ NotificationActionInput,
+ QueueJobActionFields,
+)
+from ._validators import (
+ LenientStrEnum,
+ SerializedToJson,
+ default_if_none,
+ to_input_action,
+ to_saved_action,
+ upper_if_str,
+)
+from .integrations import SlackIntegration, WebhookIntegration
+
+
+# NOTE: Name shortened for readability and defined publicly for easier access
+class ActionType(LenientStrEnum):
+ """The type of action triggered by an automation."""
+
+ QUEUE_JOB = "QUEUE_JOB" # NOTE: Deprecated for creation
+ NOTIFICATION = "NOTIFICATION"
+ GENERIC_WEBHOOK = "GENERIC_WEBHOOK"
+ NO_OP = "NO_OP"
+
+
+# ------------------------------------------------------------------------------
+# Saved types: for parsing response data from saved automations
+
+
+# NOTE: `QueueJobActionInput` for defining a Launch job is deprecated,
+# so while we allow parsing it from previously saved Automations, we deliberately
+# don't currently expose it in the API for creating automations.
+class SavedLaunchJobAction(QueueJobActionFields):
+ action_type: Literal[ActionType.QUEUE_JOB] = ActionType.QUEUE_JOB
+
+
+# FIXME: Find a better place to put these OR a better way to handle the
+# conversion from `InputAction` -> `SavedAction`.
+#
+# Necessary placeholder class defs for converting:
+# - `SendNotification -> SavedNotificationAction`
+# - `SendWebhook -> SavedWebhookAction`
+#
+# The "input" types (`Send{Notification,Webhook}`) will only have an `integration_id`,
+# and we don't want/need to fetch the other `{Slack,Webhook}Integration` fields if
+# we can avoid it.
+class _SavedActionSlackIntegration(GQLBase, extra="allow"):
+ typename__: Typename[Literal["SlackIntegration"]] = "SlackIntegration"
+ id: GQLId
+
+
+class _SavedActionWebhookIntegration(GQLBase, extra="allow"):
+ typename__: Typename[Literal["GenericWebhookIntegration"]] = (
+ "GenericWebhookIntegration"
+ )
+ id: GQLId
+
+
+class SavedNotificationAction(NotificationActionFields):
+ action_type: Literal[ActionType.NOTIFICATION] = ActionType.NOTIFICATION
+ integration: _SavedActionSlackIntegration
+
+
+class SavedWebhookAction(GenericWebhookActionFields):
+ action_type: Literal[ActionType.GENERIC_WEBHOOK] = ActionType.GENERIC_WEBHOOK
+ integration: _SavedActionWebhookIntegration
+
+ # We override the type of the `requestPayload` field since the original GraphQL
+ # schema (and generated class) effectively defines it as a string, when we know
+ # and need to anticipate the expected structure of the JSON-serialized data.
+ request_payload: Annotated[
+ Optional[SerializedToJson[dict[str, Any]]],
+ Field(alias="requestPayload"),
+ ] = None # type: ignore[assignment]
+
+
+class SavedNoOpAction(NoOpActionFields, frozen=True):
+ action_type: Literal[ActionType.NO_OP] = ActionType.NO_OP
+
+ no_op: Annotated[bool, BeforeValidator(default_if_none)] = True
+ """Placeholder field, only needed to conform to schema requirements.
+
+ There should never be a need to set this field explicitly, as its value is ignored.
+ """
+
+
+# for type annotations
+SavedAction = Annotated[
+ Union[
+ SavedLaunchJobAction,
+ SavedNotificationAction,
+ SavedWebhookAction,
+ SavedNoOpAction,
+ ],
+ BeforeValidator(to_saved_action),
+ Field(discriminator="typename__"),
+]
+# for runtime type checks
+SavedActionTypes: tuple[type, ...] = get_args(SavedAction.__origin__) # type: ignore[attr-defined]
+
+
+# ------------------------------------------------------------------------------
+# Input types: for creating or updating automations
+class _BaseActionInput(GQLBase):
+ action_type: Annotated[ActionType, Field(frozen=True)]
+ """The kind of action to be triggered."""
+
+
+class SendNotification(_BaseActionInput, NotificationActionInput):
+ """Defines an automation action that sends a (Slack) notification."""
+
+ action_type: Literal[ActionType.NOTIFICATION] = ActionType.NOTIFICATION
+
+ integration_id: GQLId
+ """The ID of the Slack integration that will be used to send the notification."""
+
+ # Note: Validation aliases are meant to provide continuity with prior `wandb.alert()` API.
+ title: str = ""
+ """The title of the sent notification."""
+
+ message: Annotated[str, Field(validation_alias="text")] = ""
+ """The message body of the sent notification."""
+
+ severity: Annotated[
+ AlertSeverity,
+ BeforeValidator(upper_if_str), # Be helpful by ensuring uppercase strings
+ Field(validation_alias="level"),
+ ] = AlertSeverity.INFO
+ """The severity (`INFO`, `WARN`, `ERROR`) of the sent notification."""
+
+ @classmethod
+ def from_integration(
+ cls,
+ integration: SlackIntegration,
+ *,
+ title: str = "",
+ text: str = "",
+ level: AlertSeverity = AlertSeverity.INFO,
+ ) -> Self:
+ """Define a notification action that sends to the given (Slack) integration."""
+ return cls(
+ integration_id=integration.id,
+ title=title,
+ message=text,
+ severity=level,
+ )
+
+
+class SendWebhook(_BaseActionInput, GenericWebhookActionInput):
+ """Defines an automation action that sends a webhook request."""
+
+ action_type: Literal[ActionType.GENERIC_WEBHOOK] = ActionType.GENERIC_WEBHOOK
+
+ integration_id: GQLId
+ """The ID of the webhook integration that will be used to send the request."""
+
+ # overrides the generated field type to parse/serialize JSON strings
+ request_payload: Optional[SerializedToJson[dict[str, Any]]] = Field( # type: ignore[assignment]
+ default=None, alias="requestPayload"
+ )
+ """The payload, possibly with template variables, to send in the webhook request."""
+
+ @classmethod
+ def from_integration(
+ cls,
+ integration: WebhookIntegration,
+ *,
+ payload: Optional[SerializedToJson[dict[str, Any]]] = None,
+ ) -> Self:
+ """Define a webhook action that sends to the given (webhook) integration."""
+ return cls(integration_id=integration.id, request_payload=payload)
+
+
+class DoNothing(_BaseActionInput, NoOpTriggeredActionInput, frozen=True):
+ """Defines an automation action that intentionally does nothing."""
+
+ action_type: Literal[ActionType.NO_OP] = ActionType.NO_OP
+
+ no_op: Annotated[bool, BeforeValidator(default_if_none)] = True
+ """Placeholder field which exists only to satisfy backend schema requirements.
+
+ There should never be a need to set this field explicitly, as its value is ignored.
+ """
+
+
+# for type annotations
+InputAction = Annotated[
+ Union[
+ SendNotification,
+ SendWebhook,
+ DoNothing,
+ ],
+ BeforeValidator(to_input_action),
+ Field(discriminator="action_type"),
+]
+# for runtime type checks
+InputActionTypes: tuple[type, ...] = get_args(InputAction.__origin__) # type: ignore[attr-defined]
+
+__all__ = [
+ "ActionType",
+ *(nameof(cls) for cls in InputActionTypes),
+]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/automations.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/automations.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ebd34046e90b651c79c2b8ab857e88108216561
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/automations.py
@@ -0,0 +1,85 @@
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Optional
+
+from pydantic import Field
+from typing_extensions import Annotated
+
+from wandb._pydantic import GQLBase, GQLId
+
+from ._generated import TriggerFields
+from .actions import InputAction, SavedAction
+from .events import InputEvent, SavedEvent
+from .scopes import AutomationScope
+
+
+# ------------------------------------------------------------------------------
+# Saved types: for parsing response data from saved automations
+class Automation(TriggerFields):
+ """A local instance of a saved W&B automation."""
+
+ id: GQLId
+
+ created_at: Annotated[datetime, Field(repr=False, frozen=True, alias="createdAt")]
+ """The date and time when this automation was created."""
+
+ updated_at: Annotated[
+ Optional[datetime], Field(repr=False, frozen=True, alias="updatedAt")
+ ] = None
+ """The date and time when this automation was last updated, if applicable."""
+
+ name: str
+ """The name of this automation."""
+
+ description: Optional[str]
+ """An optional description of this automation."""
+
+ enabled: bool
+ """Whether this automation is enabled. Only enabled automations will trigger."""
+
+ event: SavedEvent
+ """The event that will trigger this automation."""
+
+ scope: AutomationScope
+ """The scope in which the triggering event must occur."""
+
+ action: SavedAction
+ """The action that will execute when this automation is triggered."""
+
+
+class NewAutomation(GQLBase, extra="forbid", validate_default=False):
+ """A new automation to be created."""
+
+ name: Optional[str] = None
+ """The name of this automation."""
+
+ description: Optional[str] = None
+ """An optional description of this automation."""
+
+ enabled: Optional[bool] = None
+ """Whether this automation is enabled. Only enabled automations will trigger."""
+
+ event: Optional[InputEvent] = None
+ """The event that will trigger this automation."""
+
+ # Ensure that the event and its scope are always consistent, if the event is set.
+ @property
+ def scope(self) -> Optional[AutomationScope]:
+ """The scope in which the triggering event must occur."""
+ return self.event.scope if self.event else None
+
+ @scope.setter
+ def scope(self, value: AutomationScope) -> None:
+ if self.event is None:
+ raise ValueError("Cannot set `scope` for an automation with no `event`")
+ self.event.scope = value
+
+ action: Optional[InputAction] = None
+ """The action that will execute when this automation is triggered."""
+
+
+__all__ = [
+ "Automation",
+ "NewAutomation",
+]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/events.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/events.py
new file mode 100644
index 0000000000000000000000000000000000000000..218e69a549328480ee90b7816b51fea603013890
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/events.py
@@ -0,0 +1,284 @@
+"""Events that trigger W&B Automations."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Literal, Optional, Union
+
+from pydantic import Field
+from typing_extensions import Annotated, Self, get_args
+
+from wandb._pydantic import (
+ GQLBase,
+ field_validator,
+ model_validator,
+ pydantic_isinstance,
+)
+from wandb._strutils import nameof
+
+from ._filters import And, MongoLikeFilter, Or
+from ._filters.expressions import FilterableField
+from ._filters.run_metrics import MetricChangeFilter, MetricThresholdFilter, MetricVal
+from ._generated import FilterEventFields
+from ._validators import LenientStrEnum, SerializedToJson, ensure_json, simplify_op
+from .actions import InputAction, InputActionTypes, SavedActionTypes
+from .scopes import ArtifactCollectionScope, AutomationScope, ProjectScope
+
+if TYPE_CHECKING:
+ from .automations import NewAutomation
+
+
+# NOTE: Re-defined publicly with a more readable name for easier access
+class EventType(LenientStrEnum):
+ """The type of event that triggers an automation."""
+
+ # ---------------------------------------------------------------------------
+ # Events triggered by GraphQL mutations
+ UPDATE_ARTIFACT_ALIAS = "UPDATE_ARTIFACT_ALIAS" # NOTE: Avoid in new automations
+
+ CREATE_ARTIFACT = "CREATE_ARTIFACT"
+ ADD_ARTIFACT_ALIAS = "ADD_ARTIFACT_ALIAS"
+ LINK_ARTIFACT = "LINK_MODEL"
+ # Note: "LINK_MODEL" is the (legacy) value expected by the backend, but we
+ # name it "LINK_ARTIFACT" here in the public API for clarity and consistency.
+
+ # ---------------------------------------------------------------------------
+ # Events triggered by Run conditions
+ RUN_METRIC_THRESHOLD = "RUN_METRIC"
+ RUN_METRIC_CHANGE = "RUN_METRIC_CHANGE"
+
+
+# ------------------------------------------------------------------------------
+# Saved types: for parsing response data from saved automations
+
+
+# Note: In GQL responses containing saved automation data, the filter is wrapped in an extra `filter` key.
+class _WrappedSavedEventFilter(GQLBase): # from: TriggeringFilterEvent
+ filter: SerializedToJson[MongoLikeFilter] = And()
+
+
+class _WrappedMetricFilter(GQLBase): # from: RunMetricFilter
+ threshold_filter: Optional[MetricThresholdFilter] = None
+ change_filter: Optional[MetricChangeFilter] = None
+
+ @model_validator(mode="before")
+ @classmethod
+ def _wrap_metric_filter(cls, v: Any) -> Any:
+ if pydantic_isinstance(v, MetricThresholdFilter):
+ return cls(threshold_filter=v)
+ if pydantic_isinstance(v, MetricChangeFilter):
+ return cls(change_filter=v)
+ return v
+
+ @model_validator(mode="after")
+ def _ensure_exactly_one_set(self) -> Self:
+ set_fields = [name for name, val in self if (val is not None)]
+
+ if not set_fields:
+ all_names = ", ".join(map(repr, type(self).model_fields))
+ raise ValueError(f"Expected one of: {all_names}")
+
+ if len(set_fields) > 1:
+ set_names = ", ".join(map(repr, set_fields))
+ raise ValueError(f"Expected exactly one metric filter, got: {set_names}")
+
+ return self
+
+ @property
+ def event_type(self) -> EventType:
+ if self.threshold_filter is not None:
+ return EventType.RUN_METRIC_THRESHOLD
+ if self.change_filter is not None:
+ return EventType.RUN_METRIC_CHANGE
+ raise RuntimeError("Expected one of: `threshold_filter` or `change_filter`")
+
+
+class RunMetricFilter(GQLBase): # from: TriggeringRunMetricEvent
+ run: Annotated[SerializedToJson[MongoLikeFilter], Field(alias="run_filter")] = And()
+ metric: Annotated[_WrappedMetricFilter, Field(alias="run_metric_filter")]
+
+ # ------------------------------------------------------------------------------
+ legacy_metric_filter: Annotated[
+ Optional[SerializedToJson[MetricThresholdFilter]],
+ Field(alias="metric_filter", deprecated=True),
+ ] = None
+ """Deprecated legacy field that was previously used to define run metric threshold events.
+
+ For new automations, use the `metric` field (`run_metric_filter` JSON alias) instead.
+ """
+
+ @model_validator(mode="before")
+ @classmethod
+ def _wrap_metric_filter(cls, v: Any) -> Any:
+ if pydantic_isinstance(v, (MetricThresholdFilter, MetricChangeFilter)):
+ # If only an (unnested) metric filter is given, nest it under the
+ # `metric` field, delegating to inner validator(s) for further
+ # wrapping/nesting, if needed.
+ # This is necessary to conform to the expected backend schema.
+ return cls(metric=v)
+ return v
+
+ @field_validator("run", mode="after")
+ def _wrap_run_filter(cls, v: MongoLikeFilter) -> Any:
+ v_new = simplify_op(v)
+ return v_new if pydantic_isinstance(v_new, And) else And(and_=[v_new])
+
+
+class SavedEvent(FilterEventFields): # from: FilterEventTriggeringCondition
+ """A triggering event from a saved automation."""
+
+ event_type: Annotated[EventType, Field(frozen=True)] # type: ignore[assignment]
+
+ # We override the type of the `filter` field in order to enforce the expected
+ # structure for the JSON data when validating and serializing.
+ filter: SerializedToJson[Union[_WrappedSavedEventFilter, RunMetricFilter]]
+ """The condition(s) under which this event triggers an automation."""
+
+
+# ------------------------------------------------------------------------------
+# Input types: for creating or updating automations
+
+
+# Note: The GQL input for "eventFilter" does NOT wrap the filter in an extra `filter` key, unlike the
+# eventFilter returned in responses for saved automations.
+class _BaseEventInput(GQLBase):
+ event_type: EventType
+
+ scope: AutomationScope
+ """The scope of the event."""
+
+ filter: SerializedToJson[Any]
+
+ def then(self, action: InputAction) -> NewAutomation:
+ """Define a new Automation in which this event triggers the given action."""
+ from .automations import NewAutomation
+
+ if isinstance(action, (InputActionTypes, SavedActionTypes)):
+ return NewAutomation(event=self, action=action)
+
+ raise TypeError(f"Expected a valid action, got: {nameof(type(action))!r}")
+
+ def __rshift__(self, other: InputAction) -> NewAutomation:
+ """Implements `event >> action` to define an Automation with this event and action."""
+ return self.then(other)
+
+
+# ------------------------------------------------------------------------------
+# Events that trigger on specific mutations in the backend
+class _BaseMutationEventInput(_BaseEventInput):
+ filter: SerializedToJson[MongoLikeFilter] = And()
+ """Additional condition(s), if any, that must be met for this event to trigger an automation."""
+
+ @field_validator("filter", mode="after")
+ def _wrap_filter(cls, v: Any) -> Any:
+ """Ensure the given filter is wrapped like: `{"$or": [{"$and": []}]}`.
+
+ This is awkward but necessary, because the frontend expects this format.
+ """
+ v_new = simplify_op(v)
+ v_new = v_new if pydantic_isinstance(v_new, And) else And(and_=[v_new])
+ return Or(or_=[v_new])
+
+
+class OnLinkArtifact(_BaseMutationEventInput):
+ """A new artifact is linked to a collection."""
+
+ event_type: Literal[EventType.LINK_ARTIFACT] = EventType.LINK_ARTIFACT
+
+
+class OnAddArtifactAlias(_BaseMutationEventInput):
+ """A new alias is assigned to an artifact."""
+
+ event_type: Literal[EventType.ADD_ARTIFACT_ALIAS] = EventType.ADD_ARTIFACT_ALIAS
+
+
+class OnCreateArtifact(_BaseMutationEventInput):
+ """A new artifact is created."""
+
+ event_type: Literal[EventType.CREATE_ARTIFACT] = EventType.CREATE_ARTIFACT
+
+ scope: ArtifactCollectionScope
+ """The scope of the event: only artifact collections are valid scopes for this event."""
+
+
+# ------------------------------------------------------------------------------
+# Events that trigger on run conditions
+class _BaseRunEventInput(_BaseEventInput):
+ scope: ProjectScope
+ """The scope of the event: only projects are valid scopes for this event."""
+
+
+class OnRunMetric(_BaseRunEventInput):
+ """A run metric satisfies a user-defined condition."""
+
+ event_type: Literal[EventType.RUN_METRIC_THRESHOLD, EventType.RUN_METRIC_CHANGE]
+
+ filter: SerializedToJson[RunMetricFilter]
+ """Run and/or metric condition(s) that must be satisfied for this event to trigger an automation."""
+
+ @model_validator(mode="before")
+ @classmethod
+ def _infer_event_type(cls, data: Any) -> Any:
+ """Infer the event type at validation time from the inner filter.
+
+ This allows this class to accommodate both "threshold" and "change" metric
+ filter types, which are can only be determined after parsing and validating
+ the inner JSON data.
+ """
+ if isinstance(data, dict) and (raw_filter := data.get("filter")):
+ # At this point, `raw_filter` may or may not be JSON-serialized
+ parsed_filter = RunMetricFilter.model_validate_json(ensure_json(raw_filter))
+ return {**data, "event_type": parsed_filter.metric.event_type}
+
+ return data
+
+
+# for type annotations
+InputEvent = Annotated[
+ Union[
+ OnLinkArtifact,
+ OnAddArtifactAlias,
+ OnCreateArtifact,
+ OnRunMetric,
+ ],
+ Field(discriminator="event_type"),
+]
+# for runtime type checks
+InputEventTypes: tuple[type, ...] = get_args(InputEvent.__origin__) # type: ignore[attr-defined]
+
+
+# ----------------------------------------------------------------------------
+
+
+class RunEvent:
+ name = FilterableField(server_name="display_name")
+ # `Run.name` is actually filtered on `Run.display_name` in the backend.
+ # We can't reasonably expect users to know this a priori, so
+ # automatically fix it here.
+
+ @staticmethod
+ def metric(name: str) -> MetricVal:
+ """Define a metric filter condition."""
+ return MetricVal(name=name)
+
+
+class ArtifactEvent:
+ alias = FilterableField()
+
+
+MetricThresholdFilter.model_rebuild()
+RunMetricFilter.model_rebuild()
+_WrappedSavedEventFilter.model_rebuild()
+
+OnLinkArtifact.model_rebuild()
+OnAddArtifactAlias.model_rebuild()
+OnCreateArtifact.model_rebuild()
+OnRunMetric.model_rebuild()
+
+__all__ = [
+ "EventType",
+ *(nameof(cls) for cls in InputEventTypes),
+ "RunEvent",
+ "ArtifactEvent",
+ "MetricThresholdFilter",
+ "MetricChangeFilter",
+]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/integrations.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/integrations.py
new file mode 100644
index 0000000000000000000000000000000000000000..b296d6d82830ca02483bbd367478c517f1d749a4
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/integrations.py
@@ -0,0 +1,45 @@
+from typing import Union
+
+from pydantic import Field
+from typing_extensions import Annotated
+
+from wandb._pydantic import GQLBase
+from wandb.automations._generated import (
+ GenericWebhookIntegrationFields,
+ SlackIntegrationFields,
+)
+
+
+class SlackIntegration(SlackIntegrationFields):
+ team_name: str
+ """The name of the Slack workspace (not the W&B team) that this integration is associated with."""
+
+ channel_name: str
+ """The name of the Slack channel that this integration will post messages to."""
+
+
+class WebhookIntegration(GenericWebhookIntegrationFields):
+ name: str
+ """The name of this webhook integration."""
+
+ url_endpoint: str
+ """The URL that this webhook will POST events to."""
+
+
+Integration = Annotated[
+ Union[SlackIntegration, WebhookIntegration],
+ Field(discriminator="typename__"),
+]
+
+
+# For parsing integration instances from paginated responses
+class _IntegrationEdge(GQLBase):
+ cursor: str
+ node: Integration
+
+
+__all__ = [
+ "Integration",
+ "SlackIntegration",
+ "WebhookIntegration",
+]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/scopes.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/scopes.py
new file mode 100644
index 0000000000000000000000000000000000000000..630a67bcc3bd63f22b2a653be31889a9ea631527
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/automations/scopes.py
@@ -0,0 +1,78 @@
+"""Scopes in which a W&B Automation can be triggered."""
+
+from __future__ import annotations
+
+from typing import Literal, Union
+
+from pydantic import BeforeValidator, Field
+from typing_extensions import Annotated, TypeAlias, get_args
+
+from wandb._pydantic import GQLBase
+from wandb.automations._generated import (
+ ArtifactPortfolioScopeFields,
+ ArtifactSequenceScopeFields,
+ ProjectScopeFields,
+)
+
+from ._validators import LenientStrEnum, to_scope
+
+
+# NOTE: Re-defined publicly with a more readable name for easier access
+class ScopeType(LenientStrEnum):
+ """The kind of scope that triggers an automation."""
+
+ PROJECT = "PROJECT"
+ ARTIFACT_COLLECTION = "ARTIFACT_COLLECTION"
+
+
+class _BaseScope(GQLBase):
+ scope_type: Annotated[ScopeType, Field(frozen=True)]
+
+
+class _ArtifactSequenceScope(_BaseScope, ArtifactSequenceScopeFields):
+ """An automation scope defined by a specific `ArtifactSequence`."""
+
+ scope_type: Literal[ScopeType.ARTIFACT_COLLECTION] = ScopeType.ARTIFACT_COLLECTION
+
+
+class _ArtifactPortfolioScope(_BaseScope, ArtifactPortfolioScopeFields):
+ """An automation scope defined by a specific `ArtifactPortfolio` (e.g. a registry collection)."""
+
+ scope_type: Literal[ScopeType.ARTIFACT_COLLECTION] = ScopeType.ARTIFACT_COLLECTION
+
+
+# for type annotations
+ArtifactCollectionScope = Annotated[
+ Union[_ArtifactSequenceScope, _ArtifactPortfolioScope],
+ BeforeValidator(to_scope),
+ Field(discriminator="typename__"),
+]
+"""An automation scope defined by a specific `ArtifactCollection`."""
+
+# for runtime type checks
+ArtifactCollectionScopeTypes: tuple[type, ...] = get_args(
+ ArtifactCollectionScope.__origin__ # type: ignore[attr-defined]
+)
+
+
+class ProjectScope(_BaseScope, ProjectScopeFields):
+ """An automation scope defined by a specific `Project`."""
+
+ scope_type: Literal[ScopeType.PROJECT] = ScopeType.PROJECT
+
+
+# for type annotations
+AutomationScope: TypeAlias = Annotated[
+ Union[_ArtifactSequenceScope, _ArtifactPortfolioScope, ProjectScope],
+ BeforeValidator(to_scope),
+ Field(discriminator="typename__"),
+]
+# for runtime type checks
+AutomationScopeTypes: tuple[type, ...] = get_args(AutomationScope.__origin__) # type: ignore[attr-defined]
+
+
+__all__ = [
+ "ScopeType",
+ "ArtifactCollectionScope",
+ "ProjectScope",
+]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/beta/workflows.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/beta/workflows.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e3b98cc70fbb27da48a72b1a7c7a9797fabe027
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/beta/workflows.py
@@ -0,0 +1,324 @@
+from __future__ import annotations
+
+import json
+import os
+import warnings
+from typing import Any
+
+from typing_extensions import deprecated
+
+import wandb
+from wandb.data_types import WBValue, _SavedModel
+from wandb.proto.wandb_deprecated import Deprecated
+from wandb.sdk import wandb_setup
+from wandb.sdk.artifacts.artifact import Artifact
+from wandb.sdk.artifacts.artifact_manifest_entry import ArtifactManifestEntry
+from wandb.sdk.lib.deprecate import deprecate as wandb_deprecate
+
+warnings.warn(
+ message=f"The {__name__!r} module is deprecated and will be removed in a future version. Please use the equivalent 'wandb.Run' methods instead.",
+ category=DeprecationWarning,
+ stacklevel=2,
+)
+
+
+def _add_any(
+ artifact: Artifact,
+ path_or_obj: str | ArtifactManifestEntry | WBValue, # todo: add dataframe
+ name: str | None,
+) -> Any:
+ """Add an object to an artifact.
+
+ High-level wrapper to add object(s) to an artifact - calls any of the .add* methods
+ under Artifact depending on the type of object that's passed in. This will probably
+ be moved to the Artifact class in the future.
+
+ Args:
+ artifact: artifact created with `wandb.Artifact(...)`
+ path_or_obj: either a str or valid object which indicates what to add
+ to an artifact.
+ name: the name of the object which is added to an artifact.
+
+ Returns:
+ Type[Any] - Union[None, ArtifactManifestEntry, etc]
+
+ """
+ if isinstance(path_or_obj, ArtifactManifestEntry):
+ return artifact.add_reference(path_or_obj, name)
+ elif isinstance(path_or_obj, WBValue):
+ return artifact.add(path_or_obj, name)
+ elif isinstance(path_or_obj, str):
+ if os.path.isdir(path_or_obj):
+ return artifact.add_dir(path_or_obj)
+ elif os.path.isfile(path_or_obj):
+ return artifact.add_file(path_or_obj)
+ else:
+ with artifact.new_file(name) as f:
+ f.write(json.dumps(path_or_obj, sort_keys=True))
+ else:
+ raise TypeError(
+ "Expected `path_or_obj` to be instance of `ArtifactManifestEntry`,"
+ f" `WBValue`, or `str, found {type(path_or_obj)}"
+ )
+
+
+def _log_artifact_version(
+ name: str,
+ type: str,
+ entries: dict[str, str | ArtifactManifestEntry | WBValue],
+ aliases: str | list[str] | None = None,
+ description: str | None = None,
+ metadata: dict | None = None,
+ project: str | None = None,
+ scope_project: bool | None = None,
+ job_type: str = "auto",
+) -> Artifact:
+ """Create an artifact, populate it, and log it with a run.
+
+ If a run is not present, we create one.
+
+ Args:
+ name: `str` - name of the artifact. If not scoped to a project, name will be
+ suffixed by "-{run_id}".
+ type: `str` - type of the artifact, used in the UI to group artifacts of the
+ same type.
+ entries: `Dict` - dictionary containing the named objects we want added to this
+ artifact.
+ description: `str` - text description of artifact.
+ metadata: `Dict` - users can pass in artifact-specific metadata here, will be
+ visible in the UI.
+ project: `str` - project under which to place this artifact.
+ scope_project: `bool` - if True, we will not suffix `name` with "-{run_id}".
+ job_type: `str` - Only applied if run is not present and we create one.
+ Used to identify runs of a certain job type, i.e "evaluation".
+
+ Returns:
+ Artifact
+
+ """
+ run = wandb_setup.singleton().most_recent_active_run
+ if not run:
+ run = wandb.init(
+ project=project,
+ job_type=job_type,
+ settings=wandb.Settings(silent=True),
+ )
+
+ if not scope_project:
+ name = f"{name}-{run.id}"
+
+ if metadata is None:
+ metadata = {}
+
+ art = wandb.Artifact(name, type, description, metadata, False, None)
+
+ for path in entries:
+ _add_any(art, entries[path], path)
+
+ # "latest" should always be present as an alias
+ aliases = wandb.util._resolve_aliases(aliases)
+ run.log_artifact(art, aliases=aliases)
+
+ return art
+
+
+_LOG_MODEL_DEPRECATION_MSG = "`log_model` is deprecated and will be removed in a future version. Please use `Run.log_artifact` instead."
+
+
+@deprecated(_LOG_MODEL_DEPRECATION_MSG)
+def log_model(
+ model_obj: Any,
+ name: str = "model",
+ aliases: str | list[str] | None = None,
+ description: str | None = None,
+ metadata: dict | None = None,
+ project: str | None = None,
+ scope_project: bool | None = None,
+ **kwargs: dict[str, Any],
+) -> _SavedModel:
+ """Log a model object to enable model-centric workflows in the UI.
+
+ Supported frameworks include PyTorch, Keras, Tensorflow, Scikit-learn, etc. Under
+ the hood, we create a model artifact, bind it to the run that produced this model,
+ associate it with the latest metrics logged with `run.log(...)` and more.
+
+ Args:
+ model_obj: any model object created with the following ML frameworks: PyTorch,
+ Keras, Tensorflow, Scikit-learn. name: `str` - name of the model artifact
+ that will be created to house this model_obj.
+ aliases: `str, List[str]` - optional alias(es) that will be applied on this
+ model and allow for unique identification. The alias "latest" will always be
+ applied to the latest version of a model.
+ description: `str` - text description/notes about the model - will be visible in
+ the Model Card UI.
+ metadata: `Dict` - model-specific metadata goes here - will be visible the UI.
+ project: `str` - project under which to place this artifact.
+ scope_project: `bool` - If true, name of this model artifact will not be
+ suffixed by `-{run_id}`.
+
+ Returns:
+ _SavedModel instance
+
+ Example:
+ ```python
+ import torch.nn as nn
+ import torch.nn.functional as F
+
+
+ class Net(nn.Module):
+ def __init__(self):
+ super(Net, self).__init__()
+ self.fc1 = nn.Linear(10, 10)
+
+ def forward(self, x):
+ x = self.fc1(x)
+ x = F.relu(x)
+ return x
+
+
+ model = Net()
+ sm = log_model(model, "my-simple-model", aliases=["best"])
+ ```
+
+ """
+ wandb_deprecate(
+ field_name=Deprecated.beta__workflows__log_model,
+ warning_message=_LOG_MODEL_DEPRECATION_MSG,
+ )
+
+ model = _SavedModel.init(model_obj, **kwargs)
+ _ = _log_artifact_version(
+ name=name,
+ type="model",
+ entries={
+ "index": model,
+ },
+ aliases=aliases,
+ description=description,
+ metadata=metadata,
+ project=project,
+ scope_project=scope_project,
+ job_type="log_model",
+ )
+ # TODO: handle offline mode appropriately.
+ return model
+
+
+_USE_MODEL_DEPRECATION_MSG = "`use_model` is deprecated and will be removed in a future version. Please update your code to use `Run.use_artifact` instead."
+
+
+@deprecated(_USE_MODEL_DEPRECATION_MSG)
+def use_model(aliased_path: str, unsafe: bool = False) -> _SavedModel:
+ """Fetch a saved model from an alias.
+
+ Under the hood, we use the alias to fetch the model artifact containing the
+ serialized model files and rebuild the model object from these files. We also
+ declare the fetched model artifact as an input to the run (with `run.use_artifact`).
+
+ Args:
+ aliased_path: `str` - the following forms are valid: "name:version",
+ "name:alias". May be prefixed with "entity/project".
+ unsafe: `bool` - must be True to indicate the user understands the risks
+ associated with loading external models.
+
+ Returns:
+ _SavedModel instance
+
+ Example:
+ ```python
+ # Assuming the model with the name "my-simple-model" is trusted:
+ sm = use_model("my-simple-model:latest", unsafe=True)
+ model = sm.model_obj()
+ ```
+ """
+ wandb_deprecate(
+ field_name=Deprecated.beta__workflows__use_model,
+ warning_message=_USE_MODEL_DEPRECATION_MSG,
+ )
+
+ if not unsafe:
+ raise ValueError("The 'unsafe' parameter must be set to True to load a model.")
+
+ if ":" not in aliased_path:
+ raise ValueError(
+ "aliased_path must be of the form 'name:alias' or 'name:version'."
+ )
+
+ # Returns a _SavedModel instance
+ if run := wandb_setup.singleton().most_recent_active_run:
+ artifact = run.use_artifact(aliased_path)
+ sm = artifact.get("index")
+
+ if sm is None or not isinstance(sm, _SavedModel):
+ raise ValueError(
+ "Deserialization into model object failed: _SavedModel instance could not be initialized properly."
+ )
+
+ return sm
+ else:
+ raise ValueError(
+ "use_model can only be called inside a run. Please call wandb.init() before use_model(...)"
+ )
+
+
+_LINK_MODEL_DEPRECATION_MSG = "`link_model` is deprecated and will be removed in a future version. Please use `Run.link_artifact` instead."
+
+
+@deprecated(_LINK_MODEL_DEPRECATION_MSG)
+def link_model(
+ model: _SavedModel,
+ target_path: str,
+ aliases: str | list[str] | None = None,
+) -> None:
+ """Link the given model to a portfolio.
+
+ A portfolio is a promoted collection which contains (in this case) model artifacts.
+ Linking to a portfolio allows for useful model-centric workflows in the UI.
+
+ Args:
+ model: `_SavedModel` - an instance of _SavedModel, most likely from the output
+ of `log_model` or `use_model`.
+ target_path: `str` - the target portfolio. The following forms are valid for the
+ string: {portfolio}, {project/portfolio},{entity}/{project}/{portfolio}.
+ aliases: `str, List[str]` - optional alias(es) that will only be applied on this
+ linked model inside the portfolio. The alias "latest" will always be applied
+ to the latest version of a model.
+
+ Returns:
+ None
+
+ Example:
+ sm = use_model("my-simple-model:latest")
+ link_model(sm, "my-portfolio")
+
+ """
+ wandb_deprecate(
+ field_name=Deprecated.beta__workflows__link_model,
+ warning_message=_LINK_MODEL_DEPRECATION_MSG,
+ )
+
+ aliases = wandb.util._resolve_aliases(aliases)
+
+ if run := wandb_setup.singleton().most_recent_active_run:
+ # _artifact_source, if it exists, points to a Public Artifact.
+ # Its existence means that _SavedModel was deserialized from a logged artifact, most likely from `use_model`.
+ if model._artifact_source:
+ artifact = model._artifact_source.artifact
+ # If the _SavedModel has been added to a Local Artifact (most likely through `.add(WBValue)`), then
+ # model._artifact_target will point to that Local Artifact.
+ elif model._artifact_target and model._artifact_target.artifact._final:
+ artifact = model._artifact_target.artifact
+ else:
+ raise ValueError(
+ "Linking requires that the given _SavedModel belongs to an artifact"
+ )
+
+ run.link_artifact(artifact, target_path, aliases)
+
+ else:
+ if model._artifact_source is not None:
+ model._artifact_source.artifact.link(target_path, aliases)
+ else:
+ raise ValueError(
+ "Linking requires that the given _SavedModel belongs to a logged artifact."
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/cli/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/cli/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/cli/beta.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/cli/beta.py
new file mode 100644
index 0000000000000000000000000000000000000000..adabe34fb1bd91bd6ccff80430187e15c316c268
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/cli/beta.py
@@ -0,0 +1,107 @@
+"""Beta versions of wandb CLI commands.
+
+These commands are experimental and may change or be removed in future versions.
+"""
+
+from __future__ import annotations
+
+import pathlib
+
+import click
+
+from wandb.errors import WandbCoreNotAvailableError
+from wandb.util import get_core_path
+
+
+@click.group()
+def beta():
+ """Beta versions of wandb CLI commands."""
+ import wandb.env
+
+ wandb._sentry.configure_scope(process_context="wandb_beta")
+
+ try:
+ get_core_path()
+ except WandbCoreNotAvailableError as e:
+ wandb._sentry.exception(f"using `wandb beta`. failed with {e}")
+ click.secho(
+ (e),
+ fg="red",
+ err=True,
+ )
+
+
+@beta.command()
+@click.argument("path", nargs=1, type=click.Path(exists=True), required=False)
+def leet(path: str | None = None) -> None:
+ """Launch W&B LEET: the Lightweight Experiment Exploration Tool.
+
+ LEET is a terminal UI for viewing a W&B run specified by an optional PATH.
+
+ PATH can include a .wandb file or a run directory containing a .wandb file.
+ If PATH is not provided, the command will look for the latest run.
+ """
+ from . import beta_leet
+
+ beta_leet.launch(path)
+
+
+@beta.command()
+@click.argument("paths", type=click.Path(exists=True), nargs=-1)
+@click.option(
+ "--skip-synced/--no-skip-synced",
+ is_flag=True,
+ default=True,
+ help="Skip runs that have already been synced with this command.",
+)
+@click.option(
+ "--dry-run",
+ is_flag=True,
+ default=False,
+ help="Print what would happen without uploading anything.",
+)
+@click.option(
+ "-v",
+ "--verbose",
+ is_flag=True,
+ default=False,
+ help="Print more information.",
+)
+@click.option(
+ "-n",
+ default=5,
+ help="Max number of runs to sync at a time.",
+)
+def sync(
+ paths: tuple[str, ...],
+ skip_synced: bool,
+ dry_run: bool,
+ verbose: bool,
+ n: int,
+) -> None:
+ """Upload .wandb files specified by PATHS.
+
+ PATHS can include .wandb files, run directories containing .wandb files,
+ and "wandb" directories containing run directories.
+
+ For example, to sync all runs in a directory:
+
+ wandb beta sync ./wandb
+
+ To sync a specific run:
+
+ wandb beta sync ./wandb/run-20250813_124246-n67z9ude
+
+ Or equivalently:
+
+ wandb beta sync ./wandb/run-20250813_124246-n67z9ude/run-n67z9ude.wandb
+ """
+ from . import beta_sync
+
+ beta_sync.sync(
+ [pathlib.Path(path) for path in paths],
+ dry_run=dry_run,
+ skip_synced=skip_synced,
+ verbose=verbose,
+ parallelism=n,
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/cli/beta_leet.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/cli/beta_leet.py
new file mode 100644
index 0000000000000000000000000000000000000000..203b32625837937d9706eb327833d42063b5ce69
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/cli/beta_leet.py
@@ -0,0 +1,74 @@
+from __future__ import annotations
+
+import os
+import pathlib
+import subprocess
+import sys
+
+import click
+from typing_extensions import Never
+
+import wandb
+from wandb.env import error_reporting_enabled, is_debug
+from wandb.sdk import wandb_setup
+from wandb.util import get_core_path
+
+from .beta_sync import _find_wandb_files
+
+
+def _fatal(message: str) -> Never:
+ """Print an error message and exit with code 1."""
+ click.echo(f"Error: {message}", err=True)
+ sys.exit(1)
+
+
+def _wandb_file_path(path: str | None) -> str:
+ """Returns absolute path to the .wandb file to display with LEET.
+
+ If `path` is not provided, looks for the latest W&B run.
+
+ Prints an error and exits if a valid path is not found.
+ """
+ if not path:
+ wandb_dir = wandb_setup.singleton().settings.wandb_dir
+
+ wandb_run_path = (pathlib.Path(wandb_dir) / "latest-run").resolve()
+ else:
+ wandb_run_path = pathlib.Path(path).resolve()
+
+ wandb_files = list(_find_wandb_files(wandb_run_path, skip_synced=False))
+
+ if len(wandb_files) == 0:
+ _fatal(f"Could not find a .wandb file in {wandb_run_path}.")
+ elif len(wandb_files) > 1:
+ _fatal(f"Found multiple .wandb files in {wandb_run_path}.")
+
+ return wandb_files[0]
+
+
+def launch(path: str | None) -> Never:
+ wandb._sentry.configure_scope(process_context="leet")
+
+ wandb_file = _wandb_file_path(path)
+
+ try:
+ core_path = get_core_path()
+
+ args = [core_path, "leet"]
+ args.append(wandb_file)
+
+ if not error_reporting_enabled():
+ args.append("--no-observability")
+
+ if is_debug(default="False"):
+ args.extend(["--log-level", "-4"])
+
+ result = subprocess.run(
+ args,
+ env=os.environ,
+ close_fds=True,
+ )
+ sys.exit(result.returncode)
+
+ except Exception as e:
+ wandb._sentry.reraise(e)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/cli/beta_sync.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/cli/beta_sync.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a641edf83b0e1b416abb84e85fa299e286b3dfc
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/cli/beta_sync.py
@@ -0,0 +1,224 @@
+"""Implements `wandb sync` using wandb-core."""
+
+from __future__ import annotations
+
+import asyncio
+import pathlib
+import time
+from itertools import filterfalse
+from typing import Iterable, Iterator
+
+import click
+
+import wandb
+from wandb.proto.wandb_sync_pb2 import ServerSyncResponse
+from wandb.sdk import wandb_setup
+from wandb.sdk.lib import asyncio_compat
+from wandb.sdk.lib.printer import Printer, new_printer
+from wandb.sdk.lib.progress import progress_printer
+from wandb.sdk.lib.service.service_connection import ServiceConnection
+from wandb.sdk.mailbox.mailbox_handle import MailboxHandle
+
+_MAX_LIST_LINES = 20
+_POLL_WAIT_SECONDS = 0.1
+_SLEEP = asyncio.sleep # patched in tests
+
+
+def sync(
+ paths: list[pathlib.Path],
+ *,
+ dry_run: bool,
+ skip_synced: bool,
+ verbose: bool,
+ parallelism: int,
+) -> None:
+ """Replay one or more .wandb files.
+
+ Args:
+ paths: One or more .wandb files, run directories containing
+ .wandb files, and wandb directories containing run directories.
+ dry_run: If true, just prints what it would do and exits.
+ skip_synced: If true, skips files that have already been synced
+ as indicated by a .wandb.synced marker file in the same directory.
+ verbose: Verbose mode for printing more info.
+ parallelism: Max number of runs to sync at a time.
+ """
+ wandb_files: set[pathlib.Path] = set()
+ for path in paths:
+ for wandb_file in _find_wandb_files(path, skip_synced=skip_synced):
+ wandb_files.add(wandb_file.resolve())
+
+ if not wandb_files:
+ click.echo("No files to sync.")
+ return
+
+ if dry_run:
+ click.echo(f"Would sync {len(wandb_files)} file(s):")
+ _print_sorted_paths(wandb_files, verbose=verbose)
+ return
+
+ click.echo(f"Syncing {len(wandb_files)} file(s):")
+ _print_sorted_paths(wandb_files, verbose=verbose)
+
+ singleton = wandb_setup.singleton()
+ service = singleton.ensure_service()
+ printer = new_printer()
+ singleton.asyncer.run(
+ lambda: _do_sync(
+ wandb_files,
+ service=service,
+ settings=singleton.settings,
+ printer=printer,
+ parallelism=parallelism,
+ )
+ )
+
+
+async def _do_sync(
+ wandb_files: set[pathlib.Path],
+ *,
+ service: ServiceConnection,
+ settings: wandb.Settings,
+ printer: Printer,
+ parallelism: int,
+) -> None:
+ """Sync the specified files.
+
+ This is factored out to make the progress animation testable.
+ """
+ init_handle = await service.init_sync(wandb_files, settings)
+ init_result = await init_handle.wait_async(timeout=5)
+
+ sync_handle = await service.sync(init_result.id, parallelism=parallelism)
+
+ await _SyncStatusLoop(
+ init_result.id,
+ service,
+ printer,
+ ).wait_with_progress(sync_handle)
+
+
+class _SyncStatusLoop:
+ """Displays a sync operation's status until it completes."""
+
+ def __init__(
+ self,
+ id: str,
+ service: ServiceConnection,
+ printer: Printer,
+ ) -> None:
+ self._id = id
+ self._service = service
+ self._printer = printer
+
+ self._rate_limit_last_time: float | None = None
+ self._done = asyncio.Event()
+
+ async def wait_with_progress(
+ self,
+ handle: MailboxHandle[ServerSyncResponse],
+ ) -> None:
+ """Display status updates until the handle completes."""
+ async with asyncio_compat.open_task_group() as group:
+ group.start_soon(self._wait_then_mark_done(handle))
+ group.start_soon(self._show_progress_until_done())
+
+ async def _wait_then_mark_done(
+ self,
+ handle: MailboxHandle[ServerSyncResponse],
+ ) -> None:
+ response = await handle.wait_async(timeout=None)
+ for msg in response.messages:
+ self._printer.display(msg.content, level=msg.severity)
+ self._done.set()
+
+ async def _show_progress_until_done(self) -> None:
+ """Show rate-limited status updates until _done is set."""
+ with progress_printer(self._printer, "Syncing...") as progress:
+ while not await self._rate_limit_check_done():
+ handle = await self._service.sync_status(self._id)
+ response = await handle.wait_async(timeout=None)
+
+ for msg in response.new_messages:
+ self._printer.display(msg.content, level=msg.severity)
+ progress.update(response.stats)
+
+ async def _rate_limit_check_done(self) -> bool:
+ """Wait for rate limit and return whether _done is set."""
+ now = time.monotonic()
+ last_time = self._rate_limit_last_time
+ self._rate_limit_last_time = now
+
+ if last_time and (time_since_last := now - last_time) < _POLL_WAIT_SECONDS:
+ await asyncio_compat.race(
+ _SLEEP(_POLL_WAIT_SECONDS - time_since_last),
+ self._done.wait(),
+ )
+
+ return self._done.is_set()
+
+
+def _find_wandb_files(
+ path: pathlib.Path,
+ *,
+ skip_synced: bool,
+) -> Iterator[pathlib.Path]:
+ """Returns paths to the .wandb files to sync."""
+ if skip_synced:
+ yield from filterfalse(_is_synced, _expand_wandb_files(path))
+ else:
+ yield from _expand_wandb_files(path)
+
+
+def _expand_wandb_files(
+ path: pathlib.Path,
+) -> Iterator[pathlib.Path]:
+ """Iterate over .wandb files selected by the path."""
+ if path.suffix == ".wandb":
+ yield path
+ return
+
+ files_in_run_directory = path.glob("*.wandb")
+ try:
+ first_file = next(files_in_run_directory)
+ except StopIteration:
+ pass
+ else:
+ yield first_file
+ yield from files_in_run_directory
+ return
+
+ yield from path.glob("*/*.wandb")
+
+
+def _is_synced(path: pathlib.Path) -> bool:
+ """Returns whether the .wandb file is synced."""
+ return path.with_suffix(".wandb.synced").exists()
+
+
+def _print_sorted_paths(paths: Iterable[pathlib.Path], verbose: bool) -> None:
+ """Print file paths, sorting them and truncating the list if needed.
+
+ Args:
+ paths: Paths to print. Must be absolute with symlinks resolved.
+ verbose: If true, doesn't truncate paths.
+ """
+ # Prefer to print paths relative to the current working directory.
+ cwd = pathlib.Path(".").resolve()
+ formatted_paths: list[str] = []
+ for path in paths:
+ try:
+ formatted_path = str(path.relative_to(cwd))
+ except ValueError:
+ formatted_path = str(path)
+ formatted_paths.append(formatted_path)
+
+ sorted_paths = sorted(formatted_paths)
+ max_lines = len(sorted_paths) if verbose else _MAX_LIST_LINES
+
+ for i in range(min(len(sorted_paths), max_lines)):
+ click.echo(f" {sorted_paths[i]}")
+
+ if len(sorted_paths) > max_lines:
+ remaining = len(sorted_paths) - max_lines
+ click.echo(f" +{remaining:,d} more (pass --verbose to see all)")
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/cli/cli.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/cli/cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e0fc3f363a690e1deecfec459345d7b5958ec9d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/cli/cli.py
@@ -0,0 +1,2910 @@
+import asyncio
+import configparser
+import datetime
+import getpass
+import json
+import logging
+import os
+import shlex
+import shutil
+import subprocess
+import sys
+import tempfile
+import textwrap
+import time
+import traceback
+from functools import wraps
+from typing import Any, Dict, Optional, Tuple
+
+import click
+import yaml
+from click.exceptions import ClickException
+
+import wandb
+import wandb.env
+import wandb.errors
+import wandb.sdk.verify.verify as wandb_verify
+from wandb import Config, Error, env, util, wandb_agent, wandb_sdk
+from wandb.apis import InternalApi, PublicApi
+from wandb.apis.public import RunQueue
+from wandb.errors.links import url_registry
+from wandb.sdk import wandb_setup
+from wandb.sdk.artifacts._validators import is_artifact_registry_project
+from wandb.sdk.artifacts.artifact_file_cache import get_artifact_file_cache
+from wandb.sdk.internal.internal_api import Api as SDKInternalApi
+from wandb.sdk.launch import utils as launch_utils
+from wandb.sdk.launch._launch_add import _launch_add
+from wandb.sdk.launch.errors import ExecutionError, LaunchError
+from wandb.sdk.launch.sweeps import utils as sweep_utils
+from wandb.sdk.launch.sweeps.scheduler import Scheduler
+from wandb.sdk.lib import filesystem
+from wandb.sync import SyncManager, get_run_from_path, get_runs
+
+from .beta import beta
+
+# Send cli logs to wandb/debug-cli..log by default and fallback to a temp dir.
+_wandb_dir = wandb.old.core.wandb_dir(env.get_dir())
+if not os.path.exists(_wandb_dir):
+ _wandb_dir = tempfile.gettempdir()
+
+try:
+ _username = getpass.getuser()
+except KeyError:
+ # getuser() could raise KeyError in restricted environments like
+ # chroot jails or docker containers. Return user id in these cases.
+ _username = str(os.getuid())
+
+_wandb_log_path = os.path.join(_wandb_dir, f"debug-cli.{_username}.log")
+
+logging.basicConfig(
+ filename=_wandb_log_path,
+ level=logging.INFO,
+ format="%(asctime)s %(levelname)s %(message)s",
+ datefmt="%Y-%m-%d %H:%M:%S",
+)
+logging.basicConfig(stream=sys.stdout, level=logging.INFO)
+logger = logging.getLogger("wandb")
+
+_HAS_DOCKER = bool(shutil.which("docker"))
+_HAS_NVIDIA_DOCKER = bool(shutil.which("nvidia-docker"))
+
+# Click Contexts
+CONTEXT = {"default_map": {}}
+RUN_CONTEXT = {
+ "default_map": {},
+ "allow_extra_args": True,
+ "ignore_unknown_options": True,
+}
+
+
+def cli_unsupported(argument):
+ wandb.termerror(f"Unsupported argument `{argument}`")
+ sys.exit(1)
+
+
+class ClickWandbException(ClickException):
+ def format_message(self):
+ orig_type = f"{self.orig_type.__module__}.{self.orig_type.__name__}"
+ if issubclass(self.orig_type, Error):
+ return click.style(str(self.message), fg="red")
+ else:
+ return (
+ f"An Exception was raised, see {_wandb_log_path} for full"
+ " traceback.\n"
+ f"{orig_type}: {self.message}"
+ )
+
+
+def parse_service_config(
+ ctx: Optional[click.Context],
+ param: Optional[click.Parameter],
+ value: Optional[Tuple[str, ...]],
+) -> Dict[str, str]:
+ """Parse service configurations in format serviceName=policy."""
+ if not value:
+ return {}
+
+ result = {}
+ for config in value:
+ if "=" not in config:
+ raise click.BadParameter(
+ f"Service must be in format 'serviceName=policy', got '{config}'"
+ )
+
+ service_name, policy = config.split("=", 1)
+ service_name = service_name.strip()
+ policy = policy.strip()
+ if not service_name:
+ raise click.BadParameter("Service name cannot be empty")
+
+ # Simple validation for two policies
+ if policy not in ["always", "never"]:
+ raise click.BadParameter(
+ f"Policy must be 'always' or 'never', got '{policy}'"
+ )
+
+ result[service_name] = policy
+
+ return result
+
+
+def display_error(func):
+ """Function decorator for catching common errors and re-raising as wandb.Error."""
+
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ try:
+ return func(*args, **kwargs)
+ except wandb.Error as e:
+ exc_type, exc_value, exc_traceback = sys.exc_info()
+ lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
+ logger.exception("".join(lines))
+ wandb.termerror(f"Find detailed error logs at: {_wandb_log_path}")
+ click_exc = ClickWandbException(e)
+ click_exc.orig_type = exc_type
+ raise click_exc.with_traceback(sys.exc_info()[2])
+
+ return wrapper
+
+
+_api = None # caching api instance allows patching from unit tests
+
+
+def _get_cling_api(reset=None):
+ """Get a reference to the internal api with cling settings."""
+ global _api
+ if reset:
+ _api = None
+ wandb.teardown()
+ if _api is None:
+ # TODO(jhr): make a settings object that is better for non runs.
+ # only override the necessary setting
+ wandb_setup.singleton().settings.x_cli_only_mode = True
+ _api = InternalApi()
+ return _api
+
+
+def prompt_for_project(ctx, entity):
+ """Ask the user for a project, creating one if necessary."""
+ result = ctx.invoke(projects, entity=entity, display=False)
+ api = _get_cling_api()
+ try:
+ if len(result) == 0:
+ project = click.prompt("Enter a name for your first project")
+ # description = editor()
+ project = api.upsert_project(project, entity=entity)["name"]
+ else:
+ project_names = [project["name"] for project in result] + ["Create New"]
+ wandb.termlog("Which project should we use?")
+ result = util.prompt_choices(project_names)
+ if result:
+ project = result
+ else:
+ project = "Create New"
+ # TODO: check with the server if the project exists
+ if project == "Create New":
+ project = click.prompt(
+ "Enter a name for your new project", value_proc=api.format_project
+ )
+ # description = editor()
+ project = api.upsert_project(project, entity=entity)["name"]
+
+ except wandb.errors.CommError as e:
+ raise ClickException(str(e))
+
+ return project
+
+
+class RunGroup(click.Group):
+ @display_error
+ def get_command(self, ctx, cmd_name):
+ # TODO: check if cmd_name is a file in the current dir and not require `run`?
+ rv = click.Group.get_command(self, ctx, cmd_name)
+ if rv is not None:
+ return rv
+ return None
+
+
+@click.command(cls=RunGroup, invoke_without_command=True)
+@click.version_option(version=wandb.__version__)
+@click.pass_context
+def cli(ctx):
+ if ctx.invoked_subcommand is None:
+ click.echo(ctx.get_help())
+
+
+@cli.command(context_settings=CONTEXT, help="List projects", hidden=True)
+@click.option(
+ "--entity",
+ "-e",
+ default=None,
+ envvar=env.ENTITY,
+ help="The entity to scope the listing to.",
+)
+@display_error
+def projects(entity, display=True):
+ api = _get_cling_api()
+ projects = api.list_projects(entity=entity)
+ if len(projects) == 0:
+ message = f"No projects found for {entity}"
+ else:
+ message = f'Latest projects for "{entity}"'
+ if display:
+ click.echo(click.style(message, bold=True))
+ for project in projects:
+ click.echo(
+ "".join(
+ (
+ click.style(project["name"], fg="blue", bold=True),
+ " - ",
+ str(project["description"] or "").split("\n")[0],
+ )
+ )
+ )
+ return projects
+
+
+@cli.command(context_settings=CONTEXT)
+@click.argument("key", nargs=-1)
+@click.option("--cloud", is_flag=True, help="Login to the cloud instead of local")
+@click.option(
+ "--host", "--base-url", default=None, help="Login to a specific instance of W&B"
+)
+@click.option(
+ "--relogin", default=None, is_flag=True, help="Force relogin if already logged in."
+)
+@click.option("--anonymously", default=False, is_flag=True, help="Log in anonymously")
+@click.option(
+ "--verify/--no-verify",
+ default=False,
+ is_flag=True,
+ help="Verify login credentials",
+)
+@display_error
+def login(key, host, cloud, relogin, anonymously, verify, no_offline=False):
+ """Verify and store your API key for authentication with W&B services.
+
+ By default, only store credentials locally without verifying them with W&B.
+ To verify credentials, set `--verify=True`.
+
+ For server deployments (dedicated cloud or customer-managed instances),
+ specify the host URL using the `--host` flag. You can also set environment
+ variables `WANDB_BASE_URL` and `WANDB_API_KEY` instead of running
+ the `login` command with host parameters.
+ """
+ # TODO: handle no_offline
+ anon_mode = "must" if anonymously else "never"
+
+ wandb_sdk.wandb_login._handle_host_wandb_setting(host, cloud)
+ # A change in click or the test harness means key can be none...
+ key = key[0] if key is not None and len(key) > 0 else None
+ relogin = True if key or relogin else False
+
+ global_settings = wandb_setup.singleton().settings
+ global_settings.x_cli_only_mode = True
+ global_settings.x_disable_viewer = relogin and not verify
+
+ wandb.login(
+ anonymous=anon_mode,
+ force=True,
+ host=host,
+ key=key,
+ relogin=relogin,
+ verify=verify,
+ referrer="models",
+ )
+
+
+@cli.command(
+ context_settings=CONTEXT, help="Configure a directory with Weights & Biases"
+)
+@click.option("--project", "-p", help="The project to use.")
+@click.option("--entity", "-e", help="The entity to scope the project to.")
+# TODO(jhr): Enable these with settings rework
+# @click.option("--setting", "-s", help="enable an arbitrary setting.", multiple=True)
+# @click.option('--show', is_flag=True, help="Show settings")
+@click.option("--reset", is_flag=True, help="Reset settings")
+@click.option(
+ "--mode",
+ "-m",
+ help=' Can be "online", "offline" or "disabled". Defaults to online.',
+)
+@click.pass_context
+@display_error
+def init(ctx, project, entity, reset, mode):
+ from wandb.old.core import __stage_dir__, _set_stage_dir, wandb_dir
+
+ if __stage_dir__ is None:
+ _set_stage_dir("wandb")
+
+ # non-interactive init
+ if reset or project or entity or mode:
+ api = InternalApi()
+ if reset:
+ api.clear_setting("entity", persist=True)
+ api.clear_setting("project", persist=True)
+ api.clear_setting("mode", persist=True)
+ # TODO(jhr): clear more settings?
+ if entity:
+ api.set_setting("entity", entity, persist=True)
+ if project:
+ api.set_setting("project", project, persist=True)
+ if mode:
+ api.set_setting("mode", mode, persist=True)
+ return
+
+ if os.path.isdir(wandb_dir()) and os.path.exists(
+ os.path.join(wandb_dir(), "settings")
+ ):
+ click.confirm(
+ click.style(
+ "This directory has been configured previously, should we re-configure it?",
+ bold=True,
+ ),
+ abort=True,
+ )
+ else:
+ click.echo(
+ click.style("Let's setup this directory for W&B!", fg="green", bold=True)
+ )
+ api = _get_cling_api()
+ if api.api_key is None:
+ ctx.invoke(login)
+ api = _get_cling_api(reset=True)
+
+ viewer = api.viewer()
+
+ # Viewer can be `None` in case your API information became invalid, or
+ # in testing if you switch hosts.
+ if not viewer:
+ click.echo(
+ click.style(
+ "Your login information seems to be invalid: can you log in again please?",
+ fg="red",
+ bold=True,
+ )
+ )
+ ctx.invoke(login)
+ api = _get_cling_api(reset=True)
+
+ # This shouldn't happen.
+ viewer = api.viewer()
+ if not viewer:
+ click.echo(
+ click.style(
+ "We're sorry, there was a problem logging you in. "
+ "Please send us a note at support@wandb.com and tell us how this happened.",
+ fg="red",
+ bold=True,
+ )
+ )
+ sys.exit(1)
+
+ # At this point we should be logged in successfully.
+ if len(viewer["teams"]["edges"]) > 1:
+ team_names = [e["node"]["name"] for e in viewer["teams"]["edges"]] + [
+ "Manual entry"
+ ]
+ wandb.termlog(
+ "Which team should we use?",
+ )
+ result = util.prompt_choices(team_names)
+ # result can be empty on click
+ if result:
+ entity = result
+ else:
+ entity = "Manual Entry"
+ if entity == "Manual Entry":
+ entity = click.prompt("Enter the name of the team you want to use")
+ else:
+ entity = viewer.get("entity") or click.prompt(
+ "What username or team should we use?"
+ )
+
+ # TODO: this error handling sucks and the output isn't pretty
+ try:
+ project = prompt_for_project(ctx, entity)
+ except ClickWandbException:
+ raise ClickException(f"Could not find team: {entity}")
+
+ api.set_setting("entity", entity, persist=True)
+ api.set_setting("project", project, persist=True)
+ api.set_setting("base_url", api.settings().get("base_url"), persist=True)
+
+ filesystem.mkdir_exists_ok(wandb_dir())
+ with open(os.path.join(wandb_dir(), ".gitignore"), "w") as file:
+ file.write("*\n!settings")
+
+ click.echo(
+ click.style("This directory is configured! Next, track a run:\n", fg="green")
+ + textwrap.dedent(
+ """\
+ * In your training script:
+ {code1}
+ {code2}
+ * then `{run}`.
+ """
+ ).format(
+ code1=click.style("import wandb", bold=True),
+ code2=click.style(f'wandb.init(project="{project}")', bold=True),
+ run=click.style("python ", bold=True),
+ )
+ )
+
+
+@cli.command(context_settings=CONTEXT)
+@click.pass_context
+@click.argument("path", nargs=-1, type=click.Path(exists=True))
+@click.option("--view", is_flag=True, default=False, help="View runs", hidden=True)
+@click.option("--verbose", is_flag=True, default=False, help="Verbose", hidden=True)
+@click.option("--id", "run_id", help="The run you want to upload to.")
+@click.option("--project", "-p", help="The project you want to upload to.")
+@click.option("--entity", "-e", help="The entity to scope to.")
+@click.option(
+ "--job_type",
+ "job_type",
+ help="Specifies the type of run for grouping related runs together.",
+)
+@click.option(
+ "--sync-tensorboard/--no-sync-tensorboard",
+ is_flag=True,
+ default=None,
+ help="Stream tfevent files to wandb.",
+)
+@click.option("--include-globs", help="Comma separated list of globs to include.")
+@click.option("--exclude-globs", help="Comma separated list of globs to exclude.")
+@click.option(
+ "--include-online/--no-include-online",
+ is_flag=True,
+ default=None,
+ help="Include online runs",
+)
+@click.option(
+ "--include-offline/--no-include-offline",
+ is_flag=True,
+ default=None,
+ help="Include offline runs",
+)
+@click.option(
+ "--include-synced/--no-include-synced",
+ is_flag=True,
+ default=None,
+ help="Include synced runs",
+)
+@click.option(
+ "--mark-synced/--no-mark-synced",
+ is_flag=True,
+ default=True,
+ help="Mark runs as synced",
+)
+@click.option("--sync-all", is_flag=True, default=False, help="Sync all runs")
+@click.option("--clean", is_flag=True, default=False, help="Delete synced runs")
+@click.option(
+ "--clean-old-hours",
+ default=24,
+ help="Delete runs created before this many hours. To be used alongside --clean flag.",
+ type=int,
+)
+@click.option(
+ "--clean-force",
+ is_flag=True,
+ default=False,
+ help="Clean without confirmation prompt.",
+)
+@click.option("--ignore", hidden=True)
+@click.option("--show", default=5, help="Number of runs to show")
+@click.option("--append", is_flag=True, default=False, help="Append run")
+@click.option("--skip-console", is_flag=True, default=False, help="Skip console logs")
+@click.option(
+ "--replace-tags",
+ help="Replace tags in the format 'old_tag1=new_tag1,old_tag2=new_tag2'",
+)
+@display_error
+def sync(
+ ctx,
+ path=None,
+ view=None,
+ verbose=None,
+ run_id=None,
+ project=None,
+ entity=None,
+ job_type=None, # trace this back to SyncManager
+ sync_tensorboard=None,
+ include_globs=None,
+ exclude_globs=None,
+ include_online=None,
+ include_offline=None,
+ include_synced=None,
+ mark_synced=None,
+ sync_all=None,
+ ignore=None,
+ show=None,
+ clean=None,
+ clean_old_hours=24,
+ clean_force=None,
+ append=None,
+ skip_console=None,
+ replace_tags=None,
+):
+ """Synchronize W&B run data to the cloud.
+
+ If PATH is provided, sync runs found at the given path. If a path
+ is not specified, search for `./wandb` first, then search for a
+ `wandb/` subdirectory.
+
+ To sync a specific run:
+
+ wandb sync ./wandb/run-20250813_124246-n67z9ude
+
+ Or equivalently:
+
+ wandb sync ./wandb/run-20250813_124246-n67z9ude/run-n67z9ude.wandb
+ """
+ api = _get_cling_api()
+ if not api.is_authenticated:
+ wandb.termlog("Login to W&B to sync runs")
+ ctx.invoke(login, no_offline=True)
+ api = _get_cling_api(reset=True)
+
+ if ignore:
+ exclude_globs = ignore
+ if include_globs:
+ include_globs = include_globs.split(",")
+ if exclude_globs:
+ exclude_globs = exclude_globs.split(",")
+
+ replace_tags_dict = _parse_sync_replace_tags(replace_tags)
+ if replace_tags and replace_tags_dict is None:
+ return # Error already printed by helper function
+
+ def _summary():
+ all_items = get_runs(
+ include_online=True,
+ include_offline=True,
+ include_synced=True,
+ include_unsynced=True,
+ )
+ sync_items = get_runs(
+ include_online=include_online if include_online is not None else True,
+ include_offline=include_offline if include_offline is not None else True,
+ include_synced=include_synced if include_synced is not None else False,
+ include_unsynced=True,
+ exclude_globs=exclude_globs,
+ include_globs=include_globs,
+ )
+ synced = []
+ unsynced = []
+ for item in all_items:
+ (synced if item.synced else unsynced).append(item)
+ if sync_items:
+ wandb.termlog(f"Number of runs to be synced: {len(sync_items)}")
+ if show and show < len(sync_items):
+ wandb.termlog(f"Showing {show} runs to be synced:")
+ for item in sync_items[: (show or len(sync_items))]:
+ wandb.termlog(f" {item}")
+ else:
+ wandb.termlog("No runs to be synced.")
+ if synced:
+ clean_cmd = click.style("wandb sync --clean", fg="yellow")
+ wandb.termlog(
+ f"NOTE: use {clean_cmd} to delete {len(synced)} synced runs from local directory."
+ )
+ if unsynced:
+ sync_cmd = click.style("wandb sync --sync-all", fg="yellow")
+ wandb.termlog(
+ f"NOTE: use {sync_cmd} to sync {len(unsynced)} unsynced runs from local directory."
+ )
+
+ def _sync_path(_path, _sync_tensorboard):
+ if run_id and len(_path) > 1:
+ wandb.termerror("id can only be set for a single run.")
+ sys.exit(1)
+ sm = SyncManager(
+ project=project,
+ entity=entity,
+ run_id=run_id,
+ job_type=job_type,
+ mark_synced=mark_synced,
+ app_url=api.app_url,
+ view=view,
+ verbose=verbose,
+ sync_tensorboard=_sync_tensorboard,
+ log_path=_wandb_log_path,
+ append=append,
+ skip_console=skip_console,
+ replace_tags=replace_tags_dict,
+ )
+ for p in _path:
+ sm.add(p)
+ sm.start()
+ while not sm.is_done():
+ _ = sm.poll()
+
+ def _sync_all():
+ sync_items = get_runs(
+ include_online=include_online if include_online is not None else True,
+ include_offline=include_offline if include_offline is not None else True,
+ include_synced=include_synced if include_synced is not None else False,
+ include_unsynced=True,
+ exclude_globs=exclude_globs,
+ include_globs=include_globs,
+ )
+ if not sync_items:
+ wandb.termerror("Nothing to sync.")
+ else:
+ # When syncing run directories, default to not syncing tensorboard
+ sync_tb = sync_tensorboard if sync_tensorboard is not None else False
+ _sync_path(sync_items, sync_tb)
+
+ def _clean():
+ if path:
+ runs = list(map(get_run_from_path, path))
+ if not clean_force:
+ click.confirm(
+ click.style(
+ f"Are you sure you want to remove {len(runs)} runs?",
+ bold=True,
+ ),
+ abort=True,
+ )
+ for run in runs:
+ shutil.rmtree(run.path)
+ click.echo(click.style("Success!", fg="green"))
+ return
+ runs = get_runs(
+ include_online=include_online if include_online is not None else True,
+ include_offline=include_offline if include_offline is not None else True,
+ include_synced=include_synced if include_synced is not None else True,
+ include_unsynced=False,
+ exclude_globs=exclude_globs,
+ include_globs=include_globs,
+ )
+ since = datetime.datetime.now() - datetime.timedelta(hours=clean_old_hours)
+ old_runs = [run for run in runs if run.datetime < since]
+ old_runs.sort(key=lambda _run: _run.datetime)
+ if old_runs:
+ click.echo(
+ f"Found {len(runs)} runs, {len(old_runs)} are older than {clean_old_hours} hours"
+ )
+ for run in old_runs:
+ click.echo(run.path)
+ if not clean_force:
+ click.confirm(
+ click.style(
+ f"Are you sure you want to remove {len(old_runs)} runs?",
+ bold=True,
+ ),
+ abort=True,
+ )
+ for run in old_runs:
+ shutil.rmtree(run.path)
+ click.echo(click.style("Success!", fg="green"))
+ else:
+ click.echo(
+ click.style(
+ f"No runs older than {clean_old_hours} hours found", fg="red"
+ )
+ )
+
+ if sync_all:
+ _sync_all()
+ elif clean:
+ _clean()
+ elif path:
+ # When syncing a specific path, default to syncing tensorboard
+ sync_tb = sync_tensorboard if sync_tensorboard is not None else True
+ _sync_path(path, sync_tb)
+ else:
+ _summary()
+
+
+def _parse_sync_replace_tags(replace_tags: str) -> Optional[Dict[str, str]]:
+ """Parse replace_tags string into a dictionary.
+
+ Args:
+ replace_tags: String in format 'old_tag1=new_tag1,old_tag2=new_tag2'
+
+ Returns:
+ Mapping of old tags to new tags, or None if format is invalid
+ """
+ if not replace_tags:
+ return {}
+
+ replace_tags_dict = {}
+ for pair in replace_tags.split(","):
+ if "=" not in pair:
+ wandb.termerror(
+ f"Invalid replace-tags format: {pair}. Use 'old_tag=new_tag' format."
+ )
+ return None
+ old_tag, new_tag = pair.split("=", 1)
+ replace_tags_dict[old_tag.strip()] = new_tag.strip()
+
+ return replace_tags_dict
+
+
+@cli.command(
+ context_settings=CONTEXT,
+ help="Initialize a hyperparameter sweep. Search for hyperparameters that optimizes a cost function of a machine learning model by testing various combinations.",
+)
+@click.option(
+ "--project",
+ "-p",
+ default=None,
+ help="""The name of the project where W&B runs created from the sweep are sent to. If the project is not specified, the run is sent to a project labeled Uncategorized.""",
+)
+@click.option(
+ "--entity",
+ "-e",
+ default=None,
+ help="""The username or team name where you want to send W&B runs created by the sweep to. Ensure that the entity you specify already exists. If you don't specify an entity, the run will be sent to your default entity, which is usually your username.""",
+)
+@click.option("--controller", is_flag=True, default=False, help="Run local controller")
+@click.option("--verbose", is_flag=True, default=False, help="Display verbose output")
+@click.option(
+ "--name",
+ default=None,
+ help="The name of the sweep. The sweep ID is used if no name is specified.",
+)
+@click.option("--program", default=None, help="Set sweep program")
+@click.option("--settings", default=None, help="Set sweep settings", hidden=True)
+@click.option("--update", default=None, help="Update pending sweep")
+@click.option(
+ "--stop",
+ is_flag=True,
+ default=False,
+ help="Finish a sweep to stop running new runs and let currently running runs finish.",
+)
+@click.option(
+ "--cancel",
+ is_flag=True,
+ default=False,
+ help="Cancel a sweep to kill all running runs and stop running new runs.",
+)
+@click.option(
+ "--pause",
+ is_flag=True,
+ default=False,
+ help="Pause a sweep to temporarily stop running new runs.",
+)
+@click.option(
+ "--resume",
+ is_flag=True,
+ default=False,
+ help="Resume a sweep to continue running new runs.",
+)
+@click.option(
+ "--prior_run",
+ "-R",
+ "prior_runs",
+ multiple=True,
+ default=None,
+ help="ID of an existing run to add to this sweep",
+)
+@click.argument("config_yaml_or_sweep_id")
+@click.pass_context
+@display_error
+def sweep(
+ ctx,
+ project,
+ entity,
+ controller,
+ verbose,
+ name,
+ program,
+ settings,
+ update,
+ stop,
+ cancel,
+ pause,
+ resume,
+ prior_runs,
+ config_yaml_or_sweep_id,
+):
+ state_args = "stop", "cancel", "pause", "resume"
+ lcls = locals()
+ is_state_change_command = sum(lcls[k] for k in state_args)
+ if is_state_change_command > 1:
+ raise Exception("Only one state flag (stop/cancel/pause/resume) is allowed.")
+ elif is_state_change_command == 1:
+ sweep_id = config_yaml_or_sweep_id
+ api = _get_cling_api()
+ if not api.is_authenticated:
+ wandb.termlog("Login to W&B to use the sweep feature")
+ ctx.invoke(login, no_offline=True)
+ api = _get_cling_api(reset=True)
+ parts = dict(entity=entity, project=project, name=sweep_id)
+ err = sweep_utils.parse_sweep_id(parts)
+ if err:
+ wandb.termerror(err)
+ return
+ entity = parts.get("entity") or entity
+ project = parts.get("project") or project
+ sweep_id = parts.get("name") or sweep_id
+ state = [s for s in state_args if lcls[s]][0]
+ ings = {
+ "stop": "Stopping",
+ "cancel": "Cancelling",
+ "pause": "Pausing",
+ "resume": "Resuming",
+ }
+ wandb.termlog(f"{ings[state]} sweep {entity}/{project}/{sweep_id}")
+ getattr(api, f"{state}_sweep")(sweep_id, entity=entity, project=project)
+ wandb.termlog("Done.")
+ return
+ else:
+ config_yaml = config_yaml_or_sweep_id
+
+ def _parse_settings(settings):
+ """Parse settings from json or comma separated assignments."""
+ ret = {}
+ # TODO(jhr): merge with magic:_parse_magic
+ if settings.find("=") > 0:
+ for item in settings.split(","):
+ kv = item.split("=")
+ if len(kv) != 2:
+ wandb.termwarn(
+ "Unable to parse sweep settings key value pair", repeat=False
+ )
+ ret.update(dict([kv]))
+ return ret
+ wandb.termwarn("Unable to parse settings parameter", repeat=False)
+ return ret
+
+ api = _get_cling_api()
+ if not api.is_authenticated:
+ wandb.termlog("Login to W&B to use the sweep feature")
+ ctx.invoke(login, no_offline=True)
+ api = _get_cling_api(reset=True)
+
+ sweep_obj_id = None
+ if update:
+ parts = dict(entity=entity, project=project, name=update)
+ err = sweep_utils.parse_sweep_id(parts)
+ if err:
+ wandb.termerror(err)
+ return
+ entity = parts.get("entity") or entity
+ project = parts.get("project") or project
+ sweep_id = parts.get("name") or update
+
+ has_project = (project or api.settings("project")) is not None
+ has_entity = (entity or api.settings("entity")) is not None
+
+ termerror_msg = (
+ "Sweep lookup requires a valid %s, and none was specified. \n"
+ "Either set a default %s in wandb/settings, or, if invoking \n`wandb sweep` "
+ "from the command line, specify the full sweep path via: \n\n"
+ " wandb sweep {username}/{projectname}/{sweepid}\n\n"
+ )
+
+ if not has_entity:
+ wandb.termerror(termerror_msg % (("entity",) * 2))
+ return
+
+ if not has_project:
+ wandb.termerror(termerror_msg % (("project",) * 2))
+ return
+
+ found = api.sweep(sweep_id, "{}", entity=entity, project=project)
+ if not found:
+ wandb.termerror(f"Could not find sweep {entity}/{project}/{sweep_id}")
+ return
+ sweep_obj_id = found["id"]
+
+ action = "Updating" if sweep_obj_id else "Creating"
+ wandb.termlog(f"{action} sweep from: {config_yaml}")
+ config = sweep_utils.load_sweep_config(config_yaml)
+
+ # Set or override parameters
+ if name:
+ config["name"] = name
+ if program:
+ config["program"] = program
+ if settings:
+ settings = _parse_settings(settings)
+ if settings:
+ config.setdefault("settings", {})
+ config["settings"].update(settings)
+ if controller:
+ config.setdefault("controller", {})
+ config["controller"]["type"] = "local"
+
+ is_local = config.get("controller", {}).get("type") == "local"
+ if is_local:
+ from wandb import controller as wandb_controller
+
+ tuner = wandb_controller()
+ err = tuner._validate(config)
+ if err:
+ wandb.termerror(f"Error in sweep file: {err}")
+ return
+
+ env = os.environ
+ entity = (
+ entity
+ or env.get("WANDB_ENTITY")
+ or config.get("entity")
+ or api.settings("entity")
+ )
+ project = (
+ project
+ or env.get("WANDB_PROJECT")
+ or config.get("project")
+ or api.settings("project")
+ or util.auto_project_name(config.get("program"))
+ )
+
+ sweep_id, warnings = api.upsert_sweep(
+ config,
+ project=project,
+ entity=entity,
+ obj_id=sweep_obj_id,
+ prior_runs=prior_runs,
+ )
+ sweep_utils.handle_sweep_config_violations(warnings)
+
+ # Log nicely formatted sweep information
+ styled_id = click.style(sweep_id, fg="yellow")
+ wandb.termlog(f"{action} sweep with ID: {styled_id}")
+
+ sweep_url = wandb_sdk.wandb_sweep._get_sweep_url(api, sweep_id)
+ if sweep_url:
+ styled_url = click.style(sweep_url, underline=True, fg="blue")
+ wandb.termlog(f"View sweep at: {styled_url}")
+
+ # re-probe entity and project if it was auto-detected by upsert_sweep
+ entity = entity or env.get("WANDB_ENTITY")
+ project = project or env.get("WANDB_PROJECT")
+
+ if entity and project:
+ sweep_path = f"{entity}/{project}/{sweep_id}"
+ elif project:
+ sweep_path = f"{project}/{sweep_id}"
+ else:
+ sweep_path = sweep_id
+
+ if sweep_path.find(" ") >= 0:
+ sweep_path = f"{sweep_path!r}"
+
+ styled_path = click.style(f"wandb agent {sweep_path}", fg="yellow")
+ wandb.termlog(f"Run sweep agent with: {styled_path}")
+ if controller:
+ wandb.termlog("Starting wandb controller...")
+ from wandb import controller as wandb_controller
+
+ tuner = wandb_controller(sweep_id)
+ tuner.run(verbose=verbose)
+
+
+@cli.command(
+ context_settings=CONTEXT,
+ no_args_is_help=True,
+ help="Run a W&B launch sweep (Experimental).",
+)
+@click.option(
+ "--queue",
+ "-q",
+ default=None,
+ help="The name of a queue to push the sweep to",
+)
+@click.option(
+ "--project",
+ "-p",
+ default=None,
+ help="Name of the project which the agent will watch. "
+ "If passed in, will override the project value passed in using a config file",
+)
+@click.option(
+ "--entity",
+ "-e",
+ default=None,
+ help="The entity to use. Defaults to current logged-in user",
+)
+@click.option(
+ "--resume_id",
+ "-r",
+ default=None,
+ help="Resume a launch sweep by passing an 8-char sweep id. Queue required",
+)
+@click.option(
+ "--prior_run",
+ "-R",
+ "prior_runs",
+ multiple=True,
+ default=None,
+ help="ID of an existing run to add to this sweep",
+)
+@click.argument("config", required=False, type=click.Path(exists=True))
+@click.pass_context
+@display_error
+def launch_sweep(
+ ctx,
+ project,
+ entity,
+ queue,
+ config,
+ resume_id,
+ prior_runs,
+):
+ api = _get_cling_api()
+ env = os.environ
+ if not api.is_authenticated:
+ wandb.termlog("Login to W&B to use the sweep feature")
+ ctx.invoke(login, no_offline=True)
+ api = _get_cling_api(reset=True)
+
+ entity = entity or env.get("WANDB_ENTITY") or api.settings("entity")
+ if entity is None:
+ wandb.termerror("Must specify entity when using launch")
+ return
+
+ project = project or env.get("WANDB_PROJECT") or api.settings("project")
+ if project is None:
+ wandb.termerror("A project must be configured when using launch")
+ return
+
+ # get personal username, not team name or service account, default to entity
+ author = api.viewer().get("username") or entity
+
+ # if not sweep_config XOR resume_id
+ if not (config or resume_id):
+ wandb.termerror("'config' and/or 'resume_id' required")
+ return
+
+ parsed_user_config = sweep_utils.load_launch_sweep_config(config)
+ # Rip special keys out of config, store in scheduler run_config
+ launch_args: Dict[str, Any] = parsed_user_config.pop("launch", {})
+ scheduler_args: Dict[str, Any] = parsed_user_config.pop("scheduler", {})
+ settings: Dict[str, Any] = scheduler_args.pop("settings", {})
+
+ scheduler_job: Optional[str] = scheduler_args.get("job")
+ if scheduler_job:
+ wandb.termwarn(
+ "Using a scheduler job for launch sweeps is *experimental* and may change without warning"
+ )
+ queue: Optional[str] = queue or launch_args.get("queue")
+
+ sweep_config, sweep_obj_id = None, None
+ if not resume_id:
+ sweep_config = parsed_user_config
+
+ # check method
+ method = sweep_config.get("method")
+ if scheduler_job and not method:
+ sweep_config["method"] = "custom"
+ elif scheduler_job and method != "custom":
+ # TODO(gst): Check if using Anaconda2
+ wandb.termwarn(
+ "Use 'method': 'custom' in the sweep config when using scheduler jobs, "
+ "or omit it entirely. For jobs using the wandb optimization engine (WandbScheduler), "
+ "set the method in the sweep config under scheduler.settings.method "
+ )
+ settings["method"] = method
+
+ if settings.get("method"):
+ # assume WandbScheduler, and user is using this right
+ sweep_config["method"] = settings["method"]
+
+ else: # Resuming an existing sweep
+ found = api.sweep(resume_id, "{}", entity=entity, project=project)
+ if not found:
+ wandb.termerror(f"Could not find sweep {entity}/{project}/{resume_id}")
+ return
+
+ if found.get("state") == "RUNNING":
+ wandb.termerror(
+ f"Cannot resume sweep {entity}/{project}/{resume_id}, it is already running"
+ )
+ return
+
+ sweep_obj_id = found["id"]
+ sweep_config = yaml.safe_load(found["config"])
+ wandb.termlog(f"Resuming from existing sweep {entity}/{project}/{resume_id}")
+ if len(parsed_user_config.keys()) > 0:
+ wandb.termwarn(
+ "Sweep parameters loaded from resumed sweep, ignoring provided config"
+ )
+
+ prev_scheduler = json.loads(found.get("scheduler") or "{}")
+ run_spec = json.loads(prev_scheduler.get("run_spec", "{}"))
+ if (
+ scheduler_job
+ and run_spec.get("job")
+ and run_spec.get("job") != scheduler_job
+ ):
+ wandb.termerror(
+ f"Resuming a launch sweep with a different scheduler job is not supported. Job loaded from sweep: {run_spec.get('job')}, job in config: {scheduler_job}"
+ )
+ return
+
+ prev_scheduler_args, prev_settings = sweep_utils.get_previous_args(run_spec)
+ # Passed in scheduler_args and settings override previous
+ scheduler_args.update(prev_scheduler_args)
+ settings.update(prev_settings)
+ if not queue:
+ wandb.termerror(
+ "Launch-sweeps require setting a 'queue', use --queue option or a 'queue' key in the 'launch' section in the config"
+ )
+ return
+
+ entrypoint = Scheduler.ENTRYPOINT if not scheduler_job else None
+ args = sweep_utils.construct_scheduler_args(
+ return_job=scheduler_job is not None,
+ sweep_config=sweep_config,
+ queue=queue,
+ project=project,
+ author=author,
+ )
+ if not args:
+ return
+
+ # validate training job existence
+ if not sweep_utils.check_job_exists(PublicApi(), sweep_config.get("job")):
+ return False
+
+ # validate scheduler job existence, if present
+ if not sweep_utils.check_job_exists(PublicApi(), scheduler_job):
+ return False
+
+ # Set run overrides for the Scheduler
+ overrides = {"run_config": {}}
+ if launch_args:
+ overrides["run_config"]["launch"] = launch_args
+ if scheduler_args:
+ overrides["run_config"]["scheduler"] = scheduler_args
+ if settings:
+ overrides["run_config"]["settings"] = settings
+
+ if scheduler_job:
+ overrides["run_config"]["sweep_args"] = args
+ else:
+ overrides["args"] = args
+
+ # configure scheduler job resource
+ resource = scheduler_args.get("resource")
+ if resource:
+ if resource == "local-process" and scheduler_job:
+ wandb.termerror(
+ "Scheduler jobs cannot be run with the 'local-process' resource"
+ )
+ return
+ if resource == "local-process" and scheduler_args.get("docker_image"):
+ wandb.termerror(
+ "Scheduler jobs cannot be run with the 'local-process' resource and a docker image"
+ )
+ return
+ else: # no resource set, default local-process if not scheduler job, else container
+ resource = "local-process" if not scheduler_job else "local-container"
+
+ # Launch job spec for the Scheduler
+ launch_scheduler_spec = launch_utils.construct_launch_spec(
+ uri=Scheduler.PLACEHOLDER_URI,
+ api=api,
+ name="Scheduler.WANDB_SWEEP_ID",
+ project=project,
+ entity=entity,
+ docker_image=scheduler_args.get("docker_image"),
+ resource=resource,
+ entry_point=entrypoint,
+ resource_args=scheduler_args.get("resource_args", {}),
+ repository=launch_args.get("registry", {}).get("url", None),
+ job=scheduler_job,
+ version=None,
+ launch_config={"overrides": overrides},
+ run_id="WANDB_SWEEP_ID", # scheduler inits run with sweep_id=run_id
+ author=None, # author gets passed into scheduler override args
+ )
+ launch_scheduler_with_queue = json.dumps(
+ {
+ "queue": queue,
+ "run_queue_project": launch_utils.LAUNCH_DEFAULT_PROJECT,
+ "run_spec": json.dumps(launch_scheduler_spec),
+ }
+ )
+
+ sweep_id, warnings = api.upsert_sweep(
+ sweep_config,
+ project=project,
+ entity=entity,
+ obj_id=sweep_obj_id, # if resuming
+ launch_scheduler=launch_scheduler_with_queue,
+ state="PENDING",
+ prior_runs=prior_runs,
+ template_variable_values=scheduler_args.get("template_variables", None),
+ )
+ sweep_utils.handle_sweep_config_violations(warnings)
+ # Log nicely formatted sweep information
+ styled_id = click.style(sweep_id, fg="yellow")
+ wandb.termlog(f"{'Resumed' if resume_id else 'Created'} sweep with ID: {styled_id}")
+ sweep_url = wandb_sdk.wandb_sweep._get_sweep_url(api, sweep_id)
+ if sweep_url:
+ styled_url = click.style(sweep_url, underline=True, fg="blue")
+ wandb.termlog(f"View sweep at: {styled_url}")
+ wandb.termlog(f"Scheduler added to launch queue ({queue})")
+
+
+@cli.command(help=f"Launch or queue a W&B Job. See {url_registry.url('wandb-launch')}")
+@click.option(
+ "--uri",
+ "-u",
+ metavar="(str)",
+ default=None,
+ help="Local path or git repo uri to launch. If provided this command will "
+ "create a job from the specified uri.",
+)
+@click.option(
+ "--job",
+ "-j",
+ metavar="(str)",
+ default=None,
+ help="Name of the job to launch. If passed in, launch does not require a uri.",
+)
+@click.option(
+ "--entry-point",
+ "-E",
+ metavar="NAME",
+ default=None,
+ help="""Entry point within project. [default: main]. If the entry point is not found,
+ attempts to run the project file with the specified name as a script,
+ using 'python' to run .py files and the default shell (specified by
+ environment variable $SHELL) to run .sh files. If passed in, will override the entrypoint value passed in using a config file.""",
+)
+@click.option(
+ "--git-version",
+ "-g",
+ metavar="GIT-VERSION",
+ hidden=True,
+ help="Version of the project to run, as a Git commit reference for Git projects.",
+)
+@click.option(
+ "--build-context",
+ metavar="(str)",
+ help="Path to the build context within the source code. Defaults to the "
+ "root of the source code. Compatible only with -u.",
+)
+@click.option(
+ "--job-name",
+ "-J",
+ metavar="(str)",
+ default=None,
+ hidden=True,
+ help="Name for the job created if the -u,--uri flag is passed in.",
+)
+@click.option(
+ "--name",
+ envvar="WANDB_NAME",
+ help="""Name of the run under which to launch the run. If not
+ specified, a random run name will be used to launch run. If passed in, will override the name passed in using a config file.""",
+)
+@click.option(
+ "--entity",
+ "-e",
+ metavar="(str)",
+ default=None,
+ help="""Name of the target entity which the new run will be sent to. Defaults to using the entity set by local wandb/settings folder.
+ If passed in, will override the entity value passed in using a config file.""",
+)
+@click.option(
+ "--project",
+ "-p",
+ metavar="(str)",
+ default=None,
+ help="""Name of the target project which the new run will be sent to. Defaults to using the project name given by the source uri
+ or for github runs, the git repo name. If passed in, will override the project value passed in using a config file.""",
+)
+@click.option(
+ "--resource",
+ "-r",
+ metavar="BACKEND",
+ default=None,
+ help="""Execution resource to use for run. Supported values: 'local-process', 'local-container', 'kubernetes', 'sagemaker', 'gcp-vertex'.
+ This is now a required parameter if pushing to a queue with no resource configuration.
+ If passed in, will override the resource value passed in using a config file.""",
+)
+@click.option(
+ "--docker-image",
+ "-d",
+ default=None,
+ metavar="DOCKER IMAGE",
+ help="""Specific docker image you'd like to use. In the form name:tag.
+ If passed in, will override the docker image value passed in using a config file.""",
+)
+@click.option(
+ "--base-image",
+ "-B",
+ default=None,
+ metavar="BASE IMAGE",
+ help="""Docker image to run job code in. Incompatible with --docker-image.""",
+)
+@click.option(
+ "--config",
+ "-c",
+ metavar="FILE",
+ help="""Path to JSON file (must end in '.json') or JSON string which will be passed
+ as a launch config. Dictation how the launched run will be configured.""",
+)
+@click.option(
+ "--set-var",
+ "-v",
+ "cli_template_vars",
+ default=None,
+ multiple=True,
+ help="""Set template variable values for queues with allow listing enabled,
+ as key-value pairs e.g. `--set-var key1=value1 --set-var key2=value2`""",
+)
+@click.option(
+ "--queue",
+ "-q",
+ is_flag=False,
+ flag_value="default",
+ default=None,
+ help="""Name of run queue to push to. If none, launches single run directly. If supplied without
+ an argument (`--queue`), defaults to queue 'default'. Else, if name supplied, specified run queue must exist under the
+ project and entity supplied.""",
+)
+@click.option(
+ "--async",
+ "run_async",
+ is_flag=True,
+ help="""Flag to run the job asynchronously. Defaults to false, i.e. unless --async is set, wandb launch will wait for
+ the job to finish. This option is incompatible with --queue; asynchronous options when running with an agent should be
+ set on wandb launch-agent.""",
+)
+@click.option(
+ "--resource-args",
+ "-R",
+ metavar="FILE",
+ help="""Path to JSON file (must end in '.json') or JSON string which will be passed
+ as resource args to the compute resource. The exact content which should be
+ provided is different for each execution backend. See documentation for layout of this file.""",
+)
+@click.option(
+ "--build",
+ "-b",
+ is_flag=True,
+ hidden=True,
+ help="Flag to build an associated job and push to queue as an image job.",
+)
+@click.option(
+ "--repository",
+ "-rg",
+ is_flag=False,
+ default=None,
+ hidden=True,
+ help="Name of a remote repository. Will be used to push a built image to.",
+)
+# TODO: this is only included for back compat. But we should remove this in the future
+@click.option(
+ "--project-queue",
+ "-pq",
+ default=None,
+ hidden=True,
+ help="Name of the project containing the queue to push to. If none, defaults to entity level queues.",
+)
+@click.option(
+ "--dockerfile",
+ "-D",
+ default=None,
+ help="Path to the Dockerfile used to build the job, relative to the job's root",
+)
+@click.option(
+ "--priority",
+ "-P",
+ default=None,
+ type=click.Choice(["critical", "high", "medium", "low"]),
+ help="""When --queue is passed, set the priority of the job. Launch jobs with higher priority
+ are served first. The order, from highest to lowest priority, is: critical, high, medium, low""",
+)
+@display_error
+def launch(
+ uri,
+ job,
+ entry_point,
+ git_version,
+ build_context,
+ name,
+ resource,
+ entity,
+ project,
+ docker_image,
+ base_image,
+ config,
+ cli_template_vars,
+ queue,
+ run_async,
+ resource_args,
+ build,
+ repository,
+ project_queue,
+ dockerfile,
+ priority,
+ job_name,
+):
+ """Start a W&B run from the given URI.
+
+ The URI can bea wandb URI, a GitHub repo uri, or a local path). In the case of a
+ wandb URI the arguments used in the original run will be used by default. These
+ arguments can be overridden using the args option, or specifying those arguments in
+ the config's 'overrides' key, 'args' field as a list of strings.
+
+ Running `wandb launch [URI]` will launch the run directly. To add the run to a
+ queue, run `wandb launch [URI] --queue [optional queuename]`.
+ """
+ logger.info(
+ f"=== Launch called with kwargs {locals()} CLI Version: {wandb.__version__}==="
+ )
+ from wandb.sdk.launch._launch import _launch
+ from wandb.sdk.launch.create_job import _create_job
+ from wandb.sdk.launch.utils import _is_git_uri
+
+ api = _get_cling_api()
+ wandb._sentry.configure_scope(process_context="launch_cli")
+
+ if run_async and queue is not None:
+ raise LaunchError(
+ "Cannot use both --async and --queue with wandb launch, see help for details."
+ )
+
+ if queue and docker_image and not project:
+ raise LaunchError(
+ "Cannot use --queue and --docker together without a project. Please specify a project with --project or -p."
+ )
+
+ if priority is not None and queue is None:
+ raise LaunchError("--priority flag requires --queue to be set")
+
+ if resource_args is not None:
+ resource_args = util.load_json_yaml_dict(resource_args)
+ if resource_args is None:
+ raise LaunchError("Invalid format for resource-args")
+ else:
+ resource_args = {}
+
+ if entry_point is not None:
+ entry_point = shlex.split(entry_point)
+
+ if config is not None:
+ config = util.load_json_yaml_dict(config)
+ if config is None:
+ raise LaunchError("Invalid format for config")
+ else:
+ config = {}
+
+ resource = resource or config.get("resource")
+
+ if build and queue is None:
+ raise LaunchError("Build flag requires a queue to be set")
+
+ try:
+ launch_utils.check_logged_in(api)
+ except Exception:
+ wandb.termerror(f"Error running job: {traceback.format_exc()}")
+
+ run_id = config.get("run_id")
+
+ # If URI was provided, we need to create a job from it.
+ if uri:
+ if entry_point is None:
+ raise LaunchError(
+ "Cannot provide a uri without an entry point. Please provide an "
+ "entry point with --entry-point or -E."
+ )
+ if job is not None:
+ raise LaunchError("Cannot provide both a uri and a job name.")
+ job_type = (
+ "git" if _is_git_uri(uri) else "code"
+ ) # TODO: Add support for local URIs with git.
+ if entity is None:
+ entity = launch_utils.get_default_entity(api, config)
+ artifact, _, _ = _create_job(
+ api,
+ job_type,
+ uri,
+ entrypoint=" ".join(entry_point),
+ git_hash=git_version,
+ name=job_name,
+ project=project,
+ base_image=base_image,
+ build_context=build_context,
+ dockerfile=dockerfile,
+ entity=entity,
+ )
+ if artifact is None:
+ raise LaunchError(f"Failed to create job from uri: {uri}")
+ job = f"{entity}/{project}/{artifact.name}"
+
+ if dockerfile:
+ if "overrides" in config:
+ config["overrides"]["dockerfile"] = dockerfile
+ else:
+ config["overrides"] = {"dockerfile": dockerfile}
+
+ if priority is not None:
+ priority_map = {
+ "critical": 0,
+ "high": 1,
+ "medium": 2,
+ "low": 3,
+ }
+ priority = priority_map[priority.lower()]
+
+ template_variables = None
+ if cli_template_vars:
+ if queue is None:
+ raise LaunchError("'--set-var' flag requires queue to be set")
+ if entity is None:
+ entity = launch_utils.get_default_entity(api, config)
+ public_api = PublicApi()
+ runqueue = RunQueue(client=public_api.client, name=queue, entity=entity)
+ template_variables = launch_utils.fetch_and_validate_template_variables(
+ runqueue, cli_template_vars
+ )
+
+ if queue is None:
+ # direct launch
+ try:
+ run = asyncio.run(
+ _launch(
+ api,
+ job,
+ project=project,
+ entity=entity,
+ docker_image=docker_image,
+ name=name,
+ entry_point=entry_point,
+ version=git_version,
+ resource=resource,
+ resource_args=resource_args,
+ launch_config=config,
+ synchronous=(not run_async),
+ run_id=run_id,
+ repository=repository,
+ )
+ )
+ if asyncio.run(run.get_status()).state in [
+ "failed",
+ "stopped",
+ "preempted",
+ ]:
+ wandb.termerror("Launched run exited with non-zero status")
+ sys.exit(1)
+ except LaunchError as e:
+ logger.exception("An error occurred.")
+ wandb._sentry.exception(e)
+ sys.exit(e)
+ except ExecutionError as e:
+ logger.exception("An error occurred.")
+ wandb._sentry.exception(e)
+ sys.exit(e)
+ except asyncio.CancelledError:
+ sys.exit(0)
+ else:
+ try:
+ _launch_add(
+ api,
+ job,
+ config,
+ template_variables,
+ project,
+ entity,
+ queue,
+ resource,
+ entry_point,
+ name,
+ git_version,
+ docker_image,
+ project_queue,
+ resource_args,
+ build=build,
+ run_id=run_id,
+ repository=repository,
+ priority=priority,
+ )
+
+ except Exception as e:
+ wandb._sentry.exception(e)
+ raise
+
+
+@cli.command(
+ context_settings=CONTEXT,
+ help="Run a W&B launch agent.",
+)
+@click.pass_context
+@click.option(
+ "--queue",
+ "-q",
+ "queues",
+ default=None,
+ multiple=True,
+ help="The name of a queue for the agent to watch. Multiple -q flags supported.",
+)
+@click.option(
+ "--entity",
+ "-e",
+ default=None,
+ help="The entity to use. Defaults to current logged-in user",
+)
+@click.option(
+ "--log-file",
+ "-l",
+ default=None,
+ help=(
+ "Destination for internal agent logs. Use - for stdout. "
+ "By default all agents logs will go to debug.log in your wandb/ "
+ "subdirectory or WANDB_DIR if set."
+ ),
+)
+@click.option(
+ "--max-jobs",
+ "-j",
+ default=None,
+ help="The maximum number of launch jobs this agent can run in parallel. Defaults to 1. Set to -1 for no upper limit",
+)
+@click.option(
+ "--config", "-c", default=None, help="path to the agent config yaml to use"
+)
+@click.option(
+ "--url",
+ "-u",
+ default=None,
+ hidden=True,
+ help="a wandb client registration URL, this is generated in the UI",
+)
+@click.option("--verbose", "-v", count=True, help="Display verbose output")
+@display_error
+def launch_agent(
+ ctx,
+ entity=None,
+ queues=None,
+ max_jobs=None,
+ config=None,
+ url=None,
+ log_file=None,
+ verbose=0,
+):
+ logger.info(
+ f"=== Launch-agent called with kwargs {locals()} CLI Version: {wandb.__version__} ==="
+ )
+ if url is not None:
+ raise LaunchError(
+ "--url is not supported in this version, upgrade with: pip install -u wandb"
+ )
+
+ import wandb.sdk.launch._launch as _launch
+
+ if log_file is not None:
+ _launch.set_launch_logfile(log_file)
+
+ api = _get_cling_api()
+ wandb._sentry.configure_scope(process_context="launch_agent")
+ agent_config, api = _launch.resolve_agent_config(
+ entity, max_jobs, queues, config, verbose
+ )
+
+ if len(agent_config.get("queues")) == 0:
+ raise LaunchError(
+ "To launch an agent please specify a queue or a list of queues in the configuration file or cli."
+ )
+
+ launch_utils.check_logged_in(api)
+
+ wandb.termlog("Starting launch agent ✨")
+ try:
+ _launch.create_and_run_agent(api, agent_config)
+ except Exception as e:
+ wandb._sentry.exception(e)
+ raise
+
+
+@cli.command(context_settings=CONTEXT, help="Run the W&B agent")
+@click.pass_context
+@click.option(
+ "--project",
+ "-p",
+ default=None,
+ help="""The name of the project where W&B runs created from the sweep are sent to. If the project is not specified, the run is sent to a project labeled 'Uncategorized'.""",
+)
+@click.option(
+ "--entity",
+ "-e",
+ default=None,
+ help="""The username or team name where you want to send W&B runs created by the sweep to. Ensure that the entity you specify already exists. If you don't specify an entity, the run will be sent to your default entity, which is usually your username.""",
+)
+@click.option(
+ "--count", default=None, type=int, help="The max number of runs for this agent."
+)
+@click.argument("sweep_id")
+@display_error
+def agent(ctx, project, entity, count, sweep_id):
+ api = _get_cling_api()
+ if not api.is_authenticated:
+ wandb.termlog("Login to W&B to use the sweep agent feature")
+ ctx.invoke(login, no_offline=True)
+ api = _get_cling_api(reset=True)
+
+ wandb.termlog("Starting wandb agent 🕵️")
+ wandb_agent.agent(sweep_id, entity=entity, project=project, count=count)
+
+ # you can send local commands like so:
+ # agent_api.command({'type': 'run', 'program': 'train.py',
+ # 'args': ['--max_epochs=10']})
+
+
+@cli.command(
+ context_settings=RUN_CONTEXT, help="Run a W&B launch sweep scheduler (Experimental)"
+)
+@click.pass_context
+@click.argument("sweep_id")
+@display_error
+def scheduler(
+ ctx,
+ sweep_id,
+):
+ api = InternalApi()
+ if not api.is_authenticated:
+ wandb.termlog("Login to W&B to use the sweep scheduler feature")
+ ctx.invoke(login, no_offline=True)
+ api = InternalApi(reset=True)
+
+ wandb._sentry.configure_scope(process_context="sweep_scheduler")
+ wandb.termlog("Starting a Launch Scheduler 🚀")
+ from wandb.sdk.launch.sweeps import load_scheduler
+
+ # TODO(gst): remove this monstrosity
+ # Future-proofing hack to pull any kwargs that get passed in through the CLI
+ kwargs = {}
+ for i, _arg in enumerate(ctx.args):
+ if isinstance(_arg, str) and _arg.startswith("--"):
+ # convert input kwargs from hyphens to underscores
+ _key = _arg[2:].replace("-", "_")
+ _args = ctx.args[i + 1]
+ if str.isdigit(_args):
+ _args = int(_args)
+ kwargs[_key] = _args
+ try:
+ sweep_type = kwargs.get("sweep_type", "wandb")
+ _scheduler = load_scheduler(scheduler_type=sweep_type)(
+ api,
+ sweep_id=sweep_id,
+ **kwargs,
+ )
+ _scheduler.start()
+ except Exception as e:
+ wandb._sentry.exception(e)
+ raise
+
+
+@cli.group(help="Commands for managing and viewing W&B jobs")
+def job() -> None:
+ pass
+
+
+@job.command("list", help="List jobs in a project")
+@click.option(
+ "--project",
+ "-p",
+ envvar=env.PROJECT,
+ help="The project you want to list jobs from.",
+)
+@click.option(
+ "--entity",
+ "-e",
+ default="models",
+ envvar=env.ENTITY,
+ help="The entity the jobs belong to",
+)
+def _list(project, entity):
+ wandb.termlog(f"Listing jobs in {entity}/{project}")
+ public_api = PublicApi()
+ try:
+ jobs = public_api.list_jobs(entity=entity, project=project)
+ except wandb.errors.CommError as e:
+ wandb.termerror(f"{e}")
+ return
+
+ if len(jobs) == 0:
+ wandb.termlog("No jobs found")
+ return
+
+ for job in jobs:
+ aliases = []
+ if len(job["edges"]) == 0:
+ # deleted?
+ continue
+
+ name = job["edges"][0]["node"]["artifactSequence"]["name"]
+ for version in job["edges"]:
+ aliases += [x["alias"] for x in version["node"]["aliases"]]
+
+ # only list the most recent 10 job versions
+ aliases_str = ",".join(aliases[::-1])
+ wandb.termlog(f"{name} -- versions ({len(aliases)}): {aliases_str}")
+
+
+@job.command(
+ help="Describe a launch job. Provide the launch job in the form of: entity/project/job-name:alias-or-version"
+)
+@click.argument("job")
+def describe(job):
+ public_api = PublicApi()
+ try:
+ job = public_api.job(name=job)
+ except wandb.errors.CommError as e:
+ wandb.termerror(f"{e}")
+ return
+
+ for key in job._job_info:
+ if key.startswith("_"):
+ continue
+ wandb.termlog(f"{key}: {job._job_info[key]}")
+
+
+@job.command(
+ no_args_is_help=True,
+)
+@click.option(
+ "--project",
+ "-p",
+ envvar=env.PROJECT,
+ help="The project you want to list jobs from.",
+)
+@click.option(
+ "--entity",
+ "-e",
+ envvar=env.ENTITY,
+ help="The entity the jobs belong to",
+)
+@click.option(
+ "--name",
+ "-n",
+ help="Name for the job",
+)
+@click.option(
+ "--description",
+ "-d",
+ help="Description for the job",
+)
+@click.option(
+ "--alias",
+ "-a",
+ "aliases",
+ help="Alias for the job",
+ multiple=True,
+ default=tuple(),
+)
+@click.option(
+ "--entry-point",
+ "-E",
+ "entrypoint",
+ help="Entrypoint to the script, including an executable and an entrypoint "
+ "file. Required for code or repo jobs. If --build-context is provided, "
+ "paths in the entrypoint command will be relative to the build context.",
+)
+@click.option(
+ "--git-hash",
+ "-g",
+ "git_hash",
+ type=str,
+ help="Commit reference to use as the source for git jobs",
+)
+@click.option(
+ "--runtime",
+ "-r",
+ type=str,
+ help="Python runtime to execute the job",
+)
+@click.option(
+ "--build-context",
+ "-b",
+ type=str,
+ help="Path to the build context from the root of the job source code. If "
+ "provided, this is used as the base path for the Dockerfile and entrypoint.",
+)
+@click.option(
+ "--base-image",
+ "-B",
+ type=str,
+ help="Base image to use for the job. Incompatible with image jobs.",
+)
+@click.option(
+ "--dockerfile",
+ "-D",
+ type=str,
+ help="Path to the Dockerfile for the job. If --build-context is provided, "
+ "the Dockerfile path will be relative to the build context.",
+)
+@click.argument(
+ "job_type",
+ type=click.Choice(("git", "code", "image")),
+)
+@click.option(
+ "--service",
+ "-s",
+ "services",
+ multiple=True,
+ callback=parse_service_config,
+ help="Service configurations in format serviceName=policy. Valid policies: always, never",
+ hidden=True,
+)
+@click.option(
+ "--schema",
+ type=str,
+ help="Path to the schema file for the job.",
+ hidden=True,
+)
+@click.argument("path")
+def create(
+ path,
+ project,
+ entity,
+ name,
+ job_type,
+ description,
+ aliases,
+ entrypoint,
+ git_hash,
+ runtime,
+ build_context,
+ base_image,
+ dockerfile,
+ services,
+ schema,
+):
+ """Create a job from a source, without a wandb run.
+
+ Jobs can be of three types, git, code, or image.
+
+ git: A git source, with an entrypoint either in the path or provided explicitly pointing to the main python executable.
+ code: A code path, containing a requirements.txt file.
+ image: A docker image.
+ """
+ from wandb.sdk.launch.create_job import _create_job
+
+ api = _get_cling_api()
+ wandb._sentry.configure_scope(process_context="job_create")
+
+ entity = entity or os.getenv("WANDB_ENTITY") or api.default_entity
+ if not entity:
+ wandb.termerror("No entity provided, use --entity or set WANDB_ENTITY")
+ return
+
+ project = project or os.getenv("WANDB_PROJECT")
+ if not project:
+ wandb.termerror("No project provided, use --project or set WANDB_PROJECT")
+ return
+
+ if entrypoint is None and job_type in ["git", "code"]:
+ wandb.termwarn(
+ f"No entrypoint provided for {job_type} job, defaulting to main.py"
+ )
+ entrypoint = "main.py"
+
+ if job_type == "image" and base_image:
+ wandb.termerror("Cannot provide --base-image/-B for an `image` job")
+ return
+
+ if schema:
+ schema_dict = util.load_json_yaml_dict(schema)
+ if schema_dict is None:
+ wandb.termerror(f"Invalid format for schema file: {schema}")
+ return
+
+ artifact, action, aliases = _create_job(
+ api=api,
+ path=path,
+ entity=entity,
+ project=project,
+ name=name,
+ job_type=job_type,
+ description=description,
+ aliases=list(aliases),
+ entrypoint=entrypoint,
+ git_hash=git_hash,
+ runtime=runtime,
+ build_context=build_context,
+ base_image=base_image,
+ dockerfile=dockerfile,
+ services=services,
+ schema=schema_dict if schema else None,
+ )
+ if not artifact:
+ wandb.termerror("Job creation failed")
+ return
+
+ artifact_path = f"{entity}/{project}/{artifact.name}"
+ msg = f"{action} job: {click.style(artifact_path, fg='yellow')}"
+ if len(aliases) == 1:
+ alias_str = click.style(aliases[0], fg="yellow")
+ msg += f", with alias: {alias_str}"
+ elif len(aliases) > 1:
+ alias_str = click.style(", ".join(aliases), fg="yellow")
+ msg += f", with aliases: {alias_str}"
+
+ wandb.termlog(msg)
+ web_url = util.app_url(api.settings().get("base_url"))
+ url = click.style(f"{web_url}/{entity}/{project}/jobs", underline=True)
+ wandb.termlog(f"View all jobs in project '{project}' here: {url}\n")
+
+
+@cli.command(context_settings=CONTEXT, help="Run the W&B local sweep controller")
+@click.option("--verbose", is_flag=True, default=False, help="Display verbose output")
+@click.argument("sweep_id")
+@display_error
+def controller(verbose, sweep_id):
+ click.echo("Starting wandb controller...")
+ from wandb import controller as wandb_controller
+
+ tuner = wandb_controller(sweep_id)
+ tuner.run(verbose=verbose)
+
+
+@cli.command(context_settings=RUN_CONTEXT, name="docker-run")
+@click.pass_context
+@click.argument("docker_run_args", nargs=-1)
+def docker_run(ctx, docker_run_args):
+ """Wrap `docker run` and adds WANDB_API_KEY and WANDB_DOCKER environment variables.
+
+ This will also set the runtime to nvidia if the nvidia-docker executable is present
+ on the system and --runtime wasn't set.
+
+ See `docker run --help` for more details.
+ """
+ import wandb.docker
+
+ api = InternalApi()
+ args = list(docker_run_args)
+ if len(args) > 0 and args[0] == "run":
+ args.pop(0)
+ if len([a for a in args if a.startswith("--runtime")]) == 0 and _HAS_NVIDIA_DOCKER:
+ args = ["--runtime", "nvidia"] + args
+ # TODO: image_from_docker_args uses heuristics to find the docker image arg, there are likely cases
+ # where this won't work
+ image = util.image_from_docker_args(args)
+ resolved_image = None
+ if image:
+ resolved_image = wandb.docker.image_id(image)
+ if resolved_image:
+ args = ["-e", f"WANDB_DOCKER={resolved_image}"] + args
+ else:
+ wandb.termlog(
+ "Couldn't detect image argument, running command without the WANDB_DOCKER env variable"
+ )
+ if api.api_key:
+ args = ["-e", f"WANDB_API_KEY={api.api_key}"] + args
+ else:
+ wandb.termlog(
+ "Not logged in, run `wandb login` from the host machine to enable result logging"
+ )
+ subprocess.call(["docker", "run"] + args)
+
+
+@cli.command(context_settings=RUN_CONTEXT)
+@click.pass_context
+@click.argument("docker_run_args", nargs=-1)
+@click.argument("docker_image", required=False)
+@click.option(
+ "--nvidia/--no-nvidia",
+ default=_HAS_NVIDIA_DOCKER,
+ help="Use the nvidia runtime, defaults to nvidia if nvidia-docker is present",
+)
+@click.option(
+ "--digest", is_flag=True, default=False, help="Output the image digest and exit"
+)
+@click.option(
+ "--jupyter/--no-jupyter", default=False, help="Run jupyter lab in the container"
+)
+@click.option(
+ "--dir", default="/app", help="Which directory to mount the code in the container"
+)
+@click.option("--no-dir", is_flag=True, help="Don't mount the current directory")
+@click.option(
+ "--shell", default="/bin/bash", help="The shell to start the container with"
+)
+@click.option("--port", default="8888", help="The host port to bind jupyter on")
+@click.option("--cmd", help="The command to run in the container")
+@click.option(
+ "--no-tty", is_flag=True, default=False, help="Run the command without a tty"
+)
+@display_error
+def docker(
+ ctx,
+ docker_run_args,
+ docker_image,
+ nvidia,
+ digest,
+ jupyter,
+ dir,
+ no_dir,
+ shell,
+ port,
+ cmd,
+ no_tty,
+):
+ """Run your code in a docker container.
+
+ W&B docker lets you run your code in a docker image ensuring wandb is configured. It
+ adds the WANDB_DOCKER and WANDB_API_KEY environment variables to your container and
+ mounts the current directory in /app by default. You can pass additional args which
+ will be added to `docker run` before the image name is declared, we'll choose a
+ default image for you if one isn't passed:
+
+ ```sh
+ wandb docker -v /mnt/dataset:/app/data
+ wandb docker gcr.io/kubeflow-images-public/tensorflow-1.12.0-notebook-cpu:v0.4.0 --jupyter
+ wandb docker wandb/deepo:keras-gpu --no-tty --cmd "python train.py --epochs=5"
+ ```
+
+ By default, we override the entrypoint to check for the existence of wandb and
+ install it if not present. If you pass the --jupyter flag we will ensure jupyter is
+ installed and start jupyter lab on port 8888. If we detect nvidia-docker on your
+ system we will use the nvidia runtime. If you just want wandb to set environment
+ variable to an existing docker run command, see the wandb docker-run command.
+ """
+ api = InternalApi()
+ if not _HAS_DOCKER:
+ raise ClickException("Docker not installed, install it from https://docker.com")
+
+ import wandb.docker
+
+ args = list(docker_run_args)
+ image = docker_image or ""
+ # remove run for users used to nvidia-docker
+ if len(args) > 0 and args[0] == "run":
+ args.pop(0)
+ if image == "" and len(args) > 0:
+ image = args.pop(0)
+ # If the user adds docker args without specifying an image (should be rare)
+ if not util.docker_image_regex(image.split("@")[0]):
+ if image:
+ args = args + [image]
+ image = wandb.docker.default_image(gpu=nvidia)
+ subprocess.call(["docker", "pull", image])
+ _, repo_name, tag = wandb.docker.parse(image)
+
+ resolved_image = wandb.docker.image_id(image)
+ if resolved_image is None:
+ raise ClickException(
+ f"Couldn't find image locally or in a registry, try running `docker pull {image}`"
+ )
+ if digest:
+ sys.stdout.write(resolved_image)
+ exit(0)
+
+ existing = wandb.docker.shell(["ps", "-f", f"ancestor={resolved_image}", "-q"])
+ if existing:
+ if click.confirm(
+ "Found running container with the same image, do you want to attach?"
+ ):
+ subprocess.call(["docker", "attach", existing.split("\n")[0]])
+ exit(0)
+ cwd = os.getcwd()
+ command = [
+ "docker",
+ "run",
+ "-e",
+ "LANG=C.UTF-8",
+ "-e",
+ f"WANDB_DOCKER={resolved_image}",
+ "--ipc=host",
+ "-v",
+ wandb.docker.entrypoint + ":/wandb-entrypoint.sh",
+ "--entrypoint",
+ "/wandb-entrypoint.sh",
+ ]
+ if nvidia:
+ command.extend(["--runtime", "nvidia"])
+ if not no_dir:
+ # TODO: We should default to the working directory if defined
+ command.extend(["-v", cwd + ":" + dir, "-w", dir])
+ if api.api_key:
+ command.extend(["-e", f"WANDB_API_KEY={api.api_key}"])
+ else:
+ wandb.termlog(
+ "Couldn't find WANDB_API_KEY, run `wandb login` to enable streaming metrics"
+ )
+ if jupyter:
+ command.extend(["-e", "WANDB_ENSURE_JUPYTER=1", "-p", port + ":8888"])
+ no_tty = True
+ cmd = f"jupyter lab --no-browser --ip=0.0.0.0 --allow-root --NotebookApp.token= --notebook-dir {dir}"
+ command.extend(args)
+ if no_tty:
+ command.extend([image, shell, "-c", cmd])
+ else:
+ if cmd:
+ command.extend(["-e", f"WANDB_COMMAND={cmd}"])
+ command.extend(["-it", image, shell])
+ wandb.termlog("Launching docker container \U0001f6a2")
+ subprocess.call(command)
+
+
+@cli.command(
+ context_settings=RUN_CONTEXT,
+ help="Start a local W&B container (deprecated, see wandb server --help)",
+ hidden=True,
+)
+@click.pass_context
+@click.option("--port", "-p", default="8080", help="The host port to bind W&B local on")
+@click.option(
+ "--env", "-e", default=[], multiple=True, help="Env vars to pass to wandb/local"
+)
+@click.option(
+ "--daemon/--no-daemon", default=True, help="Run or don't run in daemon mode"
+)
+@click.option(
+ "--upgrade", is_flag=True, default=False, help="Upgrade to the most recent version"
+)
+@click.option(
+ "--edge", is_flag=True, default=False, help="Run the bleeding edge", hidden=True
+)
+@display_error
+def local(ctx, *args, **kwargs):
+ wandb.termwarn("`wandb local` has been replaced with `wandb server start`.")
+ ctx.invoke(start, *args, **kwargs)
+
+
+@cli.group(help="Commands for operating a local W&B server")
+def server():
+ pass
+
+
+@server.command(context_settings=RUN_CONTEXT, help="Start a local W&B server")
+@click.pass_context
+@click.option(
+ "--port", "-p", default="8080", help="The host port to bind W&B server on"
+)
+@click.option(
+ "--env", "-e", default=[], multiple=True, help="Env vars to pass to wandb/local"
+)
+@click.option(
+ "--daemon/--no-daemon", default=True, help="Run or don't run in daemon mode"
+)
+@click.option(
+ "--upgrade",
+ is_flag=True,
+ default=False,
+ help="Upgrade to the most recent version",
+ hidden=True,
+)
+@click.option(
+ "--edge", is_flag=True, default=False, help="Run the bleeding edge", hidden=True
+)
+@display_error
+def start(ctx, port, env, daemon, upgrade, edge):
+ api = InternalApi()
+ if not _HAS_DOCKER:
+ raise ClickException("Docker not installed, install it from https://docker.com")
+
+ import wandb.docker
+
+ local_image_sha = wandb.docker.image_id("wandb/local").split("wandb/local")[-1]
+ registry_image_sha = wandb.docker.image_id_from_registry("wandb/local").split(
+ "wandb/local"
+ )[-1]
+ if local_image_sha != registry_image_sha:
+ if upgrade:
+ subprocess.call(["docker", "pull", "wandb/local"])
+ else:
+ wandb.termlog(
+ "A new version of the W&B server is available, upgrade by calling `wandb server start --upgrade`"
+ )
+ running = subprocess.check_output(
+ ["docker", "ps", "--filter", "name=^wandb-local$", "--format", "{{.ID}}"]
+ )
+ if running != b"":
+ if upgrade:
+ subprocess.call(["docker", "stop", "wandb-local"])
+ else:
+ wandb.termerror(
+ "A container named wandb-local is already running, run `docker stop wandb-local` if you want to start a new instance"
+ )
+ exit(1)
+ image = "docker.pkg.github.com/wandb/core/local" if edge else "wandb/local"
+ username = getpass.getuser()
+ env_vars = ["-e", f"LOCAL_USERNAME={username}"]
+ for e in env:
+ env_vars.append("-e")
+ env_vars.append(e)
+ command = [
+ "docker",
+ "run",
+ "--rm",
+ "-v",
+ "wandb:/vol",
+ "-p",
+ port + ":8080",
+ "--name",
+ "wandb-local",
+ ] + env_vars
+ host = f"http://localhost:{port}"
+ api.set_setting("base_url", host, globally=True, persist=True)
+ if daemon:
+ command += ["-d"]
+ command += [image]
+
+ # DEVNULL is only in py3
+ try:
+ from subprocess import DEVNULL
+ except ImportError:
+ DEVNULL = open(os.devnull, "wb") # noqa: N806
+ code = subprocess.call(command, stdout=DEVNULL)
+ if daemon:
+ if code != 0:
+ wandb.termerror(
+ "Failed to launch the W&B server container, see the above error."
+ )
+ exit(1)
+ else:
+ wandb.termlog(f"W&B server started at http://localhost:{port} \U0001f680")
+ wandb.termlog("You can stop the server by running `wandb server stop`")
+ if not api.api_key:
+ # Let the server start before potentially launching a browser
+ time.sleep(2)
+ ctx.invoke(login, host=host)
+
+
+@server.command(context_settings=RUN_CONTEXT, help="Stop a local W&B server")
+def stop():
+ if not _HAS_DOCKER:
+ raise ClickException("Docker not installed, install it from https://docker.com")
+ subprocess.call(["docker", "stop", "wandb-local"])
+
+
+@cli.group(help="Commands for interacting with artifacts")
+def artifact():
+ pass
+
+
+@artifact.command(context_settings=CONTEXT, help="Upload an artifact to wandb")
+@click.argument("path")
+@click.option(
+ "--name", "-n", help="The name of the artifact to push: project/artifact_name"
+)
+@click.option("--description", "-d", help="A description of this artifact")
+@click.option("--type", "-t", default="dataset", help="The type of the artifact")
+@click.option(
+ "--alias",
+ "-a",
+ default=["latest"],
+ multiple=True,
+ help="An alias to apply to this artifact",
+)
+@click.option("--id", "run_id", help="The run you want to upload to.")
+@click.option(
+ "--resume",
+ is_flag=True,
+ default=None,
+ help="Resume the last run from your current directory.",
+)
+@click.option(
+ "--skip_cache",
+ is_flag=True,
+ default=False,
+ help="Skip caching while uploading artifact files.",
+)
+@click.option(
+ "--policy",
+ default="mutable",
+ type=click.Choice(["mutable", "immutable"]),
+ help="Set the storage policy while uploading artifact files.",
+)
+@display_error
+def put(
+ path,
+ name,
+ description,
+ type,
+ alias,
+ run_id,
+ resume,
+ skip_cache,
+ policy,
+):
+ if name is None:
+ name = os.path.basename(path)
+ public_api = PublicApi()
+ entity, project, artifact_name = public_api._parse_artifact_path(name)
+ if project is None:
+ project = click.prompt("Enter the name of the project you want to use")
+ # TODO: settings nightmare...
+ api = InternalApi()
+ api.set_setting("entity", entity)
+ api.set_setting("project", project)
+ artifact = wandb.Artifact(name=artifact_name, type=type, description=description)
+ artifact_path = f"{entity}/{project}/{artifact_name}:{alias[0]}"
+ if os.path.isdir(path):
+ wandb.termlog(f'Uploading directory {path} to: "{artifact_path}" ({type})')
+ artifact.add_dir(path, skip_cache=skip_cache, policy=policy)
+ elif os.path.isfile(path):
+ wandb.termlog(f'Uploading file {path} to: "{artifact_path}" ({type})')
+ artifact.add_file(path, skip_cache=skip_cache, policy=policy)
+ elif "://" in path:
+ wandb.termlog(
+ f'Logging reference artifact from {path} to: "{artifact_path}" ({type})'
+ )
+ artifact.add_reference(path)
+ else:
+ raise ClickException("Path argument must be a file or directory")
+
+ with wandb.init(
+ entity=entity,
+ project=project,
+ config={"path": path},
+ job_type="cli_put",
+ id=run_id,
+ resume=resume,
+ ) as run:
+ run.log_artifact(artifact, aliases=alias)
+ artifact.wait()
+
+ wandb.termlog(
+ "Artifact uploaded, use this artifact in a run by adding:\n", prefix=False
+ )
+ wandb.termlog(
+ f' artifact = run.use_artifact("{artifact.source_qualified_name}")\n',
+ prefix=False,
+ )
+
+
+@artifact.command(context_settings=CONTEXT, help="Download an artifact from wandb")
+@click.argument("path")
+@click.option("--root", help="The directory you want to download the artifact to")
+@click.option("--type", help="The type of artifact you are downloading")
+@display_error
+def get(path, root, type):
+ public_api = PublicApi()
+ entity, project, artifact_name = public_api._parse_artifact_path(path)
+ if project is None:
+ project = click.prompt("Enter the name of the project you want to use")
+
+ try:
+ artifact_parts = artifact_name.split(":")
+ if len(artifact_parts) > 1:
+ version = artifact_parts[1]
+ artifact_name = artifact_parts[0]
+ else:
+ version = "latest"
+ if is_artifact_registry_project(project):
+ organization = path.split("/")[0] if path.count("/") == 2 else ""
+ # set entity to match the settings since in above code it was potentially set to an org
+ settings_entity = public_api.settings["entity"] or public_api.default_entity
+ # Registry artifacts are under the org entity. Because we offer a shorthand and alias for this path,
+ # we need to fetch the org entity to for the user behind the scenes.
+ entity = SDKInternalApi()._resolve_org_entity_name(
+ entity=settings_entity, organization=organization
+ )
+ full_path = f"{entity}/{project}/{artifact_name}:{version}"
+ wandb.termlog(
+ "Downloading {type} artifact {full_path}".format(
+ type=type or "dataset", full_path=full_path
+ )
+ )
+ artifact = public_api.artifact(full_path, type=type)
+ path = artifact.download(root=root)
+ wandb.termlog(f"Artifact downloaded to {path}")
+ except ValueError:
+ raise ClickException("Unable to download artifact")
+
+
+@artifact.command(
+ context_settings=CONTEXT, help="List all artifacts in a wandb project"
+)
+@click.argument("path")
+@click.option("--type", "-t", help="The type of artifacts to list")
+@display_error
+def ls(path, type):
+ public_api = PublicApi()
+ if type is not None:
+ types = [public_api.artifact_type(type, path)]
+ else:
+ types = public_api.artifact_types(path)
+
+ for kind in types:
+ for collection in kind.collections():
+ versions = public_api.artifact_versions(
+ kind.type,
+ "/".join([kind.entity, kind.project, collection.name]),
+ per_page=1,
+ )
+ latest = next(versions)
+ wandb.termlog(
+ f"{kind.type:<15s}{latest.updated_at:<15s}{util.to_human_size(latest.size):>15s} {latest.name:<20s}"
+ )
+
+
+@artifact.group(help="Commands for interacting with the artifact cache")
+def cache():
+ pass
+
+
+@cache.command(
+ context_settings=CONTEXT,
+ help="Clean up less frequently used files from the artifacts cache",
+)
+@click.argument("target_size")
+@click.option("--remove-temp/--no-remove-temp", default=False, help="Remove temp files")
+@display_error
+def cleanup(target_size, remove_temp):
+ target_size = util.from_human_size(target_size)
+ cache = get_artifact_file_cache()
+ reclaimed_bytes = cache.cleanup(target_size, remove_temp)
+ wandb.termlog(f"Reclaimed {util.to_human_size(reclaimed_bytes)} of space")
+
+
+@cli.command(context_settings=CONTEXT, help="Pull files from Weights & Biases")
+@click.argument("run", envvar=env.RUN_ID)
+@click.option(
+ "--project", "-p", envvar=env.PROJECT, help="The project you want to download."
+)
+@click.option(
+ "--entity",
+ "-e",
+ default="models",
+ envvar=env.ENTITY,
+ help="The entity to scope the listing to.",
+)
+@display_error
+def pull(run, project, entity):
+ api = InternalApi()
+ project, run = api.parse_slug(run, project=project)
+ urls = api.download_urls(project, run=run, entity=entity)
+ if len(urls) == 0:
+ raise ClickException("Run has no files")
+ click.echo(f"Downloading: {click.style(project, bold=True)}/{run}")
+
+ for name in urls:
+ if api.file_current(name, urls[name]["md5"]):
+ click.echo(f"File {name} is up to date")
+ else:
+ length, response = api.download_file(urls[name]["url"])
+ # TODO: I had to add this because some versions in CI broke click.progressbar
+ sys.stdout.write(f"File {name}\r")
+ dirname = os.path.dirname(name)
+ if dirname != "":
+ filesystem.mkdir_exists_ok(dirname)
+ with click.progressbar(
+ length=length,
+ label=f"File {name}",
+ fill_char=click.style("&", fg="green"),
+ ) as bar:
+ with open(name, "wb") as f:
+ for data in response.iter_content(chunk_size=4096):
+ f.write(data)
+ bar.update(len(data))
+
+
+@cli.command(
+ context_settings=CONTEXT,
+ help="Restore code, config and docker state for a run. Retrieves code from latest commit if code was not saved with `wandb.save()` or `wandb.init(save_code=True)`.",
+)
+@click.pass_context
+@click.argument("run", envvar=env.RUN_ID)
+@click.option("--no-git", is_flag=True, default=False, help="Don't restore git state")
+@click.option(
+ "--branch/--no-branch",
+ default=True,
+ help="Whether to create a branch or checkout detached",
+)
+@click.option(
+ "--project", "-p", envvar=env.PROJECT, help="The project you wish to upload to."
+)
+@click.option(
+ "--entity", "-e", envvar=env.ENTITY, help="The entity to scope the listing to."
+)
+@display_error
+def restore(ctx, run, no_git, branch, project, entity):
+ from wandb.old.core import wandb_dir
+
+ api = _get_cling_api()
+ if ":" in run:
+ if "/" in run:
+ entity, rest = run.split("/", 1)
+ else:
+ rest = run
+ project, run = rest.split(":", 1)
+ elif run.count("/") > 1:
+ entity, run = run.split("/", 1)
+
+ project, run = api.parse_slug(run, project=project)
+ commit, json_config, patch_content, metadata = api.run_config(
+ project, run=run, entity=entity
+ )
+ repo = metadata.get("git", {}).get("repo")
+ image = metadata.get("docker")
+ restore_message = f"""`wandb restore` needs to be run from the same git repository as the original run.
+Run `git clone {repo}` and restore from there or pass the --no-git flag."""
+ if no_git:
+ commit = None
+ elif not api.git.enabled:
+ if repo:
+ raise ClickException(restore_message)
+ elif image:
+ wandb.termlog(
+ "Original run has no git history. Just restoring config and docker"
+ )
+
+ if commit and api.git.enabled:
+ wandb.termlog(f"Fetching origin and finding commit: {commit}")
+ subprocess.check_call(["git", "fetch", "--all"])
+ try:
+ api.git.repo.commit(commit)
+ except ValueError:
+ wandb.termlog(f"Couldn't find original commit: {commit}")
+ commit = None
+ files = api.download_urls(project, run=run, entity=entity)
+ for filename in files:
+ if filename.startswith("upstream_diff_") and filename.endswith(
+ ".patch"
+ ):
+ commit = filename[len("upstream_diff_") : -len(".patch")]
+ try:
+ api.git.repo.commit(commit)
+ except ValueError:
+ commit = None
+ else:
+ break
+
+ if commit:
+ wandb.termlog(f"Falling back to upstream commit: {commit}")
+ patch_path, _ = api.download_write_file(files[filename])
+ else:
+ raise ClickException(restore_message)
+ else:
+ if patch_content:
+ patch_path = os.path.join(wandb_dir(), "diff.patch")
+ with open(patch_path, "w") as f:
+ f.write(patch_content)
+ else:
+ patch_path = None
+
+ branch_name = f"wandb/{run}"
+ if branch and branch_name not in api.git.repo.branches:
+ api.git.repo.git.checkout(commit, b=branch_name)
+ wandb.termlog(f"Created branch {click.style(branch_name, bold=True)}")
+ elif branch:
+ wandb.termlog(
+ f"Using existing branch, run `git branch -D {branch_name}` from master for a clean checkout"
+ )
+ api.git.repo.git.checkout(branch_name)
+ else:
+ wandb.termlog(f"Checking out {commit} in detached mode")
+ api.git.repo.git.checkout(commit)
+
+ if patch_path:
+ # we apply the patch from the repository root so git doesn't exclude
+ # things outside the current directory
+ root = api.git.root
+ patch_rel_path = os.path.relpath(patch_path, start=root)
+ # --reject is necessary or else this fails any time a binary file
+ # occurs in the diff
+ exit_code = subprocess.call(
+ ["git", "apply", "--reject", patch_rel_path], cwd=root
+ )
+ if exit_code == 0:
+ wandb.termlog("Applied patch")
+ else:
+ wandb.termerror(
+ "Failed to apply patch, try un-staging any un-committed changes"
+ )
+
+ filesystem.mkdir_exists_ok(wandb_dir())
+ config_path = os.path.join(wandb_dir(), "config.yaml")
+ config = Config()
+ for k, v in json_config.items():
+ if k not in ("_wandb", "wandb_version"):
+ config[k] = v
+ s = b"wandb_version: 1"
+ s += b"\n\n" + yaml.dump(
+ config._as_dict(),
+ Dumper=yaml.SafeDumper,
+ default_flow_style=False,
+ allow_unicode=True,
+ encoding="utf-8",
+ )
+ s = s.decode("utf-8")
+ with open(config_path, "w") as f:
+ f.write(s)
+
+ wandb.termlog(f"Restored config variables to {config_path}")
+ if image:
+ if not metadata["program"].startswith("<") and metadata.get("args") is not None:
+ # TODO: we may not want to default to python here.
+ runner = util.find_runner(metadata["program"]) or ["python"]
+ command = runner + [metadata["program"]] + metadata["args"]
+ cmd = " ".join(command)
+ else:
+ wandb.termlog("Couldn't find original command, just restoring environment")
+ cmd = None
+ wandb.termlog("Docker image found, attempting to start")
+ ctx.invoke(docker, docker_run_args=[image], cmd=cmd)
+
+ return commit, json_config, patch_content, repo, metadata
+
+
+@cli.command("online")
+@display_error
+def online():
+ """Undo `wandb offline`."""
+ api = InternalApi()
+ try:
+ api.clear_setting("mode", persist=True)
+ except configparser.Error:
+ pass
+ click.echo(
+ "W&B online. Running your script from this directory will now sync to the cloud."
+ )
+
+
+@cli.command("offline")
+@display_error
+def offline():
+ """Save data logged to W&B locally without uploading it to the cloud.
+
+ Use `wandb online` or `wandb sync` to upload offline runs.
+ """
+ api = InternalApi()
+ try:
+ api.set_setting("mode", "offline", persist=True)
+ click.echo(
+ "W&B offline. Running your script from this directory will only write metadata locally. Use wandb disabled to completely turn off W&B."
+ )
+ except configparser.Error:
+ click.echo(
+ "Unable to write config, copy and paste the following in your terminal to turn off W&B:\nexport WANDB_MODE=offline"
+ )
+
+
+@cli.command("on", hidden=True)
+@click.pass_context
+@display_error
+def on(ctx):
+ ctx.invoke(online)
+
+
+@cli.command("off", hidden=True)
+@click.pass_context
+@display_error
+def off(ctx):
+ ctx.invoke(offline)
+
+
+@cli.command("status", help="Show configuration settings")
+@click.option(
+ "--settings/--no-settings", help="Show the current settings", default=True
+)
+def status(settings):
+ api = _get_cling_api()
+ if settings:
+ click.echo(click.style("Current Settings", bold=True))
+ settings = api.settings()
+ click.echo(
+ json.dumps(settings, sort_keys=True, indent=2, separators=(",", ": "))
+ )
+
+
+@cli.command("disabled", help="Disable W&B.")
+@click.option(
+ "--service",
+ is_flag=True,
+ show_default=True,
+ default=True,
+ help="Disable W&B service",
+)
+def disabled(service):
+ api = InternalApi()
+ try:
+ api.set_setting("mode", "disabled", persist=True)
+ click.echo("W&B disabled.")
+ except configparser.Error:
+ click.echo(
+ "Unable to write config, copy and paste the following in your terminal to turn off W&B:\nexport WANDB_MODE=disabled"
+ )
+
+
+@cli.command("enabled", help="Enable W&B.")
+@click.option(
+ "--service",
+ is_flag=True,
+ show_default=True,
+ default=True,
+ help="Enable W&B service",
+)
+def enabled(service):
+ api = InternalApi()
+ try:
+ api.set_setting("mode", "online", persist=True)
+ click.echo("W&B enabled.")
+ except configparser.Error:
+ click.echo(
+ "Unable to write config, copy and paste the following in your terminal to turn on W&B:\nexport WANDB_MODE=online"
+ )
+
+
+@cli.command(
+ context_settings=CONTEXT,
+ help="""Checks and verifies local instance of W&B. W&B checks for:
+
+ Checks that the host is not `api.wandb.ai` (host check).
+
+ Verifies if the user is logged in correctly using the provided API key (login check).
+
+ Checks that requests are made over HTTPS (secure requests).
+
+ Validates the CORS (Cross-Origin Resource Sharing) configuration of the
+ object store (CORS configuration).
+
+ Logs metrics, saves, and downloads files to check if runs are correctly
+ recorded and accessible (run check).
+
+ Saves and downloads artifacts to verify that the artifact storage and
+ retrieval system is working as expected (artifact check).
+
+ Tests the GraphQL endpoint by uploading a file to ensure it can handle
+ signed URL uploads (GraphQL PUT check).
+
+ Checks the ability to send large payloads through the proxy (large payload check).
+
+ Verifies that the installed version of the W&B package is up-to-date and
+ compatible with the server (W&B version check).
+
+ Creates and executes a sweep to ensure that sweep functionality is
+ working correctly (sweeps check).
+""",
+)
+@click.option("--host", default=None, help="Test a specific instance of W&B")
+def verify(host):
+ # TODO: (kdg) Build this all into a WandbVerify object, and clean this up.
+ os.environ["WANDB_SILENT"] = "true"
+ os.environ["WANDB_PROJECT"] = "verify"
+ api = _get_cling_api()
+ reinit = False
+ if host is None:
+ host = api.settings("base_url")
+ wandb.termlog(f"Default host selected: {host}")
+ # if the given host does not match the default host, re-run init
+ elif host != api.settings("base_url"):
+ reinit = True
+
+ tmp_dir = tempfile.mkdtemp()
+ wandb.termlog(
+ "Find detailed logs for this test at: {}".format(os.path.join(tmp_dir, "wandb"))
+ )
+ os.chdir(tmp_dir)
+ os.environ["WANDB_BASE_URL"] = host
+ wandb.login(host=host)
+ if reinit:
+ api = _get_cling_api(reset=True)
+ if not wandb_verify.check_host(host):
+ sys.exit(1)
+ if not wandb_verify.check_logged_in(api, host):
+ sys.exit(1)
+ url_success, url = wandb_verify.check_graphql_put(api, host)
+ large_post_success = wandb_verify.check_large_post()
+ wandb_verify.check_secure_requests(
+ api.settings("base_url"),
+ "Checking requests to base url",
+ "Connections are not made over https. SSL required for secure communications.",
+ )
+ if url:
+ wandb_verify.check_secure_requests(
+ url,
+ "Checking requests made over signed URLs",
+ "Signed URL requests not made over https. SSL is required for secure communications.",
+ )
+ wandb_verify.check_cors_configuration(url, host)
+ wandb_verify.check_wandb_version(api)
+ check_run_success = wandb_verify.check_run(api)
+ check_artifacts_success = wandb_verify.check_artifacts()
+ check_sweeps_success = wandb_verify.check_sweeps(api)
+ if not (
+ check_artifacts_success
+ and check_run_success
+ and large_post_success
+ and url_success
+ and check_sweeps_success
+ ):
+ sys.exit(1)
+
+
+cli.add_command(beta)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/data_types.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/data_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..f28e283d8436d1b366cb59ba66d4171df88bcda7
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/data_types.py
@@ -0,0 +1,66 @@
+"""This module defines data types for logging rich, interactive visualizations to W&B.
+
+Data types include common media types, like images, audio, and videos,
+flexible containers for information, like tables and HTML, and more.
+
+For more on logging media, see [our guide](https://docs.wandb.com/guides/track/log/media)
+
+For more on logging structured data for interactive dataset and model analysis,
+see [our guide to W&B Tables](https://docs.wandb.com/guides/models/tables/).
+
+All of these special data types are subclasses of WBValue. All the data types
+serialize to JSON, since that is what wandb uses to save the objects locally
+and upload them to the W&B server.
+"""
+
+from .sdk.data_types.audio import Audio
+from .sdk.data_types.base_types.media import BatchableMedia, Media
+from .sdk.data_types.base_types.wb_value import WBValue
+from .sdk.data_types.bokeh import Bokeh
+from .sdk.data_types.graph import Graph, Node
+from .sdk.data_types.helper_types.bounding_boxes_2d import BoundingBoxes2D
+from .sdk.data_types.helper_types.classes import Classes
+from .sdk.data_types.helper_types.image_mask import ImageMask
+from .sdk.data_types.histogram import Histogram
+from .sdk.data_types.html import Html
+from .sdk.data_types.image import Image
+from .sdk.data_types.molecule import Molecule
+from .sdk.data_types.object_3d import Object3D, box3d
+from .sdk.data_types.plotly import Plotly
+from .sdk.data_types.saved_model import _SavedModel
+from .sdk.data_types.table import JoinedTable, PartitionedTable, Table
+from .sdk.data_types.trace_tree import WBTraceTree
+from .sdk.data_types.video import Video
+
+# Note: we are importing everything from the sdk/data_types to maintain a namespace for now.
+# Once we fully type this file and move it all into sdk, then we will need to clean up the
+# other internal imports
+
+__all__ = [
+ # Untyped Exports
+ "Audio",
+ "Table",
+ "JoinedTable",
+ "PartitionedTable",
+ "Bokeh",
+ "Node",
+ "Graph",
+ # Typed Exports
+ "Histogram",
+ "Html",
+ "Image",
+ "Molecule",
+ "box3d",
+ "Object3D",
+ "Plotly",
+ "Video",
+ "WBTraceTree",
+ "_SavedModel",
+ "WBValue",
+ "Media",
+ "BatchableMedia",
+ # Typed Legacy Exports (I'd like to remove these)
+ "ImageMask",
+ "BoundingBoxes2D",
+ "Classes",
+]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/docker/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/docker/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..761748bb8bece16f4b95a25995f6d05ef710748d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/docker/__init__.py
@@ -0,0 +1,290 @@
+import json
+import logging
+import os
+import shutil
+import subprocess
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+from wandb.docker import names
+from wandb.errors import Error
+
+
+class DockerError(Error):
+ """Raised when attempting to execute a docker command."""
+
+ def __init__(
+ self,
+ command_launched: List[str],
+ return_code: int,
+ stdout: Optional[bytes] = None,
+ stderr: Optional[bytes] = None,
+ ) -> None:
+ command_launched_str = " ".join(command_launched)
+ error_msg = (
+ f"The docker command executed was `{command_launched_str}`.\n"
+ f"It returned with code {return_code}\n"
+ )
+ if stdout is not None:
+ error_msg += f"The content of stdout is '{stdout.decode()}'\n"
+ else:
+ error_msg += (
+ "The content of stdout can be found above the "
+ "stacktrace (it wasn't captured).\n"
+ )
+ if stderr is not None:
+ error_msg += f"The content of stderr is '{stderr.decode()}'\n"
+ else:
+ error_msg += (
+ "The content of stderr can be found above the "
+ "stacktrace (it wasn't captured)."
+ )
+ super().__init__(error_msg)
+
+
+entrypoint = os.path.join(
+ os.path.dirname(os.path.abspath(__file__)), "wandb-entrypoint.sh"
+)
+log = logging.getLogger(__name__)
+
+
+def shell(cmd: List[str]) -> Optional[str]:
+ """Simple wrapper for calling docker,.
+
+ returning None on error and the output on success
+ """
+ try:
+ return (
+ subprocess.check_output(["docker"] + cmd, stderr=subprocess.STDOUT)
+ .decode("utf8")
+ .strip()
+ )
+ except subprocess.CalledProcessError as e:
+ print(e) # noqa: T201
+ return None
+
+
+_buildx_installed = None
+
+
+def is_buildx_installed() -> bool:
+ """Return `True` if docker buildx is installed and working."""
+ global _buildx_installed
+ if _buildx_installed is not None:
+ return _buildx_installed # type: ignore
+ if not shutil.which("docker"):
+ _buildx_installed = False
+ else:
+ help_output = shell(["buildx", "--help"])
+ _buildx_installed = help_output is not None and "buildx" in help_output
+ return _buildx_installed
+
+
+def is_docker_installed() -> bool:
+ """Return `True` if docker is installed and working, else `False`."""
+ try:
+ # Run the docker --version command
+ result = subprocess.run(
+ ["docker", "--version"],
+ capture_output=True,
+ )
+ if result.returncode == 0:
+ return True
+ else:
+ return False
+ except FileNotFoundError:
+ # If docker command is not found
+ return False
+
+
+def build(
+ tags: List[str], file: str, context_path: str, platform: Optional[str] = None
+) -> str:
+ use_buildx = is_buildx_installed()
+ command = ["buildx", "build"] if use_buildx else ["build"]
+ command += ["--load"] if should_add_load_argument(platform) and use_buildx else []
+ if platform:
+ command += ["--platform", platform]
+ build_tags = []
+ for tag in tags:
+ build_tags += ["-t", tag]
+ args = ["docker"] + command + build_tags + ["-f", file, context_path]
+ stdout = run_command_live_output(
+ args,
+ )
+ return stdout
+
+
+def should_add_load_argument(platform: Optional[str]) -> bool:
+ # the load option does not work when multiple platforms are specified:
+ # https://github.com/docker/buildx/issues/59
+ if platform is None or (platform and "," not in platform):
+ return True
+ return False
+
+
+def run_command_live_output(args: List[Any]) -> str:
+ with subprocess.Popen(
+ args,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ universal_newlines=True,
+ bufsize=1,
+ ) as process:
+ stdout = ""
+ while True:
+ chunk = os.read(process.stdout.fileno(), 4096) # type: ignore
+ if not chunk:
+ break
+ index = chunk.find(b"\r")
+ if index != -1:
+ print(chunk.decode(), end="") # noqa: T201
+ else:
+ stdout += chunk.decode()
+ print(chunk.decode(), end="\r") # noqa: T201
+
+ print(stdout) # noqa: T201
+
+ return_code = process.wait()
+ if return_code != 0:
+ raise DockerError(args, return_code, stdout.encode())
+
+ return stdout
+
+
+def run(
+ args: List[Any],
+ capture_stdout: bool = True,
+ capture_stderr: bool = True,
+ input: Optional[bytes] = None,
+ return_stderr: bool = False,
+ env: Optional[Dict[str, str]] = None,
+) -> Union[str, Tuple[str, str]]:
+ args = [str(x) for x in args]
+ subprocess_env = dict(os.environ)
+ subprocess_env.update(env or {})
+ if args[1] == "buildx":
+ subprocess_env["DOCKER_CLI_EXPERIMENTAL"] = "enabled"
+ stdout_dest: Optional[int] = subprocess.PIPE if capture_stdout else None
+ stderr_dest: Optional[int] = subprocess.PIPE if capture_stderr else None
+
+ completed_process = subprocess.run(
+ args, input=input, stdout=stdout_dest, stderr=stderr_dest, env=subprocess_env
+ )
+ if completed_process.returncode != 0:
+ raise DockerError(
+ args,
+ completed_process.returncode,
+ completed_process.stdout,
+ completed_process.stderr,
+ )
+
+ if return_stderr:
+ return (
+ _post_process_stream(completed_process.stdout),
+ _post_process_stream(completed_process.stderr),
+ )
+ else:
+ return _post_process_stream(completed_process.stdout)
+
+
+def _post_process_stream(stream: Optional[bytes]) -> str:
+ if stream is None:
+ return ""
+ decoded_stream = stream.decode()
+ if len(decoded_stream) != 0 and decoded_stream[-1] == "\n":
+ decoded_stream = decoded_stream[:-1]
+ return decoded_stream
+
+
+def default_image(gpu: bool = False) -> str:
+ tag = "all"
+ if not gpu:
+ tag += "-cpu"
+ return f"wandb/deepo:{tag}"
+
+
+def parse_repository_tag(repo_name: str) -> Tuple[str, Optional[str]]:
+ parts = repo_name.rsplit("@", 1)
+ if len(parts) == 2:
+ return parts[0], parts[1]
+ parts = repo_name.rsplit(":", 1)
+ if len(parts) == 2 and "/" not in parts[1]:
+ return parts[0], parts[1]
+ return repo_name, None
+
+
+def parse(image_name: str) -> Tuple[str, str, str]:
+ repository, tag = parse_repository_tag(image_name)
+ registry, repo_name = names.resolve_repository_name(repository)
+ if registry == "docker.io":
+ registry = "index.docker.io"
+ return registry, repo_name, (tag or "latest")
+
+
+def image_id_from_registry(image_name: str) -> Optional[str]:
+ """Query the image manifest to get its full ID including the digest.
+
+ Args:
+ image_name: The image name, such as "wandb/local".
+
+ Returns:
+ The image name followed by its digest, like "wandb/local@sha256:...".
+ """
+ # https://docs.docker.com/reference/cli/docker/buildx/imagetools/inspect
+ inspect_cmd = ["buildx", "imagetools", "inspect", image_name]
+ format_args = ["--format", r"{{.Name}}@{{.Manifest.Digest}}"]
+ return shell([*inspect_cmd, *format_args])
+
+
+def image_id(image_name: str) -> Optional[str]:
+ """Retrieve the image id from the local docker daemon or remote registry."""
+ if "@sha256:" in image_name:
+ return image_name
+ else:
+ digests = shell(["inspect", image_name, "--format", "{{json .RepoDigests}}"])
+
+ if digests is None:
+ return image_id_from_registry(image_name)
+
+ try:
+ return json.loads(digests)[0]
+ except (ValueError, IndexError):
+ return image_id_from_registry(image_name)
+
+
+def get_image_uid(image_name: str) -> int:
+ """Retrieve the image default uid through brute force."""
+ image_uid = shell(["run", image_name, "id", "-u"])
+ return int(image_uid) if image_uid else -1
+
+
+def push(image: str, tag: str) -> Optional[str]:
+ """Push an image to a remote registry."""
+ return shell(["push", f"{image}:{tag}"])
+
+
+def login(username: str, password: str, registry: str) -> Optional[str]:
+ """Login to a registry."""
+ return shell(["login", "--username", username, "--password", password, registry])
+
+
+def tag(image_name: str, tag: str) -> Optional[str]:
+ """Tag an image."""
+ return shell(["tag", image_name, tag])
+
+
+__all__ = [
+ "shell",
+ "build",
+ "run",
+ "image_id",
+ "image_id_from_registry",
+ "is_docker_installed",
+ "parse",
+ "parse_repository_tag",
+ "default_image",
+ "get_image_uid",
+ "push",
+ "login",
+ "tag",
+]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/docker/names.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/docker/names.py
new file mode 100644
index 0000000000000000000000000000000000000000..384d39a9e21329bcb71abfbcacdcfa9b3c78bbd2
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/docker/names.py
@@ -0,0 +1,40 @@
+from __future__ import annotations
+
+
+class InvalidRepositoryError(Exception):
+ """The given string is not a valid repository name."""
+
+
+def resolve_repository_name(repo_name: str) -> tuple[str, str]:
+ if "://" in repo_name:
+ raise InvalidRepositoryError(
+ f"Repository name cannot contain a scheme ({repo_name})"
+ )
+
+ index_name, remote_name = split_repo_name(repo_name)
+ if index_name[0] == "-" or index_name[-1] == "-":
+ raise InvalidRepositoryError(
+ f"Invalid index name ({index_name}). Cannot begin or end with a hyphen."
+ )
+ return resolve_index_name(index_name), remote_name
+
+
+def resolve_index_name(index_name: str) -> str:
+ index_name = convert_to_hostname(index_name)
+ if index_name == "index.docker.io":
+ index_name = "docker.io"
+ return index_name
+
+
+def split_repo_name(repo_name: str) -> tuple[str, str]:
+ parts = repo_name.split("/", 1)
+ if len(parts) == 1 or (
+ "." not in parts[0] and ":" not in parts[0] and parts[0] != "localhost"
+ ):
+ # This is a docker index repo (ex: username/foobar or ubuntu)
+ return "docker.io", repo_name
+ return parts[0], parts[1]
+
+
+def convert_to_hostname(url: str) -> str:
+ return url.replace("http://", "").replace("https://", "").split("/", 1)[0]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/docker/wandb-entrypoint.sh b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/docker/wandb-entrypoint.sh
new file mode 100644
index 0000000000000000000000000000000000000000..f2d4af61de2eb53973f8ee5eb6e619521d66a63a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/docker/wandb-entrypoint.sh
@@ -0,0 +1,33 @@
+#!/bin/sh
+set -e
+
+wandb="\x1b[34m\x1b[1mwandb\x1b[0m"
+/bin/echo -e "${wandb}: Checking image for required packages."
+
+if ! [ -x "$(command -v python)" ]; then
+ /bin/echo -e "${wandb}: python not installed, can't use wandb with this image."
+ exit 1
+fi
+
+if ! [ -x "$(command -v wandb)" ]; then
+ /bin/echo -e "${wandb}: wandb not installed, installing."
+ pip install wandb --upgrade
+else
+ ver=$(wandb --version)
+ /bin/echo -e "${wandb}: Found $ver"
+fi
+
+if [ "$WANDB_ENSURE_JUPYTER" = "1" ]; then
+ if ! [ -x "$(command -v jupyter-lab)" ]; then
+ /bin/echo -e "${wandb}: jupyter not installed, installing."
+ pip install jupyterlab
+ /bin/echo -e "${wandb}: starting jupyter, you can access it at: http://127.0.0.1:8888"
+ fi
+fi
+
+if ! [ -z "$WANDB_COMMAND" ]; then
+ /bin/echo $WANDB_COMMAND >> ~/.bash_history
+ /bin/echo -e "${wandb}: Command added to history, press up arrow to access it."
+ /bin/echo -e "${wandb}: $WANDB_COMMAND"
+fi
+exec "$@"
\ No newline at end of file
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/env.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/env.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b69eace7c3fc846fbc443776d66aadd2161268e
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/env.py
@@ -0,0 +1,535 @@
+"""All of W&B's environment variables.
+
+Getters and putters for all of them should go here. That way it'll be easier to
+avoid typos with names and be consistent about environment variables' semantics.
+
+Environment variables are not the authoritative source for these values in many
+cases.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from pathlib import Path
+from typing import MutableMapping
+
+import platformdirs
+
+CONFIG_PATHS = "WANDB_CONFIG_PATHS"
+SWEEP_PARAM_PATH = "WANDB_SWEEP_PARAM_PATH"
+SHOW_RUN = "WANDB_SHOW_RUN"
+DEBUG = "WANDB_DEBUG"
+SILENT = "WANDB_SILENT"
+QUIET = "WANDB_QUIET"
+INITED = "WANDB_INITED"
+DIR = "WANDB_DIR"
+# Deprecate DESCRIPTION in a future release
+DESCRIPTION = "WANDB_DESCRIPTION"
+NAME = "WANDB_NAME"
+NOTEBOOK_NAME = "WANDB_NOTEBOOK_NAME"
+NOTES = "WANDB_NOTES"
+USERNAME = "WANDB_USERNAME"
+USER_EMAIL = "WANDB_USER_EMAIL"
+PROJECT = "WANDB_PROJECT"
+ENTITY = "WANDB_ENTITY"
+ORGANIZATION = "WANDB_ORGANIZATION"
+BASE_URL = "WANDB_BASE_URL"
+APP_URL = "WANDB_APP_URL"
+PROGRAM = "WANDB_PROGRAM"
+ARGS = "WANDB_ARGS"
+MODE = "WANDB_MODE"
+START_METHOD = "WANDB_START_METHOD"
+RESUME = "WANDB_RESUME"
+RUN_ID = "WANDB_RUN_ID"
+RUN_STORAGE_ID = "WANDB_RUN_STORAGE_ID"
+RUN_GROUP = "WANDB_RUN_GROUP"
+RUN_DIR = "WANDB_RUN_DIR"
+SWEEP_ID = "WANDB_SWEEP_ID"
+HTTP_TIMEOUT = "WANDB_HTTP_TIMEOUT"
+FILE_PUSHER_TIMEOUT = "WANDB_FILE_PUSHER_TIMEOUT"
+API_KEY = "WANDB_API_KEY"
+IDENTITY_TOKEN_FILE = "WANDB_IDENTITY_TOKEN_FILE"
+CREDENTIALS_FILE = "WANDB_CREDENTIALS_FILE"
+JOB_TYPE = "WANDB_JOB_TYPE"
+DISABLE_CODE = "WANDB_DISABLE_CODE"
+DISABLE_GIT = "WANDB_DISABLE_GIT"
+GIT_ROOT = "WANDB_GIT_ROOT"
+SAVE_CODE = "WANDB_SAVE_CODE"
+TAGS = "WANDB_TAGS"
+IGNORE = "WANDB_IGNORE_GLOBS"
+ERROR_REPORTING = "WANDB_ERROR_REPORTING"
+CORE_DEBUG = "WANDB_CORE_DEBUG"
+DOCKER = "WANDB_DOCKER"
+AGENT_REPORT_INTERVAL = "WANDB_AGENT_REPORT_INTERVAL"
+AGENT_KILL_DELAY = "WANDB_AGENT_KILL_DELAY"
+AGENT_DISABLE_FLAPPING = "WANDB_AGENT_DISABLE_FLAPPING"
+AGENT_MAX_INITIAL_FAILURES = "WANDB_AGENT_MAX_INITIAL_FAILURES"
+CRASH_NOSYNC_TIME = "WANDB_CRASH_NOSYNC_TIME"
+MAGIC = "WANDB_MAGIC"
+HOST = "WANDB_HOST"
+ANONYMOUS = "WANDB_ANONYMOUS"
+JUPYTER = "WANDB_JUPYTER"
+CONFIG_DIR = "WANDB_CONFIG_DIR"
+DATA_DIR = "WANDB_DATA_DIR"
+ARTIFACT_DIR = "WANDB_ARTIFACT_DIR"
+ARTIFACT_FETCH_FILE_URL_BATCH_SIZE = "WANDB_ARTIFACT_FETCH_FILE_URL_BATCH_SIZE"
+CACHE_DIR = "WANDB_CACHE_DIR"
+DISABLE_SSL = "WANDB_INSECURE_DISABLE_SSL"
+SERVICE = "WANDB_SERVICE"
+SENTRY_DSN = "WANDB_SENTRY_DSN"
+INIT_TIMEOUT = "WANDB_INIT_TIMEOUT"
+GIT_COMMIT = "WANDB_GIT_COMMIT"
+GIT_REMOTE_URL = "WANDB_GIT_REMOTE_URL"
+_EXECUTABLE = "WANDB_X_EXECUTABLE"
+LAUNCH_QUEUE_NAME = "WANDB_LAUNCH_QUEUE_NAME"
+LAUNCH_QUEUE_ENTITY = "WANDB_LAUNCH_QUEUE_ENTITY"
+LAUNCH_TRACE_ID = "WANDB_LAUNCH_TRACE_ID"
+ENABLE_DCGM_PROFILING = "WANDB_ENABLE_DCGM_PROFILING"
+
+# For testing, to be removed in future version
+USE_V1_ARTIFACTS = "_WANDB_USE_V1_ARTIFACTS"
+
+
+def immutable_keys() -> list[str]:
+ """These are env keys that shouldn't change within a single process.
+
+ We use this to maintain certain values between multiple calls to wandb.init within a single process.
+ """
+ return [
+ DIR,
+ ENTITY,
+ PROJECT,
+ API_KEY,
+ IGNORE,
+ DISABLE_CODE,
+ DISABLE_GIT,
+ DOCKER,
+ MODE,
+ BASE_URL,
+ ERROR_REPORTING,
+ CRASH_NOSYNC_TIME,
+ MAGIC,
+ USERNAME,
+ USER_EMAIL,
+ DIR,
+ SILENT,
+ CONFIG_PATHS,
+ ANONYMOUS,
+ RUN_GROUP,
+ JOB_TYPE,
+ TAGS,
+ RESUME,
+ AGENT_REPORT_INTERVAL,
+ HTTP_TIMEOUT,
+ HOST,
+ DATA_DIR,
+ ARTIFACT_DIR,
+ ARTIFACT_FETCH_FILE_URL_BATCH_SIZE,
+ CACHE_DIR,
+ USE_V1_ARTIFACTS,
+ DISABLE_SSL,
+ IDENTITY_TOKEN_FILE,
+ CREDENTIALS_FILE,
+ ]
+
+
+def _env_as_bool(
+ var: str, default: str | None = None, env: MutableMapping | None = None
+) -> bool:
+ if env is None:
+ env = os.environ
+ val = env.get(var, default)
+ if not isinstance(val, str):
+ return False
+ try:
+ return strtobool(val)
+ except ValueError:
+ return False
+
+
+def is_debug(default: str | None = None, env: MutableMapping | None = None) -> bool:
+ return _env_as_bool(DEBUG, default=default, env=env)
+
+
+def is_offline(env: MutableMapping | None = None) -> bool:
+ if env is None:
+ env = os.environ
+ return env.get(MODE) == "offline"
+
+
+def is_quiet() -> bool:
+ return _env_as_bool(QUIET, default="false")
+
+
+def is_silent() -> bool:
+ return _env_as_bool(SILENT, default="false")
+
+
+def error_reporting_enabled() -> bool:
+ return _env_as_bool(ERROR_REPORTING, default="True")
+
+
+def core_debug(default: str | None = None) -> bool:
+ return _env_as_bool(CORE_DEBUG, default=default) or is_debug()
+
+
+def ssl_disabled() -> bool:
+ return _env_as_bool(DISABLE_SSL, default="False")
+
+
+def dcgm_profiling_enabled() -> bool:
+ """Checks whether collecting profiling metrics for Nvidia GPUs using DCGM is requested.
+
+ Note: Enabling this feature can lead to increased resource usage
+ compared to standard monitoring.
+ Requires the `nvidia-dcgm` service to be running on the machine.
+ """
+ return _env_as_bool(ENABLE_DCGM_PROFILING, default="False")
+
+
+def get_error_reporting(
+ default: bool | str = True,
+ env: MutableMapping | None = None,
+) -> bool | str:
+ if env is None:
+ env = os.environ
+
+ return env.get(ERROR_REPORTING, default)
+
+
+def get_run(
+ default: str | None = None, env: MutableMapping | None = None
+) -> str | None:
+ if env is None:
+ env = os.environ
+
+ return env.get(RUN_ID, default)
+
+
+def get_args(
+ default: list[str] | None = None, env: MutableMapping | None = None
+) -> list[str] | None:
+ if env is None:
+ env = os.environ
+ if env.get(ARGS):
+ try:
+ return json.loads(env.get(ARGS, "[]")) # type: ignore
+ except ValueError:
+ return None
+ else:
+ return default or sys.argv[1:]
+
+
+def get_docker(
+ default: str | None = None, env: MutableMapping | None = None
+) -> str | None:
+ if env is None:
+ env = os.environ
+
+ return env.get(DOCKER, default)
+
+
+def get_http_timeout(default: int = 20, env: MutableMapping | None = None) -> int:
+ if env is None:
+ env = os.environ
+
+ return int(env.get(HTTP_TIMEOUT, default))
+
+
+def get_file_pusher_timeout(
+ default: int | None = None,
+ env: MutableMapping | None = None,
+) -> int | None:
+ if env is None:
+ env = os.environ
+
+ timeout = env.get(FILE_PUSHER_TIMEOUT, default)
+ return int(timeout) if timeout else None
+
+
+def get_ignore(
+ default: list[str] | None = None, env: MutableMapping | None = None
+) -> list[str] | None:
+ if env is None:
+ env = os.environ
+ ignore = env.get(IGNORE)
+ if ignore is not None:
+ return ignore.split(",")
+ else:
+ return default
+
+
+def get_project(
+ default: str | None = None, env: MutableMapping | None = None
+) -> str | None:
+ if env is None:
+ env = os.environ
+
+ return env.get(PROJECT, default)
+
+
+def get_username(
+ default: str | None = None, env: MutableMapping | None = None
+) -> str | None:
+ if env is None:
+ env = os.environ
+
+ return env.get(USERNAME, default)
+
+
+def get_user_email(
+ default: str | None = None, env: MutableMapping | None = None
+) -> str | None:
+ if env is None:
+ env = os.environ
+
+ return env.get(USER_EMAIL, default)
+
+
+def get_entity(
+ default: str | None = None, env: MutableMapping | None = None
+) -> str | None:
+ if env is None:
+ env = os.environ
+
+ return env.get(ENTITY, default)
+
+
+def get_organization(
+ default: str | None = None, env: MutableMapping | None = None
+) -> str | None:
+ if env is None:
+ env = os.environ
+
+ return env.get(ORGANIZATION, default)
+
+
+def get_base_url(
+ default: str | None = None, env: MutableMapping | None = None
+) -> str | None:
+ if env is None:
+ env = os.environ
+
+ return env.get(BASE_URL, default)
+
+
+def get_app_url(
+ default: str | None = None, env: MutableMapping | None = None
+) -> str | None:
+ if env is None:
+ env = os.environ
+
+ return env.get(APP_URL, default)
+
+
+def get_show_run(default: str | None = None, env: MutableMapping | None = None) -> bool:
+ if env is None:
+ env = os.environ
+
+ return bool(env.get(SHOW_RUN, default))
+
+
+def get_description(
+ default: str | None = None, env: MutableMapping | None = None
+) -> str | None:
+ if env is None:
+ env = os.environ
+
+ return env.get(DESCRIPTION, default)
+
+
+def get_tags(default: str = "", env: MutableMapping | None = None) -> list[str]:
+ if env is None:
+ env = os.environ
+
+ return [tag for tag in env.get(TAGS, default).split(",") if tag]
+
+
+def get_dir(
+ default: str | None = None, env: MutableMapping | None = None
+) -> str | None:
+ if env is None:
+ env = os.environ
+ return env.get(DIR, default)
+
+
+def get_config_paths(
+ default: str | None = None, env: MutableMapping | None = None
+) -> str | None:
+ if env is None:
+ env = os.environ
+ return env.get(CONFIG_PATHS, default)
+
+
+def get_agent_report_interval(
+ default: str | None = None, env: MutableMapping | None = None
+) -> int | None:
+ if env is None:
+ env = os.environ
+ val = env.get(AGENT_REPORT_INTERVAL, default)
+ try:
+ val = int(val) # type: ignore
+ except ValueError:
+ val = None # silently ignore env format errors, caller should handle.
+ return val
+
+
+def get_agent_kill_delay(
+ default: str | None = None, env: MutableMapping | None = None
+) -> int | None:
+ if env is None:
+ env = os.environ
+ val = env.get(AGENT_KILL_DELAY, default)
+ try:
+ val = int(val) # type: ignore
+ except ValueError:
+ val = None # silently ignore env format errors, caller should handle.
+ return val
+
+
+def get_crash_nosync_time(
+ default: str | None = None, env: MutableMapping | None = None
+) -> int | None:
+ if env is None:
+ env = os.environ
+ val = env.get(CRASH_NOSYNC_TIME, default)
+ try:
+ val = int(val) # type: ignore
+ except ValueError:
+ val = None # silently ignore env format errors, caller should handle.
+ return val
+
+
+def get_magic(
+ default: str | None = None, env: MutableMapping | None = None
+) -> str | None:
+ if env is None:
+ env = os.environ
+ val = env.get(MAGIC, default)
+ return val
+
+
+def get_data_dir(env: MutableMapping | None = None) -> str:
+ default_dir = platformdirs.user_data_dir("wandb")
+ if env is None:
+ env = os.environ
+ val = env.get(DATA_DIR, default_dir)
+ return val
+
+
+def get_artifact_dir(env: MutableMapping | None = None) -> str:
+ default_dir = os.path.join(".", "artifacts")
+ if env is None:
+ env = os.environ
+ val = env.get(ARTIFACT_DIR, default_dir)
+ return os.path.abspath(str(val))
+
+
+def get_artifact_fetch_file_url_batch_size(env: MutableMapping | None = None) -> int:
+ default_batch_size = 5000
+ if env is None:
+ env = os.environ
+ val = int(env.get(ARTIFACT_FETCH_FILE_URL_BATCH_SIZE, default_batch_size))
+ return val
+
+
+def get_cache_dir(env: MutableMapping | None = None) -> Path:
+ env = env or os.environ
+ return Path(env.get(CACHE_DIR, platformdirs.user_cache_dir("wandb")))
+
+
+def get_use_v1_artifacts(env: MutableMapping | None = None) -> bool:
+ if env is None:
+ env = os.environ
+ val = bool(env.get(USE_V1_ARTIFACTS, False))
+ return val
+
+
+def get_agent_max_initial_failures(
+ default: int | None = None, env: MutableMapping | None = None
+) -> int | None:
+ if env is None:
+ env = os.environ
+ val = env.get(AGENT_MAX_INITIAL_FAILURES, default)
+ try:
+ val = int(val) # type: ignore
+ except ValueError:
+ val = default
+ return val
+
+
+def set_entity(value: str, env: MutableMapping | None = None) -> None:
+ if env is None:
+ env = os.environ
+ env[ENTITY] = value
+
+
+def set_project(value: str, env: MutableMapping | None = None) -> None:
+ if env is None:
+ env = os.environ
+ env[PROJECT] = value or "uncategorized"
+
+
+def should_save_code() -> bool:
+ save_code = _env_as_bool(SAVE_CODE, default="False")
+ code_disabled = _env_as_bool(DISABLE_CODE, default="False")
+ return save_code and not code_disabled
+
+
+def disable_git(env: MutableMapping | None = None) -> bool:
+ if env is None:
+ env = os.environ
+ val = env.get(DISABLE_GIT, default="False")
+ if isinstance(val, str):
+ val = False if val.lower() == "false" else True
+ return val
+
+
+def get_launch_queue_name(env: MutableMapping | None = None) -> str | None:
+ if env is None:
+ env = os.environ
+ val = env.get(LAUNCH_QUEUE_NAME, None)
+ return val
+
+
+def get_launch_queue_entity(env: MutableMapping | None = None) -> str | None:
+ if env is None:
+ env = os.environ
+ val = env.get(LAUNCH_QUEUE_ENTITY, None)
+ return val
+
+
+def get_launch_trace_id(env: MutableMapping | None = None) -> str | None:
+ if env is None:
+ env = os.environ
+ val = env.get(LAUNCH_TRACE_ID, None)
+ return val
+
+
+def get_credentials_file(default: str, env: MutableMapping | None = None) -> Path:
+ """Retrieve the path for the credentials file used to save access tokens.
+
+ The credentials file path can be set via an environment variable, otherwise
+ the default path is used.
+ """
+ if env is None:
+ env = os.environ
+ credentials_file = env.get(CREDENTIALS_FILE, default)
+ return Path(credentials_file)
+
+
+def strtobool(val: str) -> bool:
+ """Convert a string representation of truth to true or false.
+
+ Copied from distutils. distutils was removed in Python 3.12.
+ """
+ val = val.lower()
+
+ if val in ("y", "yes", "t", "true", "on", "1"):
+ return True
+ elif val in ("n", "no", "f", "false", "off", "0"):
+ return False
+ else:
+ raise ValueError(f"invalid truth value {val!r}")
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/errors/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/errors/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1aa45ad8aced101f4bec07df6f1d8972dabffd34
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/errors/__init__.py
@@ -0,0 +1,17 @@
+__all__ = (
+ "Error",
+ "CommError",
+ "AuthenticationError",
+ "UsageError",
+ "UnsupportedError",
+ "WandbCoreNotAvailableError",
+)
+
+from .errors import (
+ AuthenticationError,
+ CommError,
+ Error,
+ UnsupportedError,
+ UsageError,
+ WandbCoreNotAvailableError,
+)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/errors/errors.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/errors/errors.py
new file mode 100644
index 0000000000000000000000000000000000000000..6130cb683a25e4469f4cf81af1f63b32f0c57d62
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/errors/errors.py
@@ -0,0 +1,40 @@
+from __future__ import annotations
+
+
+class Error(Exception):
+ """Base W&B Error.
+
+
+ """
+
+ def __init__(self, message: str, context: dict | None = None) -> None:
+ super().__init__(message)
+ self.message = message
+ # sentry context capture
+ if context:
+ self.context = context
+
+
+class CommError(Error):
+ """Error communicating with W&B servers."""
+
+ def __init__(self, msg: str, exc: Exception | None = None) -> None:
+ self.exc = exc
+ self.message = msg
+ super().__init__(self.message)
+
+
+class AuthenticationError(CommError):
+ """Raised when authentication fails."""
+
+
+class UsageError(Error):
+ """Raised when an invalid usage of the SDK API is detected."""
+
+
+class UnsupportedError(UsageError):
+ """Raised when trying to use a feature that is not supported."""
+
+
+class WandbCoreNotAvailableError(Error):
+ """Raised when wandb core is not available."""
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/errors/links.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/errors/links.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ff87cde68e779ab1d857a347dfbf6bb6445e74e
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/errors/links.py
@@ -0,0 +1,73 @@
+"""Module containing the WBURLs class and WBURL dataclass.
+
+Used to store predefined URLs that can be associated with a name. The URLs are
+shortened using with the `wandb.me` domain, using dub.co as the shortening service.
+If the URLs need to be updates, use the dub.co service to point to the new URL.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+
+@dataclass
+class WBURL:
+ url: str
+ description: str
+
+
+class Registry:
+ """A collection of URLs that can be associated with a name."""
+
+ def __init__(self) -> None:
+ self.urls: dict[str, WBURL] = {
+ "wandb-launch": WBURL(
+ "https://wandb.me/launch",
+ "Link to the W&B launch marketing page",
+ ),
+ "wandb-init": WBURL(
+ "https://wandb.me/wandb-init",
+ "Link to the wandb.init reference documentation page",
+ ),
+ "define-metric": WBURL(
+ "https://wandb.me/define-metric",
+ "Link to the W&B developer guide documentation page on wandb.define_metric",
+ ),
+ "developer-guide": WBURL(
+ "https://wandb.me/developer-guide",
+ "Link to the W&B developer guide top level page",
+ ),
+ "wandb-core": WBURL(
+ "https://wandb.me/wandb-core",
+ "Link to the documentation for the wandb-core service",
+ ),
+ "wandb-server": WBURL(
+ "https://wandb.me/wandb-server",
+ "Link to the documentation for the self-hosted W&B server",
+ ),
+ "multiprocess": WBURL(
+ "https://wandb.me/multiprocess",
+ (
+ "Link to the W&B developer guide documentation page on how to "
+ "use wandb in a multiprocess environment"
+ ),
+ ),
+ }
+
+ def url(self, name: str) -> str:
+ """Get the URL associated with the given name."""
+ wb_url = self.urls.get(name)
+ if wb_url:
+ return wb_url.url
+ raise ValueError(f"URL not found for {name}")
+
+ def description(self, name: str) -> str:
+ """Get the description associated with the given name."""
+ wb_url = self.urls.get(name)
+ if wb_url:
+ return wb_url.description
+ raise ValueError(f"Description not found for {name}")
+
+
+# This is an instance of the Links class that can be used to access the URLs
+url_registry = Registry()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/errors/term.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/errors/term.py
new file mode 100644
index 0000000000000000000000000000000000000000..78ddeced609bb33cfd9486d0b0ac409865c9a243
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/errors/term.py
@@ -0,0 +1,415 @@
+"""Global functions for printing to stderr for wandb."""
+
+from __future__ import annotations
+
+import contextlib
+import logging
+import os
+import re
+import shutil
+import sys
+import threading
+from typing import TYPE_CHECKING, Iterator, Protocol
+
+import click
+
+if TYPE_CHECKING:
+ import wandb
+
+LOG_STRING = click.style("wandb", fg="blue", bold=True)
+LOG_STRING_NOCOLOR = "wandb"
+ERROR_STRING = click.style("ERROR", bg="red", fg="green")
+WARN_STRING = click.style("WARNING", fg="yellow")
+
+_silent: bool = False
+"""If true, _logger is used instead of printing to stderr."""
+
+_logger: SupportsLeveledLogging | None = None
+"""A fallback logger for _silent mode."""
+
+_show_info: bool = True
+"""If false, then termlog() uses silent mode (see _silent)."""
+
+_show_warnings: bool = True
+"""If false, then termwarn() uses silent mode (see _silent)."""
+
+_show_errors: bool = True
+"""If false, then termerror() uses silent mode (see _silent)."""
+
+
+_printed_messages: set[str] = set()
+"""Messages logged with repeat=False."""
+
+_dynamic_text_lock = threading.Lock()
+"""Lock held for dynamic text operations.
+
+All uses of `_dynamic_blocks` and calls to functions that start with
+the `_l_` prefix must be guarded by this lock.
+"""
+
+_dynamic_blocks: list[DynamicBlock] = []
+"""Active dynamic text areas, created with dynamic_text()."""
+
+
+class SupportsLeveledLogging(Protocol):
+ """Portion of the standard logging.Logger used in this module."""
+
+ def info(self, msg: str) -> None: ...
+ def warning(self, msg: str) -> None: ...
+ def error(self, msg: str) -> None: ...
+
+
+def termsetup(
+ settings: wandb.Settings,
+ logger: SupportsLeveledLogging | None,
+) -> None:
+ """Configure the global logging functions.
+
+ Args:
+ settings: The settings object passed to wandb.setup() or wandb.init().
+ logger: A fallback logger to use for "silent" mode. In this mode,
+ the logger is used instead of printing to stderr.
+ """
+ global _silent, _show_info, _show_warnings, _show_errors, _logger
+ _silent = settings.silent
+ _show_info = settings.show_info
+ _show_warnings = settings.show_warnings
+ _show_errors = settings.show_errors
+ _logger = logger
+
+
+@contextlib.contextmanager
+def dynamic_text() -> Iterator[DynamicBlock | None]:
+ """A context manager that provides a handle to a new dynamic text area.
+
+ The text goes to stderr. Returns None if dynamic text is not supported.
+
+ Dynamic text must only be used while `wandb` has control of the terminal,
+ or else text written by other programs will be overwritten. It's
+ appropriate to use during a blocking operation.
+
+ ```
+ with term.dynamic_text() as text_area:
+ if text_area:
+ text_area.set_text("Writing to a terminal.")
+ for i in range(2000):
+ text_area.set_text(f"Still going... ({i}/2000)")
+ time.sleep(0.001)
+ else:
+ wandb.termlog("Writing to a file or dumb terminal.")
+ time.sleep(1)
+ wandb.termlog("Finished 1000/2000 tasks, still working...")
+ time.sleep(1)
+ wandb.termlog("Done!", err=True)
+ ```
+ """
+ # For now, dynamic text always corresponds to the "INFO" level.
+ if _silent or not _show_info:
+ yield None
+ return
+
+ # NOTE: In Jupyter notebooks, this will return False. Notebooks
+ # support ANSI color sequences and the '\r' character, but not
+ # cursor motions or line clear commands.
+ if not _sys_stderr_isatty():
+ yield None
+ return
+
+ # This is a convention to indicate that the terminal doesn't support
+ # clearing the screen / positioning the cursor.
+ if os.environ.get("TERM") == "dumb":
+ yield None
+ return
+
+ # NOTE: On Windows < 10, ANSI escape sequences such as \x1b[Am and \x1b[2K,
+ # used to move the cursor and clear text, aren't supported by the built-in
+ # console. However, we rely on the click library's use of colorama which
+ # emulates support for such sequences.
+ #
+ # For this reason, we don't have special checks for Windows.
+
+ block = DynamicBlock()
+
+ with _dynamic_text_lock:
+ _dynamic_blocks.append(block)
+
+ try:
+ yield block
+ finally:
+ with _dynamic_text_lock:
+ block._lines_to_print = []
+ _l_rerender_dynamic_blocks()
+ _dynamic_blocks.remove(block)
+
+
+def _sys_stderr_isatty() -> bool:
+ """Returns sys.stderr.isatty().
+
+ Defined here for patching in tests.
+ """
+ return sys.stderr.isatty()
+
+
+def termlog(
+ string: str = "",
+ newline: bool = True,
+ repeat: bool = True,
+ prefix: bool = True,
+) -> None:
+ r"""Log an informational message to stderr.
+
+ The message may contain ANSI color sequences and the \n character.
+ Colors are stripped if stderr is not a TTY.
+
+ Args:
+ string: The message to display.
+ newline: Whether to add a newline to the end of the string.
+ repeat: If false, then the string is not printed if an exact match has
+ already been printed through any of the other logging functions
+ in this file.
+ prefix: Whether to include the 'wandb:' prefix.
+ """
+ _log(
+ string,
+ newline=newline,
+ repeat=repeat,
+ prefix=prefix,
+ silent=not _show_info,
+ )
+
+
+def termwarn(
+ string: str,
+ newline: bool = True,
+ repeat: bool = True,
+ prefix: bool = True,
+) -> None:
+ """Log a warning to stderr.
+
+ The arguments are the same as for `termlog()`.
+ """
+ string = "\n".join([f"{WARN_STRING} {s}" for s in string.split("\n")])
+ _log(
+ string,
+ newline=newline,
+ repeat=repeat,
+ prefix=prefix,
+ silent=not _show_warnings,
+ level=logging.WARNING,
+ )
+
+
+def termerror(
+ string: str,
+ newline: bool = True,
+ repeat: bool = True,
+ prefix: bool = True,
+) -> None:
+ """Log an error to stderr.
+
+ The arguments are the same as for `termlog()`.
+ """
+ string = "\n".join([f"{ERROR_STRING} {s}" for s in string.split("\n")])
+ _log(
+ string,
+ newline=newline,
+ repeat=repeat,
+ prefix=prefix,
+ silent=not _show_errors,
+ level=logging.ERROR,
+ )
+
+
+class DynamicBlock:
+ """A handle to a changeable text area in the terminal."""
+
+ def __init__(self):
+ self._lines_to_print = []
+ self._num_lines_printed = 0
+
+ def set_text(self, text: str, prefix=True) -> None:
+ r"""Replace the text in this block.
+
+ Args:
+ text: The text to put in the block, with lines separated
+ by \n characters. The text should not end in \n unless
+ a blank line at the end of the block is desired.
+ prefix: Whether to include the "wandb:" prefix.
+ """
+ with _dynamic_text_lock:
+ self._lines_to_print = text.splitlines()
+
+ if prefix:
+ self._lines_to_print = [
+ f"{LOG_STRING}: {line}" for line in self._lines_to_print
+ ]
+
+ _l_rerender_dynamic_blocks()
+
+ def _l_clear(self) -> None:
+ """Send terminal commands to clear all previously printed lines.
+
+ The lock must be held, and the cursor must be on the line after this
+ block of text.
+ """
+ # NOTE: We rely on the fact that click.echo() uses colorama which
+ # emulates these ANSI sequences on older Windows versions.
+ #
+ # \r move cursor to start of line
+ # \x1b[Am move cursor up
+ # \x1b[2K delete line (sometimes moves cursor)
+ # \r move cursor to start of line
+ move_up_and_delete_line = "\r\x1b[Am\x1b[2K\r"
+ click.echo(
+ move_up_and_delete_line * self._num_lines_printed,
+ file=sys.stderr,
+ nl=False,
+ )
+ self._num_lines_printed = 0
+
+ def _l_print(self) -> None:
+ """Print out this block of text.
+
+ The lock must be held.
+ """
+ if self._lines_to_print:
+ # Trim lines before printing. This is crucial because the \x1b[Am
+ # (cursor up) sequence used when clearing the text moves up by one
+ # visual line, and the terminal may be wrapping long lines onto
+ # multiple visual lines.
+ #
+ # There is no ANSI escape sequence that moves the cursor up by one
+ # "physical" line instead. Note that the user may resize their
+ # terminal.
+ term_width = _shutil_get_terminal_width()
+ click.echo(
+ "\n".join(
+ _ansi_shorten(line, term_width) #
+ for line in self._lines_to_print
+ ),
+ file=sys.stderr,
+ )
+
+ self._num_lines_printed += len(self._lines_to_print)
+
+
+def _shutil_get_terminal_width() -> int:
+ """Returns the width of the terminal.
+
+ Defined here for patching in tests.
+ """
+ columns, _ = shutil.get_terminal_size()
+ return columns
+
+
+_ANSI_RE = re.compile("\x1b\\[(K|.*?m)")
+
+
+def _ansi_shorten(text: str, width: int) -> str:
+ """Shorten text potentially containing ANSI sequences to fit a width."""
+ first_ansi = _ANSI_RE.search(text)
+
+ if not first_ansi:
+ return _raw_shorten(text, width)
+
+ if first_ansi.start() > width - 3:
+ return _raw_shorten(text[: first_ansi.start()], width)
+
+ return text[: first_ansi.end()] + _ansi_shorten(
+ text[first_ansi.end() :],
+ # Key part: the ANSI sequence doesn't reduce the remaining width.
+ width - first_ansi.start(),
+ )
+
+
+def _raw_shorten(text: str, width: int) -> str:
+ """Shorten text to fit a width, replacing the end with "...".
+
+ Unlike textwrap.shorten(), this does not drop whitespace or do anything
+ smart.
+ """
+ if len(text) <= width:
+ return text
+
+ return text[: width - 3] + "..."
+
+
+def _log(
+ string="",
+ newline=True,
+ repeat=True,
+ prefix=True,
+ silent=False,
+ level=logging.INFO,
+) -> None:
+ with _dynamic_text_lock, _l_above_dynamic_text():
+ if not repeat:
+ if string in _printed_messages:
+ return
+
+ if len(_printed_messages) < 1000:
+ _printed_messages.add(string)
+
+ if prefix:
+ string = "\n".join([f"{LOG_STRING}: {s}" for s in string.split("\n")])
+
+ silent = silent or _silent
+ if not silent:
+ click.echo(string, file=sys.stderr, nl=newline)
+ elif not _logger:
+ pass # No fallback logger, so nothing to do.
+ elif level == logging.ERROR:
+ _logger.error(click.unstyle(string))
+ elif level == logging.WARNING:
+ _logger.warning(click.unstyle(string))
+ else:
+ _logger.info(click.unstyle(string))
+
+
+def _l_rerender_dynamic_blocks() -> None:
+ """Clear and re-print all dynamic text.
+
+ The lock must be held. The cursor must be positioned at the start of
+ the first line after the dynamic text area.
+ """
+ with _l_above_dynamic_text():
+ # We just want the side-effect of rerendering the dynamic text.
+ pass
+
+
+@contextlib.contextmanager
+def _l_above_dynamic_text():
+ """A context manager for inserting static text above any dynamic text.
+
+ The lock must be held. The cursor must be positioned at the start of the
+ first line after the dynamic text area.
+
+ The dynamic text is re-rendered.
+ """
+ _l_clear_dynamic_blocks()
+
+ try:
+ yield
+ finally:
+ _l_print_dynamic_blocks()
+
+
+def _l_clear_dynamic_blocks() -> None:
+ """Delete all dynamic text.
+
+ The lock must be held, and the cursor must be positioned at the start
+ of the first line after the dynamic text area. After this, the cursor
+ is positioned at the start of the first line after all static text.
+ """
+ for block in reversed(_dynamic_blocks):
+ block._l_clear()
+
+
+def _l_print_dynamic_blocks() -> None:
+ """Output all dynamic text.
+
+ The lock must be held. After this, the cursor is positioned at the start
+ of the first line after the dynamic text area.
+ """
+ for block in _dynamic_blocks:
+ block._l_print()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/errors/util.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/errors/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..0dd207c9e59f6ad15405b753c29f8b241238941a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/errors/util.py
@@ -0,0 +1,57 @@
+from typing import Optional
+
+from wandb.proto import wandb_internal_pb2 as pb
+
+from . import AuthenticationError, CommError, Error, UnsupportedError, UsageError
+
+to_exception_map = {
+ pb.ErrorInfo.UNKNOWN: Error,
+ pb.ErrorInfo.COMMUNICATION: CommError,
+ pb.ErrorInfo.AUTHENTICATION: AuthenticationError,
+ pb.ErrorInfo.USAGE: UsageError,
+ pb.ErrorInfo.UNSUPPORTED: UnsupportedError,
+}
+
+from_exception_map = {v: k for k, v in to_exception_map.items()}
+
+
+class ProtobufErrorHandler:
+ """Converts protobuf errors to exceptions and vice versa."""
+
+ @staticmethod
+ def to_exception(error: pb.ErrorInfo) -> Optional[Error]:
+ """Convert a protobuf error to an exception.
+
+ Args:
+ error: The protobuf error to convert.
+
+ Returns:
+ The corresponding exception.
+
+ """
+ if not error.SerializeToString():
+ return None
+
+ if error.code in to_exception_map:
+ return to_exception_map[error.code](error.message)
+ return Error(error.message)
+
+ @classmethod
+ def from_exception(cls, exc: Error) -> "pb.ErrorInfo":
+ """Convert an wandb error to a protobuf error message.
+
+ Args:
+ exc: The exception to convert.
+
+ Returns:
+ The corresponding protobuf error message.
+ """
+ if not isinstance(exc, Error):
+ raise TypeError("exc must be a subclass of wandb.errors.Error")
+
+ code = None
+ for subclass in type(exc).__mro__:
+ if subclass in from_exception_map:
+ code = from_exception_map[subclass] # type: ignore
+ break
+ return pb.ErrorInfo(code=code, message=str(exc)) # type: ignore
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/errors/warnings.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/errors/warnings.py
new file mode 100644
index 0000000000000000000000000000000000000000..f956757b378de6f5481aeb467961013ad264f3a9
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/errors/warnings.py
@@ -0,0 +1,2 @@
+class WandbWarning(Warning):
+ """Base W&B Warning."""
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/filesync/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/filesync/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/filesync/dir_watcher.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/filesync/dir_watcher.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a423fc8a88f3794489752e84f969f434e300a10
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/filesync/dir_watcher.py
@@ -0,0 +1,404 @@
+import abc
+import fnmatch
+import glob
+import logging
+import os
+import queue
+import time
+from typing import TYPE_CHECKING, Any, Mapping, MutableMapping, MutableSet, Optional
+
+from wandb import util
+from wandb.sdk.interface.interface import GlobStr
+from wandb.sdk.lib.paths import LogicalPath
+
+if TYPE_CHECKING:
+ import wandb.vendor.watchdog_0_9_0.observers.api as wd_api
+ import wandb.vendor.watchdog_0_9_0.observers.polling as wd_polling
+ import wandb.vendor.watchdog_0_9_0.watchdog.events as wd_events
+ from wandb.sdk.interface.interface import PolicyName
+ from wandb.sdk.internal.file_pusher import FilePusher
+ from wandb.sdk.internal.settings_static import SettingsStatic
+else:
+ wd_polling = util.vendor_import("wandb_watchdog.observers.polling")
+ wd_events = util.vendor_import("wandb_watchdog.events")
+
+PathStr = str # TODO(spencerpearson): would be nice to use Path here
+
+
+logger = logging.getLogger(__name__)
+
+
+class FileEventHandler(abc.ABC):
+ def __init__(
+ self,
+ file_path: PathStr,
+ save_name: LogicalPath,
+ file_pusher: "FilePusher",
+ *args: Any,
+ **kwargs: Any,
+ ) -> None:
+ self.file_path = file_path
+ # Convert windows paths to unix paths
+ self.save_name = LogicalPath(save_name)
+ self._file_pusher = file_pusher
+ self._last_sync: Optional[float] = None
+
+ @property
+ @abc.abstractmethod
+ def policy(self) -> "PolicyName":
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def on_modified(self, force: bool = False) -> None:
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def finish(self) -> None:
+ raise NotImplementedError
+
+ def on_renamed(self, new_path: PathStr, new_name: LogicalPath) -> None:
+ self.file_path = new_path
+ self.save_name = new_name
+ self.on_modified()
+
+
+class PolicyNow(FileEventHandler):
+ """This policy only uploads files now."""
+
+ def on_modified(self, force: bool = False) -> None:
+ # only upload if we've never uploaded or when .save is called
+ if self._last_sync is None or force:
+ self._file_pusher.file_changed(self.save_name, self.file_path)
+ self._last_sync = os.path.getmtime(self.file_path)
+
+ def finish(self) -> None:
+ pass
+
+ @property
+ def policy(self) -> "PolicyName":
+ return "now"
+
+
+class PolicyEnd(FileEventHandler):
+ """This policy only updates at the end of the run."""
+
+ def on_modified(self, force: bool = False) -> None:
+ pass
+
+ # TODO: make sure we call this
+ def finish(self) -> None:
+ # We use copy=False to avoid possibly expensive copies, and because
+ # user files shouldn't still be changing at the end of the run.
+ self._last_sync = os.path.getmtime(self.file_path)
+ self._file_pusher.file_changed(self.save_name, self.file_path, copy=False)
+
+ @property
+ def policy(self) -> "PolicyName":
+ return "end"
+
+
+class PolicyLive(FileEventHandler):
+ """Event handler that uploads respecting throttling.
+
+ Uploads files every RATE_LIMIT_SECONDS, which changes as the size increases to deal
+ with throttling.
+ """
+
+ RATE_LIMIT_SECONDS = 15
+ unit_dict = dict(util.POW_10_BYTES)
+ # Wait to upload until size has increased 20% from last upload
+ RATE_LIMIT_SIZE_INCREASE = 1.2
+
+ def __init__(
+ self,
+ file_path: PathStr,
+ save_name: LogicalPath,
+ file_pusher: "FilePusher",
+ settings: Optional["SettingsStatic"] = None,
+ *args: Any,
+ **kwargs: Any,
+ ) -> None:
+ super().__init__(file_path, save_name, file_pusher, *args, **kwargs)
+ self._last_uploaded_time: Optional[float] = None
+ self._last_uploaded_size: int = 0
+ if settings is not None:
+ if settings.x_live_policy_rate_limit is not None:
+ self.RATE_LIMIT_SECONDS = settings.x_live_policy_rate_limit
+ self._min_wait_time: Optional[float] = settings.x_live_policy_wait_time
+ else:
+ self._min_wait_time = None
+
+ @property
+ def current_size(self) -> int:
+ return os.path.getsize(self.file_path)
+
+ @classmethod
+ def min_wait_for_size(cls, size: int) -> float:
+ if size < 10 * cls.unit_dict["MB"]:
+ return 60
+ elif size < 100 * cls.unit_dict["MB"]:
+ return 5 * 60
+ elif size < cls.unit_dict["GB"]:
+ return 10 * 60
+ else:
+ return 20 * 60
+
+ def should_update(self) -> bool:
+ if self._last_uploaded_time is not None:
+ # Check rate limit by time elapsed
+ time_elapsed = time.time() - self._last_uploaded_time
+ # if more than 15 seconds has passed potentially upload it
+ if time_elapsed < self.RATE_LIMIT_SECONDS:
+ return False
+
+ # Check rate limit by size increase
+ if float(self._last_uploaded_size) > 0:
+ size_increase = self.current_size / float(self._last_uploaded_size)
+ if size_increase < self.RATE_LIMIT_SIZE_INCREASE:
+ return False
+ return time_elapsed > (
+ self._min_wait_time or self.min_wait_for_size(self.current_size)
+ )
+
+ # if the file has never been uploaded, we'll upload it
+ return True
+
+ def on_modified(self, force: bool = False) -> None:
+ if self.current_size == 0:
+ return
+ if self._last_sync == os.path.getmtime(self.file_path):
+ return
+ if force or self.should_update():
+ self.save_file()
+
+ def save_file(self) -> None:
+ self._last_sync = os.path.getmtime(self.file_path)
+ self._last_uploaded_time = time.time()
+ self._last_uploaded_size = self.current_size
+ self._file_pusher.file_changed(self.save_name, self.file_path)
+
+ def finish(self) -> None:
+ self.on_modified(force=True)
+
+ @property
+ def policy(self) -> "PolicyName":
+ return "live"
+
+
+class DirWatcher:
+ def __init__(
+ self,
+ settings: "SettingsStatic",
+ file_pusher: "FilePusher",
+ file_dir: Optional[PathStr] = None,
+ ) -> None:
+ self._file_count = 0
+ self._dir = file_dir or settings.files_dir
+ self._settings = settings
+ self._savename_file_policies: MutableMapping[LogicalPath, PolicyName] = {}
+ self._user_file_policies: Mapping[PolicyName, MutableSet[GlobStr]] = {
+ "end": set(),
+ "live": set(),
+ "now": set(),
+ }
+ self._file_pusher = file_pusher
+ self._file_event_handlers: MutableMapping[LogicalPath, FileEventHandler] = {}
+ self._file_observer = wd_polling.PollingObserver()
+ self._file_observer.schedule(
+ self._per_file_event_handler(), self._dir, recursive=True
+ )
+ self._file_observer.start()
+ logger.info("watching files in: %s", settings.files_dir)
+
+ @property
+ def emitter(self) -> Optional["wd_api.EventEmitter"]:
+ try:
+ return next(iter(self._file_observer.emitters))
+ except StopIteration:
+ return None
+
+ def update_policy(self, path: GlobStr, policy: "PolicyName") -> None:
+ # When we're dealing with one of our own media files, there's no need
+ # to store the policy in memory. _get_file_event_handler will always
+ # return PolicyNow. Using the path makes syncing historic runs much
+ # faster if the name happens to include glob escapable characters. In
+ # the future we may add a flag to "files" records that indicates it's
+ # policy is not dynamic and doesn't need to be stored / checked.
+ save_name = LogicalPath(
+ os.path.relpath(os.path.join(self._dir, path), self._dir)
+ )
+ if save_name.startswith("media/"):
+ pass
+ elif path == glob.escape(path):
+ self._savename_file_policies[save_name] = policy
+ else:
+ self._user_file_policies[policy].add(path)
+
+ for src_path in glob.glob(os.path.join(self._dir, path)):
+ save_name = LogicalPath(os.path.relpath(src_path, self._dir))
+ feh = self._get_file_event_handler(src_path, save_name)
+ # handle the case where the policy changed
+ if feh.policy != policy:
+ try:
+ del self._file_event_handlers[save_name]
+ except KeyError:
+ # TODO: probably should do locking, but this handles moved files for now
+ pass
+ feh = self._get_file_event_handler(src_path, save_name)
+ feh.on_modified(force=True)
+
+ def _per_file_event_handler(self) -> "wd_events.FileSystemEventHandler":
+ """Create a Watchdog file event handler that does different things for every file."""
+ file_event_handler = wd_events.PatternMatchingEventHandler()
+ file_event_handler.on_created = self._on_file_created
+ file_event_handler.on_modified = self._on_file_modified
+ file_event_handler.on_moved = self._on_file_moved
+ file_event_handler._patterns = [os.path.join(self._dir, os.path.normpath("*"))]
+ # Ignore hidden files/folders
+ # TODO: what other files should we skip?
+ file_event_handler._ignore_patterns = [
+ "*.tmp",
+ "*.wandb",
+ "wandb-summary.json",
+ os.path.join(self._dir, ".*"),
+ os.path.join(self._dir, "*/.*"),
+ ]
+ for glb in self._settings.ignore_globs:
+ file_event_handler._ignore_patterns.append(os.path.join(self._dir, glb))
+
+ return file_event_handler
+
+ def _on_file_created(self, event: "wd_events.FileCreatedEvent") -> None:
+ logger.info("file/dir created: %s", event.src_path)
+ if os.path.isdir(event.src_path):
+ return None
+ self._file_count += 1
+ # We do the directory scan less often as it grows
+ if self._file_count % 100 == 0:
+ emitter = self.emitter
+ if emitter:
+ emitter._timeout = int(self._file_count / 100) + 1
+ save_name = LogicalPath(os.path.relpath(event.src_path, self._dir))
+ self._get_file_event_handler(event.src_path, save_name).on_modified()
+
+ # TODO(spencerpearson): this pattern repeats so many times we should have a method/function for it
+ # def _save_name(self, path: PathStr) -> LogicalPath:
+ # return LogicalPath(os.path.relpath(path, self._dir))
+
+ def _on_file_modified(self, event: "wd_events.FileModifiedEvent") -> None:
+ logger.info(f"file/dir modified: {event.src_path}")
+ if os.path.isdir(event.src_path):
+ return None
+ save_name = LogicalPath(os.path.relpath(event.src_path, self._dir))
+ self._get_file_event_handler(event.src_path, save_name).on_modified()
+
+ def _on_file_moved(self, event: "wd_events.FileMovedEvent") -> None:
+ # TODO: test me...
+ logger.info(f"file/dir moved: {event.src_path} -> {event.dest_path}")
+ if os.path.isdir(event.dest_path):
+ return None
+ old_save_name = LogicalPath(os.path.relpath(event.src_path, self._dir))
+ new_save_name = LogicalPath(os.path.relpath(event.dest_path, self._dir))
+
+ # We have to move the existing file handler to the new name
+ handler = self._get_file_event_handler(event.src_path, old_save_name)
+ self._file_event_handlers[new_save_name] = handler
+ del self._file_event_handlers[old_save_name]
+
+ handler.on_renamed(event.dest_path, new_save_name)
+
+ def _get_file_event_handler(
+ self, file_path: PathStr, save_name: LogicalPath
+ ) -> FileEventHandler:
+ """Get or create an event handler for a particular file.
+
+ file_path: the file's actual path
+ save_name: its path relative to the run directory (aka the watch directory)
+ """
+ # Always return PolicyNow for any of our media files.
+ if save_name.startswith("media/"):
+ return PolicyNow(file_path, save_name, self._file_pusher, self._settings)
+ if save_name not in self._file_event_handlers:
+ # TODO: we can use PolicyIgnore if there are files we never want to sync
+ if "tfevents" in save_name or "graph.pbtxt" in save_name:
+ self._file_event_handlers[save_name] = PolicyLive(
+ file_path, save_name, self._file_pusher, self._settings
+ )
+ elif save_name in self._savename_file_policies:
+ policy_name = self._savename_file_policies[save_name]
+ make_handler = (
+ PolicyLive
+ if policy_name == "live"
+ else PolicyNow
+ if policy_name == "now"
+ else PolicyEnd
+ )
+ self._file_event_handlers[save_name] = make_handler(
+ file_path, save_name, self._file_pusher, self._settings
+ )
+ else:
+ make_handler = PolicyEnd
+ for policy, globs in self._user_file_policies.items():
+ if policy == "end":
+ continue
+ # Convert set to list to avoid RuntimeError's
+ # TODO: we may need to add locks
+ for g in list(globs):
+ paths = glob.glob(os.path.join(self._dir, g))
+ if any(save_name in p for p in paths):
+ if policy == "live":
+ make_handler = PolicyLive
+ elif policy == "now":
+ make_handler = PolicyNow
+ self._file_event_handlers[save_name] = make_handler(
+ file_path, save_name, self._file_pusher, self._settings
+ )
+ return self._file_event_handlers[save_name]
+
+ def finish(self) -> None:
+ logger.info("shutting down directory watcher")
+ try:
+ # avoid hanging if we crashed before the observer was started
+ if self._file_observer.is_alive():
+ # rather unfortunately we need to manually do a final scan of the dir
+ # with `queue_events`, then iterate through all events before stopping
+ # the observer to catch all files written. First we need to prevent the
+ # existing thread from consuming our final events, then we process them
+ self._file_observer._timeout = 0
+ self._file_observer._stopped_event.set()
+ self._file_observer.join()
+ self.emitter.queue_events(0) # type: ignore[union-attr]
+ while True:
+ try:
+ self._file_observer.dispatch_events(
+ self._file_observer.event_queue, 0
+ )
+ except queue.Empty:
+ break
+ # Calling stop unschedules any inflight events so we handled them above
+ self._file_observer.stop()
+ # TODO: py2 TypeError: PyCObject_AsVoidPtr called with null pointer
+ except TypeError:
+ pass
+ # TODO: py3 SystemError: returned an error
+ except SystemError:
+ pass
+
+ # Ensure we've at least noticed every file in the run directory. Sometimes
+ # we miss things because asynchronously watching filesystems isn't reliable.
+ logger.info("scan: %s", self._dir)
+
+ for dirpath, _, filenames in os.walk(self._dir):
+ for fname in filenames:
+ file_path = os.path.join(dirpath, fname)
+ save_name = LogicalPath(os.path.relpath(file_path, self._dir))
+ ignored = False
+ for glb in self._settings.ignore_globs:
+ if len(fnmatch.filter([save_name], glb)) > 0:
+ ignored = True
+ logger.info("ignored: %s matching glob %s", save_name, glb)
+ break
+ if ignored:
+ continue
+ logger.info("scan save: %s %s", file_path, save_name)
+ self._get_file_event_handler(file_path, save_name).finish()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/filesync/stats.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/filesync/stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..95c3523a37a2a82ce17bd40a6b4a667db04ff0ff
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/filesync/stats.py
@@ -0,0 +1,100 @@
+import threading
+from typing import MutableMapping, NamedTuple
+
+import wandb
+
+
+class FileStats(NamedTuple):
+ deduped: bool
+ total: int
+ uploaded: int
+ failed: bool
+ artifact_file: bool
+
+
+class Summary(NamedTuple):
+ uploaded_bytes: int
+ total_bytes: int
+ deduped_bytes: int
+
+
+class FileCountsByCategory(NamedTuple):
+ artifact: int
+ wandb: int
+ media: int
+ other: int
+
+
+class Stats:
+ def __init__(self) -> None:
+ self._stats: MutableMapping[str, FileStats] = {}
+ self._lock = threading.Lock()
+
+ def init_file(
+ self, save_name: str, size: int, is_artifact_file: bool = False
+ ) -> None:
+ with self._lock:
+ self._stats[save_name] = FileStats(
+ deduped=False,
+ total=size,
+ uploaded=0,
+ failed=False,
+ artifact_file=is_artifact_file,
+ )
+
+ def set_file_deduped(self, save_name: str) -> None:
+ with self._lock:
+ orig = self._stats[save_name]
+ self._stats[save_name] = orig._replace(
+ deduped=True,
+ uploaded=orig.total,
+ )
+
+ def update_uploaded_file(self, save_name: str, total_uploaded: int) -> None:
+ with self._lock:
+ self._stats[save_name] = self._stats[save_name]._replace(
+ uploaded=total_uploaded,
+ )
+
+ def update_failed_file(self, save_name: str) -> None:
+ with self._lock:
+ self._stats[save_name] = self._stats[save_name]._replace(
+ uploaded=0,
+ failed=True,
+ )
+
+ def summary(self) -> Summary:
+ # Need to use list to ensure we get a copy, since other threads may
+ # modify this while we iterate
+ with self._lock:
+ stats = list(self._stats.values())
+ return Summary(
+ uploaded_bytes=sum(f.uploaded for f in stats),
+ total_bytes=sum(f.total for f in stats),
+ deduped_bytes=sum(f.total for f in stats if f.deduped),
+ )
+
+ def file_counts_by_category(self) -> FileCountsByCategory:
+ artifact_files = 0
+ wandb_files = 0
+ media_files = 0
+ other_files = 0
+ # Need to use list to ensure we get a copy, since other threads may
+ # modify this while we iterate
+ with self._lock:
+ file_stats = list(self._stats.items())
+ for save_name, stats in file_stats:
+ if stats.artifact_file:
+ artifact_files += 1
+ elif wandb.wandb_lib.filenames.is_wandb_file(save_name): # type: ignore[attr-defined] # TODO(spencerpearson): this is probably synonymous with wandb.sdk.lib.filenames...?
+ wandb_files += 1
+ elif save_name.startswith("media"):
+ media_files += 1
+ else:
+ other_files += 1
+ return FileCountsByCategory(
+ artifact=artifact_files,
+ wandb=wandb_files,
+ media=media_files,
+ other=other_files,
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/filesync/step_checksum.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/filesync/step_checksum.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0acd96e80e8ad7b4fb8027da718a3b28780f86e
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/filesync/step_checksum.py
@@ -0,0 +1,142 @@
+"""Batching file prepare requests to our API."""
+
+import concurrent.futures
+import functools
+import os
+import queue
+import shutil
+import threading
+from typing import TYPE_CHECKING, NamedTuple, Optional, Union, cast
+
+from wandb.filesync import step_upload
+from wandb.sdk.lib import filesystem, runid
+from wandb.sdk.lib.paths import LogicalPath
+
+if TYPE_CHECKING:
+ import tempfile
+
+ from wandb.filesync import stats
+ from wandb.sdk.artifacts.artifact_manifest import ArtifactManifest
+ from wandb.sdk.artifacts.artifact_saver import SaveFn
+ from wandb.sdk.internal import internal_api
+
+
+class RequestUpload(NamedTuple):
+ path: str
+ save_name: LogicalPath
+ copy: bool
+
+
+class RequestStoreManifestFiles(NamedTuple):
+ manifest: "ArtifactManifest"
+ artifact_id: str
+ save_fn: "SaveFn"
+
+
+class RequestCommitArtifact(NamedTuple):
+ artifact_id: str
+ finalize: bool
+ before_commit: step_upload.PreCommitFn
+ result_future: "concurrent.futures.Future[None]"
+
+
+class RequestFinish(NamedTuple):
+ callback: Optional[step_upload.OnRequestFinishFn]
+
+
+Event = Union[
+ RequestUpload, RequestStoreManifestFiles, RequestCommitArtifact, RequestFinish
+]
+
+
+class StepChecksum:
+ def __init__(
+ self,
+ api: "internal_api.Api",
+ tempdir: "tempfile.TemporaryDirectory",
+ request_queue: "queue.Queue[Event]",
+ output_queue: "queue.Queue[step_upload.Event]",
+ stats: "stats.Stats",
+ ) -> None:
+ self._api = api
+ self._tempdir = tempdir
+ self._request_queue = request_queue
+ self._output_queue = output_queue
+ self._stats = stats
+
+ self._thread = threading.Thread(target=self._thread_body)
+ self._thread.daemon = True
+
+ def _thread_body(self) -> None:
+ while True:
+ req = self._request_queue.get()
+ if isinstance(req, RequestUpload):
+ path = req.path
+ if req.copy:
+ path = os.path.join(
+ self._tempdir.name,
+ f"{runid.generate_id()}-{req.save_name}",
+ )
+ filesystem.mkdir_exists_ok(os.path.dirname(path))
+ try:
+ # certain linux distros throw an exception when copying
+ # large files: https://bugs.python.org/issue43743
+ shutil.copy2(req.path, path)
+ except OSError:
+ shutil._USE_CP_SENDFILE = False # type: ignore[attr-defined]
+ shutil.copy2(req.path, path)
+ self._stats.init_file(req.save_name, os.path.getsize(path))
+ self._output_queue.put(
+ step_upload.RequestUpload(
+ path,
+ req.save_name,
+ None,
+ None,
+ req.copy,
+ None,
+ None,
+ )
+ )
+ elif isinstance(req, RequestStoreManifestFiles):
+ for entry in req.manifest.entries.values():
+ if entry.local_path:
+ self._stats.init_file(
+ entry.local_path,
+ cast(int, entry.size),
+ is_artifact_file=True,
+ )
+ self._output_queue.put(
+ step_upload.RequestUpload(
+ entry.local_path,
+ entry.path,
+ req.artifact_id,
+ entry.digest,
+ False,
+ functools.partial(req.save_fn, entry),
+ entry.digest,
+ )
+ )
+ elif isinstance(req, RequestCommitArtifact):
+ self._output_queue.put(
+ step_upload.RequestCommitArtifact(
+ req.artifact_id,
+ req.finalize,
+ req.before_commit,
+ req.result_future,
+ )
+ )
+ elif isinstance(req, RequestFinish):
+ break
+ else:
+ raise TypeError
+
+ self._output_queue.put(step_upload.RequestFinish(req.callback))
+
+ def start(self) -> None:
+ self._thread.start()
+
+ def is_alive(self) -> bool:
+ return self._thread.is_alive()
+
+ def finish(self) -> None:
+ self._request_queue.put(RequestFinish(None))
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/filesync/step_prepare.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/filesync/step_prepare.py
new file mode 100644
index 0000000000000000000000000000000000000000..95a4a21b4593a62dd21d080e847c212eef7e2ca7
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/filesync/step_prepare.py
@@ -0,0 +1,179 @@
+"""Batching file prepare requests to our API."""
+
+import queue
+import threading
+import time
+from typing import (
+ TYPE_CHECKING,
+ Callable,
+ Dict,
+ List,
+ Mapping,
+ NamedTuple,
+ Optional,
+ Sequence,
+ Tuple,
+ Union,
+)
+
+if TYPE_CHECKING:
+ from wandb.sdk.internal.internal_api import (
+ Api,
+ CreateArtifactFileSpecInput,
+ CreateArtifactFilesResponseFile,
+ )
+
+
+# Request for a file to be prepared.
+class RequestPrepare(NamedTuple):
+ file_spec: "CreateArtifactFileSpecInput"
+ response_channel: "queue.Queue[ResponsePrepare]"
+
+
+class RequestFinish(NamedTuple):
+ pass
+
+
+class ResponsePrepare(NamedTuple):
+ birth_artifact_id: str
+ upload_url: Optional[str]
+ upload_headers: Sequence[str]
+ upload_id: Optional[str]
+ storage_path: Optional[str]
+ multipart_upload_urls: Optional[Dict[int, str]]
+
+
+Request = Union[RequestPrepare, RequestFinish]
+
+
+def _clamp(x: float, low: float, high: float) -> float:
+ return max(low, min(x, high))
+
+
+def gather_batch(
+ request_queue: "queue.Queue[Request]",
+ batch_time: float,
+ inter_event_time: float,
+ max_batch_size: int,
+ clock: Callable[[], float] = time.monotonic,
+) -> Tuple[bool, Sequence[RequestPrepare]]:
+ batch_start_time = clock()
+ remaining_time = batch_time
+
+ first_request = request_queue.get()
+ if isinstance(first_request, RequestFinish):
+ return True, []
+
+ batch: List[RequestPrepare] = [first_request]
+
+ while remaining_time > 0 and len(batch) < max_batch_size:
+ try:
+ request = request_queue.get(
+ timeout=_clamp(
+ x=inter_event_time,
+ low=1e-12, # 0 = "block forever", so just use something tiny
+ high=remaining_time,
+ ),
+ )
+ if isinstance(request, RequestFinish):
+ return True, batch
+
+ batch.append(request)
+ remaining_time = batch_time - (clock() - batch_start_time)
+
+ except queue.Empty:
+ break
+
+ return False, batch
+
+
+def prepare_response(response: "CreateArtifactFilesResponseFile") -> ResponsePrepare:
+ multipart_resp = response.get("uploadMultipartUrls")
+ part_list = multipart_resp["uploadUrlParts"] if multipart_resp else []
+ multipart_parts = {u["partNumber"]: u["uploadUrl"] for u in part_list} or None
+
+ return ResponsePrepare(
+ birth_artifact_id=response["artifact"]["id"],
+ upload_url=response["uploadUrl"],
+ upload_headers=response["uploadHeaders"],
+ upload_id=multipart_resp and multipart_resp.get("uploadID"),
+ storage_path=response.get("storagePath"),
+ multipart_upload_urls=multipart_parts,
+ )
+
+
+class StepPrepare:
+ """A thread that batches requests to our file prepare API.
+
+ Any number of threads may call prepare() in parallel. The PrepareBatcher thread
+ will batch requests up and send them all to the backend at once.
+ """
+
+ def __init__(
+ self,
+ api: "Api",
+ batch_time: float,
+ inter_event_time: float,
+ max_batch_size: int,
+ request_queue: Optional["queue.Queue[Request]"] = None,
+ ) -> None:
+ self._api = api
+ self._inter_event_time = inter_event_time
+ self._batch_time = batch_time
+ self._max_batch_size = max_batch_size
+ self._request_queue: queue.Queue[Request] = request_queue or queue.Queue()
+ self._thread = threading.Thread(target=self._thread_body)
+ self._thread.daemon = True
+
+ def _thread_body(self) -> None:
+ while True:
+ finish, batch = gather_batch(
+ request_queue=self._request_queue,
+ batch_time=self._batch_time,
+ inter_event_time=self._inter_event_time,
+ max_batch_size=self._max_batch_size,
+ )
+ if batch:
+ batch_response = self._prepare_batch(batch)
+ # send responses
+ for prepare_request in batch:
+ name = prepare_request.file_spec["name"]
+ response_file = batch_response[name]
+ response = prepare_response(response_file)
+ prepare_request.response_channel.put(response)
+ if finish:
+ break
+
+ def _prepare_batch(
+ self, batch: Sequence[RequestPrepare]
+ ) -> Mapping[str, "CreateArtifactFilesResponseFile"]:
+ """Execute the prepareFiles API call.
+
+ Args:
+ batch: List of RequestPrepare objects
+ Returns:
+ dict of (save_name: ResponseFile) pairs where ResponseFile is a dict with
+ an uploadUrl key. The value of the uploadUrl key is None if the file
+ already exists, or a url string if the file should be uploaded.
+ """
+ return self._api.create_artifact_files([req.file_spec for req in batch])
+
+ def prepare(
+ self, file_spec: "CreateArtifactFileSpecInput"
+ ) -> "queue.Queue[ResponsePrepare]":
+ response_queue: queue.Queue[ResponsePrepare] = queue.Queue()
+ self._request_queue.put(RequestPrepare(file_spec, response_queue))
+ return response_queue
+
+ def start(self) -> None:
+ self._thread.start()
+
+ def finish(self) -> None:
+ self._request_queue.put(RequestFinish())
+
+ def is_alive(self) -> bool:
+ return self._thread.is_alive()
+
+ def shutdown(self) -> None:
+ self.finish()
+ self._thread.join()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/filesync/step_upload.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/filesync/step_upload.py
new file mode 100644
index 0000000000000000000000000000000000000000..0840293d35aaf53aeaf8d211783f9be957beafe2
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/filesync/step_upload.py
@@ -0,0 +1,287 @@
+"""Batching file prepare requests to our API."""
+
+import concurrent.futures
+import logging
+import queue
+import sys
+import threading
+from typing import (
+ TYPE_CHECKING,
+ Callable,
+ MutableMapping,
+ MutableSequence,
+ MutableSet,
+ NamedTuple,
+ Optional,
+ Union,
+)
+
+from wandb.errors.term import termerror
+from wandb.filesync import upload_job
+from wandb.sdk.lib.paths import LogicalPath
+
+if TYPE_CHECKING:
+ from typing import TypedDict
+
+ from wandb.filesync import stats
+ from wandb.sdk.internal import file_stream, internal_api, progress
+ from wandb.sdk.internal.settings_static import SettingsStatic
+
+ class ArtifactStatus(TypedDict):
+ finalize: bool
+ pending_count: int
+ commit_requested: bool
+ pre_commit_callbacks: MutableSet["PreCommitFn"]
+ result_futures: MutableSet["concurrent.futures.Future[None]"]
+
+
+PreCommitFn = Callable[[], None]
+OnRequestFinishFn = Callable[[], None]
+SaveFn = Callable[["progress.ProgressFn"], bool]
+
+logger = logging.getLogger(__name__)
+
+
+class RequestUpload(NamedTuple):
+ path: str
+ save_name: LogicalPath
+ artifact_id: Optional[str]
+ md5: Optional[str]
+ copied: bool
+ save_fn: Optional[SaveFn]
+ digest: Optional[str]
+
+
+class RequestCommitArtifact(NamedTuple):
+ artifact_id: str
+ finalize: bool
+ before_commit: PreCommitFn
+ result_future: "concurrent.futures.Future[None]"
+
+
+class RequestFinish(NamedTuple):
+ callback: Optional[OnRequestFinishFn]
+
+
+class EventJobDone(NamedTuple):
+ job: RequestUpload
+ exc: Optional[BaseException]
+
+
+Event = Union[RequestUpload, RequestCommitArtifact, RequestFinish, EventJobDone]
+
+
+class StepUpload:
+ def __init__(
+ self,
+ api: "internal_api.Api",
+ stats: "stats.Stats",
+ event_queue: "queue.Queue[Event]",
+ max_threads: int,
+ file_stream: "file_stream.FileStreamApi",
+ settings: Optional["SettingsStatic"] = None,
+ ) -> None:
+ self._api = api
+ self._stats = stats
+ self._event_queue = event_queue
+ self._file_stream = file_stream
+
+ self._thread = threading.Thread(target=self._thread_body)
+ self._thread.daemon = True
+
+ self._pool = concurrent.futures.ThreadPoolExecutor(
+ thread_name_prefix="wandb-upload",
+ max_workers=max_threads,
+ )
+
+ # Indexed by files' `save_name`'s, which are their ID's in the Run.
+ self._running_jobs: MutableMapping[LogicalPath, RequestUpload] = {}
+ self._pending_jobs: MutableSequence[RequestUpload] = []
+
+ self._artifacts: MutableMapping[str, ArtifactStatus] = {}
+
+ self.silent = bool(settings.silent) if settings else False
+
+ def _thread_body(self) -> None:
+ event: Optional[Event]
+ # Wait for event in the queue, and process one by one until a
+ # finish event is received
+ finish_callback = None
+ while True:
+ event = self._event_queue.get()
+ if isinstance(event, RequestFinish):
+ finish_callback = event.callback
+ break
+ self._handle_event(event)
+
+ # We've received a finish event. At this point, further Upload requests
+ # are invalid.
+
+ # After a finish event is received, iterate through the event queue
+ # one by one and process all remaining events.
+ while True:
+ try:
+ event = self._event_queue.get(True, 0.2)
+ except queue.Empty:
+ event = None
+ if event:
+ self._handle_event(event)
+ elif not self._running_jobs:
+ # Queue was empty and no jobs left.
+ self._pool.shutdown(wait=False)
+ if finish_callback:
+ finish_callback()
+ break
+
+ def _handle_event(self, event: Event) -> None:
+ if isinstance(event, EventJobDone):
+ job = event.job
+
+ if event.exc is not None:
+ logger.exception(
+ "Failed to upload file: %s", job.path, exc_info=event.exc
+ )
+
+ if job.artifact_id:
+ if event.exc is None:
+ self._artifacts[job.artifact_id]["pending_count"] -= 1
+ self._maybe_commit_artifact(job.artifact_id)
+ else:
+ if not self.silent:
+ termerror(
+ "Uploading artifact file failed. Artifact won't be committed."
+ )
+ self._fail_artifact_futures(job.artifact_id, event.exc)
+ self._running_jobs.pop(job.save_name)
+ # If we have any pending jobs, start one now
+ if self._pending_jobs:
+ event = self._pending_jobs.pop(0)
+ self._start_upload_job(event)
+ elif isinstance(event, RequestCommitArtifact):
+ if event.artifact_id not in self._artifacts:
+ self._init_artifact(event.artifact_id)
+ self._artifacts[event.artifact_id]["commit_requested"] = True
+ self._artifacts[event.artifact_id]["finalize"] = event.finalize
+ self._artifacts[event.artifact_id]["pre_commit_callbacks"].add(
+ event.before_commit
+ )
+ self._artifacts[event.artifact_id]["result_futures"].add(
+ event.result_future
+ )
+ self._maybe_commit_artifact(event.artifact_id)
+ elif isinstance(event, RequestUpload):
+ if event.artifact_id is not None:
+ if event.artifact_id not in self._artifacts:
+ self._init_artifact(event.artifact_id)
+ self._artifacts[event.artifact_id]["pending_count"] += 1
+ self._start_upload_job(event)
+ else:
+ raise TypeError(f"Event has unexpected type: {event!s}")
+
+ def _start_upload_job(self, event: RequestUpload) -> None:
+ # Operations on a single backend file must be serialized. if
+ # we're already uploading this file, put the event on the
+ # end of the queue
+ if event.save_name in self._running_jobs:
+ self._pending_jobs.append(event)
+ return
+
+ self._spawn_upload(event)
+
+ def _spawn_upload(self, event: RequestUpload) -> None:
+ """Spawn an upload job, and handles the bookkeeping of `self._running_jobs`.
+
+ Context: it's important that, whenever we add an entry to `self._running_jobs`,
+ we ensure that a corresponding `EventJobDone` message will eventually get handled;
+ otherwise, the `_running_jobs` entry will never get removed, and the StepUpload
+ will never shut down.
+
+ The sole purpose of this function is to make sure that the code that adds an entry
+ to `self._running_jobs` is textually right next to the code that eventually enqueues
+ the `EventJobDone` message. This should help keep them in sync.
+ """
+ # Adding the entry to `self._running_jobs` MUST happen in the main thread,
+ # NOT in the job that gets submitted to the thread-pool, to guard against
+ # this sequence of events:
+ # - StepUpload receives a RequestUpload
+ # ...and therefore spawns a thread to do the upload
+ # - StepUpload receives a RequestFinish
+ # ...and checks `self._running_jobs` to see if there are any tasks to wait for...
+ # ...and there are none, because the addition to `self._running_jobs` happens in
+ # the background thread, which the scheduler hasn't yet run...
+ # ...so the StepUpload shuts down. Even though we haven't uploaded the file!
+ #
+ # This would be very bad!
+ # So, this line has to happen _outside_ the `pool.submit()`.
+ self._running_jobs[event.save_name] = event
+
+ def run_and_notify() -> None:
+ try:
+ self._do_upload(event)
+ finally:
+ self._event_queue.put(EventJobDone(event, exc=sys.exc_info()[1]))
+
+ self._pool.submit(run_and_notify)
+
+ def _do_upload(self, event: RequestUpload) -> None:
+ job = upload_job.UploadJob(
+ self._stats,
+ self._api,
+ self._file_stream,
+ self.silent,
+ event.save_name,
+ event.path,
+ event.artifact_id,
+ event.md5,
+ event.copied,
+ event.save_fn,
+ event.digest,
+ )
+ job.run()
+
+ def _init_artifact(self, artifact_id: str) -> None:
+ self._artifacts[artifact_id] = {
+ "finalize": False,
+ "pending_count": 0,
+ "commit_requested": False,
+ "pre_commit_callbacks": set(),
+ "result_futures": set(),
+ }
+
+ def _maybe_commit_artifact(self, artifact_id: str) -> None:
+ artifact_status = self._artifacts[artifact_id]
+ if (
+ artifact_status["pending_count"] == 0
+ and artifact_status["commit_requested"]
+ ):
+ try:
+ for pre_callback in artifact_status["pre_commit_callbacks"]:
+ pre_callback()
+ if artifact_status["finalize"]:
+ self._api.commit_artifact(artifact_id)
+ except Exception as exc:
+ termerror(
+ f"Committing artifact failed. Artifact {artifact_id} won't be finalized."
+ )
+ termerror(str(exc))
+ self._fail_artifact_futures(artifact_id, exc)
+ else:
+ self._resolve_artifact_futures(artifact_id)
+
+ def _fail_artifact_futures(self, artifact_id: str, exc: BaseException) -> None:
+ futures = self._artifacts[artifact_id]["result_futures"]
+ for result_future in futures:
+ result_future.set_exception(exc)
+ futures.clear()
+
+ def _resolve_artifact_futures(self, artifact_id: str) -> None:
+ futures = self._artifacts[artifact_id]["result_futures"]
+ for result_future in futures:
+ result_future.set_result(None)
+ futures.clear()
+
+ def start(self) -> None:
+ self._thread.start()
+
+ def is_alive(self) -> bool:
+ return self._thread.is_alive()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/filesync/upload_job.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/filesync/upload_job.py
new file mode 100644
index 0000000000000000000000000000000000000000..3db449571b3f3e06310e76cb267d0dc042557915
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/filesync/upload_job.py
@@ -0,0 +1,142 @@
+import logging
+import os
+from typing import TYPE_CHECKING, Optional
+
+import wandb
+from wandb.sdk.lib.paths import LogicalPath
+
+if TYPE_CHECKING:
+ from wandb.filesync import dir_watcher, stats, step_upload
+ from wandb.sdk.internal import file_stream, internal_api
+
+
+logger = logging.getLogger(__name__)
+
+
+class UploadJob:
+ def __init__(
+ self,
+ stats: "stats.Stats",
+ api: "internal_api.Api",
+ file_stream: "file_stream.FileStreamApi",
+ silent: bool,
+ save_name: LogicalPath,
+ path: "dir_watcher.PathStr",
+ artifact_id: Optional[str],
+ md5: Optional[str],
+ copied: bool,
+ save_fn: Optional["step_upload.SaveFn"],
+ digest: Optional[str],
+ ) -> None:
+ """A file uploader.
+
+ Args:
+ push_function: function(save_name, actual_path) which actually uploads
+ the file.
+ save_name: string logical location of the file relative to the run
+ directory.
+ path: actual string path of the file to upload on the filesystem.
+ """
+ self._stats = stats
+ self._api = api
+ self._file_stream = file_stream
+ self.silent = silent
+ self.save_name = save_name
+ self.save_path = path
+ self.artifact_id = artifact_id
+ self.md5 = md5
+ self.copied = copied
+ self.save_fn = save_fn
+ self.digest = digest
+ super().__init__()
+
+ def run(self) -> None:
+ success = False
+ try:
+ self.push()
+ success = True
+ finally:
+ if self.copied and os.path.isfile(self.save_path):
+ os.remove(self.save_path)
+ if success:
+ self._file_stream.push_success(self.artifact_id, self.save_name) # type: ignore
+
+ def push(self) -> None:
+ if self.save_fn:
+ # Retry logic must happen in save_fn currently
+ try:
+ deduped = self.save_fn(
+ lambda _, t: self._stats.update_uploaded_file(self.save_path, t)
+ )
+ except Exception as e:
+ self._stats.update_failed_file(self.save_path)
+ logger.exception("Failed to upload file: %s", self.save_path)
+ wandb._sentry.exception(e)
+ message = str(e)
+ # TODO: this is usually XML, but could be JSON
+ if hasattr(e, "response"):
+ message = e.response.content
+ wandb.termerror(
+ f'Error uploading "{self.save_path}": {type(e).__name__}, {message}'
+ )
+ raise
+
+ if deduped:
+ logger.info("Skipped uploading %s", self.save_path)
+ self._stats.set_file_deduped(self.save_path)
+ else:
+ logger.info("Uploaded file %s", self.save_path)
+ return
+
+ if self.md5:
+ # This is the new artifact manifest upload flow, in which we create the
+ # database entry for the manifest file before creating it. This is used for
+ # artifact L0 files. Which now is only artifact_manifest.json
+ _, response = self._api.create_artifact_manifest(
+ self.save_name, self.md5, self.artifact_id
+ )
+ upload_url = response["uploadUrl"]
+ upload_headers = response["uploadHeaders"]
+ else:
+ # The classic file upload flow. We get a signed url and upload the file
+ # then the backend handles the cloud storage metadata callback to create the
+ # file entry. This flow has aged like a fine wine.
+ project = self._api.get_project()
+ _, upload_headers, result = self._api.upload_urls(project, [self.save_name])
+ file_info = result[self.save_name]
+ upload_url = file_info["uploadUrl"]
+
+ if upload_url is None:
+ logger.info("Skipped uploading %s", self.save_path)
+ self._stats.set_file_deduped(self.save_name)
+ else:
+ extra_headers = self._api._extra_http_headers
+ for upload_header in upload_headers:
+ key, val = upload_header.split(":", 1)
+ extra_headers[key] = val
+ # Copied from push TODO(artifacts): clean up
+ # If the upload URL is relative, fill it in with the base URL,
+ # since its a proxied file store like the on-prem VM.
+ if upload_url.startswith("/"):
+ upload_url = f"{self._api.api_url}{upload_url}"
+ try:
+ with open(self.save_path, "rb") as f:
+ self._api.upload_file_retry(
+ upload_url,
+ f,
+ lambda _, t: self.progress(t),
+ extra_headers=extra_headers,
+ )
+ logger.info("Uploaded file %s", self.save_path)
+ except Exception as e:
+ self._stats.update_failed_file(self.save_name)
+ logger.exception("Failed to upload file: %s", self.save_path)
+ wandb._sentry.exception(e)
+ if not self.silent:
+ wandb.termerror(
+ f'Error uploading "{self.save_name}": {type(e).__name__}, {e}'
+ )
+ raise
+
+ def progress(self, total_bytes: int) -> None:
+ self._stats.update_uploaded_file(self.save_name, total_bytes)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/catboost/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/catboost/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ccd732b7e26cead03e12f0d6ab00f6d3165c2ba4
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/catboost/__init__.py
@@ -0,0 +1,5 @@
+"""W&B callback for CatBoost."""
+
+from .catboost import WandbCallback, log_summary
+
+__all__ = ["log_summary", "WandbCallback"]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/catboost/catboost.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/catboost/catboost.py
new file mode 100644
index 0000000000000000000000000000000000000000..09dc31b84ffaec7826d70536eb59ef56452a9062
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/catboost/catboost.py
@@ -0,0 +1,182 @@
+"""catboost init."""
+
+from pathlib import Path
+from types import SimpleNamespace
+from typing import List, Union
+
+from catboost import CatBoostClassifier, CatBoostRegressor # type: ignore
+
+import wandb
+from wandb.sdk.lib import telemetry as wb_telemetry
+
+
+class WandbCallback:
+ """`WandbCallback` automatically integrates CatBoost with wandb.
+
+ Args:
+ - metric_period: (int) if you are passing `metric_period` to your CatBoost model please pass the same value here (default=1).
+
+ Passing `WandbCallback` to CatBoost will:
+ - log training and validation metrics at every `metric_period`
+ - log iteration at every `metric_period`
+
+ Example:
+ ```
+ train_pool = Pool(
+ train[features], label=train["label"], cat_features=cat_features
+ )
+ test_pool = Pool(test[features], label=test["label"], cat_features=cat_features)
+
+ model = CatBoostRegressor(
+ iterations=100,
+ loss_function="Cox",
+ eval_metric="Cox",
+ )
+
+ model.fit(
+ train_pool,
+ eval_set=test_pool,
+ callbacks=[WandbCallback()],
+ )
+ ```
+ """
+
+ def __init__(self, metric_period: int = 1):
+ if wandb.run is None:
+ raise wandb.Error("You must call `wandb.init()` before `WandbCallback()`")
+
+ with wb_telemetry.context() as tel:
+ tel.feature.catboost_wandb_callback = True
+
+ self.metric_period: int = metric_period
+
+ def after_iteration(self, info: SimpleNamespace) -> bool:
+ if info.iteration % self.metric_period == 0:
+ for data, metric in info.metrics.items():
+ for metric_name, log in metric.items():
+ # todo: replace with wandb.run._log once available
+ wandb.log({f"{data}-{metric_name}": log[-1]}, commit=False)
+ # todo: replace with wandb.run._log once available
+ wandb.log({f"iteration@metric-period-{self.metric_period}": info.iteration})
+
+ return True
+
+
+def _checkpoint_artifact(
+ model: Union[CatBoostClassifier, CatBoostRegressor], aliases: List[str]
+) -> None:
+ """Upload model checkpoint as W&B artifact."""
+ if wandb.run is None:
+ raise wandb.Error(
+ "You must call `wandb.init()` before `_checkpoint_artifact()`"
+ )
+
+ model_name = f"model_{wandb.run.id}"
+ # save the model in the default `cbm` format
+ model_path = Path(wandb.run.dir) / "model"
+
+ model.save_model(model_path)
+
+ model_artifact = wandb.Artifact(name=model_name, type="model")
+ model_artifact.add_file(str(model_path))
+ wandb.log_artifact(model_artifact, aliases=aliases)
+
+
+def _log_feature_importance(
+ model: Union[CatBoostClassifier, CatBoostRegressor],
+) -> None:
+ """Log feature importance with default settings."""
+ if wandb.run is None:
+ raise wandb.Error(
+ "You must call `wandb.init()` before `_checkpoint_artifact()`"
+ )
+
+ feat_df = model.get_feature_importance(prettified=True)
+
+ fi_data = [
+ [feat, feat_imp]
+ for feat, feat_imp in zip(feat_df["Feature Id"], feat_df["Importances"])
+ ]
+ table = wandb.Table(data=fi_data, columns=["Feature", "Importance"])
+ # todo: replace with wandb.run._log once available
+ wandb.log(
+ {
+ "Feature Importance": wandb.plot.bar(
+ table, "Feature", "Importance", title="Feature Importance"
+ )
+ },
+ commit=False,
+ )
+
+
+def log_summary(
+ model: Union[CatBoostClassifier, CatBoostRegressor],
+ log_all_params: bool = True,
+ save_model_checkpoint: bool = False,
+ log_feature_importance: bool = True,
+) -> None:
+ """`log_summary` logs useful metrics about catboost model after training is done.
+
+ Args:
+ model: it can be CatBoostClassifier or CatBoostRegressor.
+ log_all_params: (boolean) if True (default) log the model hyperparameters as W&B config.
+ save_model_checkpoint: (boolean) if True saves the model upload as W&B artifacts.
+ log_feature_importance: (boolean) if True (default) logs feature importance as W&B bar chart using the default setting of `get_feature_importance`.
+
+ Using this along with `wandb_callback` will:
+
+ - save the hyperparameters as W&B config,
+ - log `best_iteration` and `best_score` as `wandb.summary`,
+ - save and upload your trained model to Weights & Biases Artifacts (when `save_model_checkpoint = True`)
+ - log feature importance plot.
+
+ Example:
+ ```python
+ train_pool = Pool(
+ train[features], label=train["label"], cat_features=cat_features
+ )
+ test_pool = Pool(test[features], label=test["label"], cat_features=cat_features)
+
+ model = CatBoostRegressor(
+ iterations=100,
+ loss_function="Cox",
+ eval_metric="Cox",
+ )
+
+ model.fit(
+ train_pool,
+ eval_set=test_pool,
+ callbacks=[WandbCallback()],
+ )
+
+ log_summary(model)
+ ```
+ """
+ if wandb.run is None:
+ raise wandb.Error("You must call `wandb.init()` before `log_summary()`")
+
+ if not (isinstance(model, (CatBoostClassifier, CatBoostRegressor))):
+ raise wandb.Error(
+ "Model should be an instance of CatBoostClassifier or CatBoostRegressor"
+ )
+
+ with wb_telemetry.context() as tel:
+ tel.feature.catboost_log_summary = True
+
+ # log configs
+ params = model.get_all_params()
+ if log_all_params:
+ wandb.config.update(params)
+
+ # log best score and iteration
+ wandb.run.summary["best_iteration"] = model.get_best_iteration()
+ wandb.run.summary["best_score"] = model.get_best_score()
+
+ # log model
+ if save_model_checkpoint:
+ aliases = ["best"] if params["use_best_model"] else ["last"]
+ _checkpoint_artifact(model, aliases=aliases)
+
+ # Feature importance
+ if log_feature_importance:
+ _log_feature_importance(model)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/cohere/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/cohere/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d367dc6988bda4251745dc6b3610a3e92b4c85e
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/cohere/__init__.py
@@ -0,0 +1,3 @@
+__all__ = ("autolog",)
+
+from .cohere import autolog
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/cohere/cohere.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/cohere/cohere.py
new file mode 100644
index 0000000000000000000000000000000000000000..91f9a43e23150a6882dbb87512e6fbe657a7b8d4
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/cohere/cohere.py
@@ -0,0 +1,21 @@
+import logging
+
+from wandb.sdk.integration_utils.auto_logging import AutologAPI
+
+from .resolver import CohereRequestResponseResolver
+
+logger = logging.getLogger(__name__)
+
+
+autolog = AutologAPI(
+ name="Cohere",
+ symbols=(
+ "Client.generate",
+ "Client.chat",
+ "Client.classify",
+ "Client.summarize",
+ "Client.rerank",
+ ),
+ resolver=CohereRequestResponseResolver(),
+ telemetry_feature="cohere_autolog",
+)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/cohere/resolver.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/cohere/resolver.py
new file mode 100644
index 0000000000000000000000000000000000000000..6cfcdf020b87c8a5a3c15f164226ac50f8670d4d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/cohere/resolver.py
@@ -0,0 +1,347 @@
+import logging
+from datetime import datetime
+from typing import Any, Dict, List, Optional, Sequence, Tuple
+
+import wandb
+from wandb.sdk.integration_utils.auto_logging import Response
+from wandb.sdk.lib.runid import generate_id
+
+logger = logging.getLogger(__name__)
+
+
+def subset_dict(
+ original_dict: Dict[str, Any], keys_subset: Sequence[str]
+) -> Dict[str, Any]:
+ """Create a subset of a dictionary using a subset of keys.
+
+ :param original_dict: The original dictionary.
+ :param keys_subset: The subset of keys to extract.
+ :return: A dictionary containing only the specified keys.
+ """
+ return {key: original_dict[key] for key in keys_subset if key in original_dict}
+
+
+def reorder_and_convert_dict_list_to_table(
+ data: List[Dict[str, Any]], order: List[str]
+) -> Tuple[List[str], List[List[Any]]]:
+ """Convert a list of dictionaries to a pair of column names and corresponding values, with the option to order specific dictionaries.
+
+ :param data: A list of dictionaries.
+ :param order: A list of keys specifying the desired order for specific dictionaries. The remaining dictionaries will be ordered based on their original order.
+ :return: A pair of column names and corresponding values.
+ """
+ final_columns = []
+ keys_present = set()
+
+ # First, add all ordered keys to the final columns
+ for key in order:
+ if key not in keys_present:
+ final_columns.append(key)
+ keys_present.add(key)
+
+ # Then, add any keys present in the dictionaries but not in the order
+ for d in data:
+ for key in d:
+ if key not in keys_present:
+ final_columns.append(key)
+ keys_present.add(key)
+
+ # Then, construct the table of values
+ values = []
+ for d in data:
+ row = []
+ for key in final_columns:
+ row.append(d.get(key, None))
+ values.append(row)
+
+ return final_columns, values
+
+
+def flatten_dict(
+ dictionary: Dict[str, Any], parent_key: str = "", sep: str = "-"
+) -> Dict[str, Any]:
+ """Flatten a nested dictionary, joining keys using a specified separator.
+
+ :param dictionary: The dictionary to flatten.
+ :param parent_key: The base key to prepend to each key.
+ :param sep: The separator to use when joining keys.
+ :return: A flattened dictionary.
+ """
+ flattened_dict = {}
+ for key, value in dictionary.items():
+ new_key = f"{parent_key}{sep}{key}" if parent_key else key
+ if isinstance(value, dict):
+ flattened_dict.update(flatten_dict(value, new_key, sep=sep))
+ else:
+ flattened_dict[new_key] = value
+ return flattened_dict
+
+
+def collect_common_keys(list_of_dicts: List[Dict[str, Any]]) -> Dict[str, List[Any]]:
+ """Collect the common keys of a list of dictionaries. For each common key, put its values into a list in the order they appear in the original dictionaries.
+
+ :param list_of_dicts: The list of dictionaries to inspect.
+ :return: A dictionary with each common key and its corresponding list of values.
+ """
+ common_keys = set.intersection(*map(set, list_of_dicts))
+ common_dict = {key: [] for key in common_keys}
+ for d in list_of_dicts:
+ for key in common_keys:
+ common_dict[key].append(d[key])
+ return common_dict
+
+
+class CohereRequestResponseResolver:
+ """Class to resolve the request/response from the Cohere API and convert it to a dictionary that can be logged."""
+
+ def __call__(
+ self,
+ args: Sequence[Any],
+ kwargs: Dict[str, Any],
+ response: Response,
+ start_time: float,
+ time_elapsed: float,
+ ) -> Optional[Dict[str, Any]]:
+ """Process the response from the Cohere API and convert it to a dictionary that can be logged.
+
+ :param args: The arguments of the original function.
+ :param kwargs: The keyword arguments of the original function.
+ :param response: The response from the Cohere API.
+ :param start_time: The start time of the request.
+ :param time_elapsed: The time elapsed for the request.
+ :return: A dictionary containing the parsed response and timing information.
+ """
+ try:
+ # Each of the different endpoints map to one specific response type
+ # We want to 'type check' the response without directly importing the packages type
+ # It may make more sense to pass the invoked symbol from the AutologAPI instead
+ response_type = str(type(response)).split("'")[1].split(".")[-1]
+
+ # Initialize parsed_response to None to handle the case where the response type is unsupported
+ parsed_response = None
+ if response_type == "Generations":
+ parsed_response = self._resolve_generate_response(response)
+ # TODO: Remove hard-coded default model name
+ table_column_order = [
+ "start_time",
+ "query_id",
+ "model",
+ "prompt",
+ "text",
+ "token_likelihoods",
+ "likelihood",
+ "time_elapsed_(seconds)",
+ "end_time",
+ ]
+ default_model = "command"
+ elif response_type == "Chat":
+ parsed_response = self._resolve_chat_response(response)
+ table_column_order = [
+ "start_time",
+ "query_id",
+ "model",
+ "conversation_id",
+ "response_id",
+ "query",
+ "text",
+ "prompt",
+ "preamble",
+ "chat_history",
+ "chatlog",
+ "time_elapsed_(seconds)",
+ "end_time",
+ ]
+ default_model = "command"
+ elif response_type == "Classifications":
+ parsed_response = self._resolve_classify_response(response)
+ kwargs = self._resolve_classify_kwargs(kwargs)
+ table_column_order = [
+ "start_time",
+ "query_id",
+ "model",
+ "id",
+ "input",
+ "prediction",
+ "confidence",
+ "time_elapsed_(seconds)",
+ "end_time",
+ ]
+ default_model = "embed-english-v2.0"
+ elif response_type == "SummarizeResponse":
+ parsed_response = self._resolve_summarize_response(response)
+ table_column_order = [
+ "start_time",
+ "query_id",
+ "model",
+ "response_id",
+ "text",
+ "additional_command",
+ "summary",
+ "time_elapsed_(seconds)",
+ "end_time",
+ "length",
+ "format",
+ ]
+ default_model = "summarize-xlarge"
+ elif response_type == "Reranking":
+ parsed_response = self._resolve_rerank_response(response)
+ table_column_order = [
+ "start_time",
+ "query_id",
+ "model",
+ "id",
+ "query",
+ "top_n",
+ # This is a nested dict key that got flattened
+ "document-text",
+ "relevance_score",
+ "index",
+ "time_elapsed_(seconds)",
+ "end_time",
+ ]
+ default_model = "rerank-english-v2.0"
+ else:
+ logger.info(f"Unsupported Cohere response object: {response}")
+
+ return self._resolve(
+ args,
+ kwargs,
+ parsed_response,
+ start_time,
+ time_elapsed,
+ response_type,
+ table_column_order,
+ default_model,
+ )
+ except Exception as e:
+ logger.warning(f"Failed to resolve request/response: {e}")
+ return None
+
+ # These helper functions process the response from different endpoints of the Cohere API.
+ # Since the response objects for different endpoints have different structures,
+ # we need different logic to process them.
+
+ def _resolve_generate_response(self, response: Response) -> List[Dict[str, Any]]:
+ return_list = []
+ for _response in response:
+ # Built in Cohere.*.Generations function to color token_likelihoods and return a dict of response data
+ _response_dict = _response._visualize_helper()
+ try:
+ _response_dict["token_likelihoods"] = wandb.Html(
+ _response_dict["token_likelihoods"]
+ )
+ except (KeyError, ValueError):
+ pass
+ return_list.append(_response_dict)
+
+ return return_list
+
+ def _resolve_chat_response(self, response: Response) -> List[Dict[str, Any]]:
+ return [
+ subset_dict(
+ response.__dict__,
+ [
+ "response_id",
+ "generation_id",
+ "query",
+ "text",
+ "conversation_id",
+ "prompt",
+ "chatlog",
+ "preamble",
+ ],
+ )
+ ]
+
+ def _resolve_classify_response(self, response: Response) -> List[Dict[str, Any]]:
+ # The labels key is a dict returning the scores for the classification probability for each label provided
+ # We flatten this nested dict for ease of consumption in the wandb UI
+ return [flatten_dict(_response.__dict__) for _response in response]
+
+ def _resolve_classify_kwargs(self, kwargs: Dict[str, Any]) -> Dict[str, Any]:
+ # Example texts look strange when rendered in Wandb UI as it is a list of text and label
+ # We extract each value into its own column
+ example_texts = []
+ example_labels = []
+ for example in kwargs["examples"]:
+ example_texts.append(example.text)
+ example_labels.append(example.label)
+ kwargs.pop("examples")
+ kwargs["example_texts"] = example_texts
+ kwargs["example_labels"] = example_labels
+ return kwargs
+
+ def _resolve_summarize_response(self, response: Response) -> List[Dict[str, Any]]:
+ return [{"response_id": response.id, "summary": response.summary}]
+
+ def _resolve_rerank_response(self, response: Response) -> List[Dict[str, Any]]:
+ # The documents key contains a dict containing the content of the document which is at least "text"
+ # We flatten this nested dict for ease of consumption in the wandb UI
+ flattened_response_dicts = [
+ flatten_dict(_response.__dict__) for _response in response
+ ]
+ # ReRank returns each document provided a top_n value so we aggregate into one view so users can paginate a row
+ # As opposed to each row being one of the top_n responses
+ return_dict = collect_common_keys(flattened_response_dicts)
+ return_dict["id"] = response.id
+ return [return_dict]
+
+ def _resolve(
+ self,
+ args: Sequence[Any],
+ kwargs: Dict[str, Any],
+ parsed_response: List[Dict[str, Any]],
+ start_time: float,
+ time_elapsed: float,
+ response_type: str,
+ table_column_order: List[str],
+ default_model: str,
+ ) -> Dict[str, Any]:
+ """Convert a list of dictionaries to a pair of column names and corresponding values, with the option to order specific dictionaries.
+
+ :param args: The arguments passed to the API client.
+ :param kwargs: The keyword arguments passed to the API client.
+ :param parsed_response: The parsed response from the API.
+ :param start_time: The start time of the API request.
+ :param time_elapsed: The time elapsed during the API request.
+ :param response_type: The type of the API response.
+ :param table_column_order: The desired order of columns in the resulting table.
+ :param default_model: The default model to use if not specified in the response.
+ :return: A dictionary containing the formatted response.
+ """
+ # Args[0] is the client object where we can grab specific metadata about the underlying API status
+ query_id = generate_id(length=16)
+ parsed_args = subset_dict(
+ args[0].__dict__,
+ ["api_version", "batch_size", "max_retries", "num_workers", "timeout"],
+ )
+
+ start_time_dt = datetime.fromtimestamp(start_time)
+ end_time_dt = datetime.fromtimestamp(start_time + time_elapsed)
+
+ timings = {
+ "start_time": start_time_dt,
+ "end_time": end_time_dt,
+ "time_elapsed_(seconds)": time_elapsed,
+ }
+
+ packed_data = []
+ for _parsed_response in parsed_response:
+ _packed_dict = {
+ "query_id": query_id,
+ **kwargs,
+ **_parsed_response,
+ **timings,
+ **parsed_args,
+ }
+ if "model" not in _packed_dict:
+ _packed_dict["model"] = default_model
+ packed_data.append(_packed_dict)
+
+ columns, data = reorder_and_convert_dict_list_to_table(
+ packed_data, table_column_order
+ )
+
+ request_response_table = wandb.Table(data=data, columns=columns)
+
+ return {f"{response_type}": request_response_table}
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/diffusers/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/diffusers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5bcf7980133c41393fdc22db3bbff89be29be94e
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/diffusers/__init__.py
@@ -0,0 +1,3 @@
+from .autologger import autolog
+
+__all__ = ["autolog"]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/diffusers/autologger.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/diffusers/autologger.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad21a77edc6a1125f8d2f5621c046c6bbe1f0b9b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/diffusers/autologger.py
@@ -0,0 +1,76 @@
+import logging
+
+from wandb.sdk.integration_utils.auto_logging import AutologAPI
+
+from .pipeline_resolver import DiffusersPipelineResolver
+
+logger = logging.getLogger(__name__)
+
+autolog = AutologAPI(
+ name="diffusers",
+ symbols=(
+ "DiffusionPipeline.__call__",
+ "AutoPipelineForText2Image.__call__",
+ "AutoPipelineForImage2Image.__call__",
+ "AutoPipelineForInpainting.__call__",
+ "StableDiffusionPipeline.__call__",
+ "KandinskyCombinedPipeline.__call__",
+ "KandinskyV22CombinedPipeline.__call__",
+ "LatentConsistencyModelPipeline.__call__",
+ "LDMTextToImagePipeline.__call__",
+ "StableDiffusionPanoramaPipeline.__call__",
+ "StableDiffusionParadigmsPipeline.__call__",
+ "PixArtAlphaPipeline.__call__",
+ "StableDiffusionSAGPipeline.__call__",
+ "SemanticStableDiffusionPipeline.__call__",
+ "WuerstchenCombinedPipeline.__call__",
+ "AltDiffusionPipeline.__call__",
+ "StableDiffusionAttendAndExcitePipeline.__call__",
+ "StableDiffusionXLPipeline.__call__",
+ "StableDiffusionXLImg2ImgPipeline.__call__",
+ "IFPipeline.__call__",
+ "BlipDiffusionPipeline.__call__",
+ "BlipDiffusionControlNetPipeline.__call__",
+ "StableDiffusionControlNetPipeline.__call__",
+ "StableDiffusionControlNetImg2ImgPipeline.__call__",
+ "StableDiffusionControlNetInpaintPipeline.__call__",
+ "CycleDiffusionPipeline.__call__",
+ "StableDiffusionInstructPix2PixPipeline.__call__",
+ "PaintByExamplePipeline.__call__",
+ "RePaintPipeline.__call__",
+ "KandinskyImg2ImgCombinedPipeline.__call__",
+ "KandinskyInpaintCombinedPipeline.__call__",
+ "KandinskyV22Img2ImgCombinedPipeline.__call__",
+ "KandinskyV22InpaintCombinedPipeline.__call__",
+ "Kandinsky3Pipeline.__call__",
+ "Kandinsky3Img2ImgPipeline.__call__",
+ "AnimateDiffPipeline.__call__",
+ "AudioLDMPipeline.__call__",
+ "AudioLDM2Pipeline.__call__",
+ "MusicLDMPipeline.__call__",
+ "StableDiffusionPix2PixZeroPipeline.__call__",
+ "PNDMPipeline.__call__",
+ "ShapEPipeline.__call__",
+ "StableDiffusionImg2ImgPipeline.__call__",
+ "StableDiffusionInpaintPipeline.__call__",
+ "StableDiffusionDepth2ImgPipeline.__call__",
+ "StableDiffusionImageVariationPipeline.__call__",
+ "StableDiffusionPipelineSafe.__call__",
+ "StableDiffusionUpscalePipeline.__call__",
+ "StableDiffusionAdapterPipeline.__call__",
+ "StableDiffusionGLIGENPipeline.__call__",
+ "StableDiffusionModelEditingPipeline.__call__",
+ "VersatileDiffusionTextToImagePipeline.__call__",
+ "VersatileDiffusionImageVariationPipeline.__call__",
+ "VersatileDiffusionDualGuidedPipeline.__call__",
+ "LDMPipeline.__call__",
+ "TextToVideoSDPipeline.__call__",
+ "TextToVideoZeroPipeline.__call__",
+ "StableVideoDiffusionPipeline.__call__",
+ "AmusedPipeline.__call__",
+ "StableDiffusionXLControlNetPipeline.__call__",
+ "StableDiffusionXLControlNetImg2ImgPipeline.__call__",
+ ),
+ resolver=DiffusersPipelineResolver(),
+ telemetry_feature="diffusers_autolog",
+)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/diffusers/pipeline_resolver.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/diffusers/pipeline_resolver.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5c4d73511c20f53e75f4b1cbf5a6cfc444c8875
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/diffusers/pipeline_resolver.py
@@ -0,0 +1,50 @@
+from typing import Any, Dict, Sequence
+
+from wandb.sdk.integration_utils.auto_logging import Response
+
+from .resolvers import (
+ SUPPORTED_MULTIMODAL_PIPELINES,
+ DiffusersMultiModalPipelineResolver,
+)
+
+
+class DiffusersPipelineResolver:
+ """Resolver for `DiffusionPipeline` request and responses from [HuggingFace Diffusers](https://huggingface.co/docs/diffusers/index), providing necessary data transformations, formatting, and logging.
+
+ This is based off `wandb.sdk.integration_utils.auto_logging.RequestResponseResolver`.
+ """
+
+ def __init__(self) -> None:
+ self.wandb_table = None
+ self.pipeline_call_count = 1
+
+ def __call__(
+ self,
+ args: Sequence[Any],
+ kwargs: Dict[str, Any],
+ response: Response,
+ start_time: float,
+ time_elapsed: float,
+ ) -> Any:
+ """Main call method for the `DiffusersPipelineResolver` class.
+
+ Args:
+ args: (Sequence[Any]) List of arguments.
+ kwargs: (Dict[str, Any]) Dictionary of keyword arguments.
+ response: (wandb.sdk.integration_utils.auto_logging.Response) The response from
+ the request.
+ start_time: (float) Time when request started.
+ time_elapsed: (float) Time elapsed for the request.
+
+ Returns:
+ Packed data as a dictionary for logging to wandb, None if an exception occurred.
+ """
+ pipeline_name = args[0].__class__.__name__
+ resolver = None
+ if pipeline_name in SUPPORTED_MULTIMODAL_PIPELINES:
+ resolver = DiffusersMultiModalPipelineResolver(
+ pipeline_name, self.pipeline_call_count
+ )
+ self.pipeline_call_count += 1
+ loggable_dict = resolver(args, kwargs, response, start_time, time_elapsed)
+ return loggable_dict
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/diffusers/resolvers/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/diffusers/resolvers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6211bd4bc2b9901593e477c1b5713bc074f8804
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/diffusers/resolvers/__init__.py
@@ -0,0 +1,9 @@
+from .multimodal import (
+ SUPPORTED_MULTIMODAL_PIPELINES,
+ DiffusersMultiModalPipelineResolver,
+)
+
+__all__ = [
+ "SUPPORTED_MULTIMODAL_PIPELINES",
+ "DiffusersMultiModalPipelineResolver",
+]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/diffusers/resolvers/multimodal.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/diffusers/resolvers/multimodal.py
new file mode 100644
index 0000000000000000000000000000000000000000..34ef33e8639193b8f87a65434e6261ff112fbd7a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/diffusers/resolvers/multimodal.py
@@ -0,0 +1,881 @@
+import logging
+from typing import Any, Dict, List, Sequence
+
+import wandb
+from wandb.sdk.integration_utils.auto_logging import Response
+
+from .utils import (
+ chunkify,
+ decode_sdxl_t2i_latents,
+ get_updated_kwargs,
+ postprocess_np_arrays_for_video,
+ postprocess_pils_to_np,
+)
+
+logger = logging.getLogger(__name__)
+
+
+SUPPORTED_MULTIMODAL_PIPELINES = {
+ "BlipDiffusionPipeline": {
+ "table-schema": [
+ "Reference-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Source-Subject-Category",
+ "Target-Subject-Category",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "reference_image",
+ "prompt",
+ "neg_prompt",
+ "source_subject_category",
+ "target_subject_category",
+ ],
+ "kwarg-actions": [wandb.Image, None, None, None, None],
+ },
+ "BlipDiffusionControlNetPipeline": {
+ "table-schema": [
+ "Reference-Image",
+ "Control-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Source-Subject-Category",
+ "Target-Subject-Category",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "reference_image",
+ "condtioning_image",
+ "prompt",
+ "neg_prompt",
+ "source_subject_category",
+ "target_subject_category",
+ ],
+ "kwarg-actions": [wandb.Image, wandb.Image, None, None, None, None],
+ },
+ "StableDiffusionControlNetPipeline": {
+ "table-schema": [
+ "Control-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "StableDiffusionControlNetImg2ImgPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Control-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "control_image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, wandb.Image, None, None],
+ },
+ "StableDiffusionControlNetInpaintPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Mask-Image",
+ "Control-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "image",
+ "mask_image",
+ "control_image",
+ "prompt",
+ "negative_prompt",
+ ],
+ "kwarg-actions": [wandb.Image, wandb.Image, wandb.Image, None, None],
+ },
+ "CycleDiffusionPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Source-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "image",
+ "prompt",
+ "source_prompt",
+ ],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "StableDiffusionInstructPix2PixPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "image",
+ "prompt",
+ "negative_prompt",
+ ],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "PaintByExamplePipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Example-Image",
+ "Mask-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "image",
+ "example_image",
+ "mask_image",
+ ],
+ "kwarg-actions": [wandb.Image, wandb.Image, wandb.Image],
+ },
+ "RePaintPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Mask-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "image",
+ "mask_image",
+ ],
+ "kwarg-actions": [wandb.Image, wandb.Image],
+ },
+ "StableDiffusionPipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "KandinskyCombinedPipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "KandinskyV22CombinedPipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "LatentConsistencyModelPipeline": {
+ "table-schema": ["Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt"],
+ "kwarg-actions": [None],
+ },
+ "LDMTextToImagePipeline": {
+ "table-schema": ["Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt"],
+ "kwarg-actions": [None],
+ },
+ "StableDiffusionPanoramaPipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "PixArtAlphaPipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "StableDiffusionSAGPipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "SemanticStableDiffusionPipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "WuerstchenCombinedPipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "IFPipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "AltDiffusionPipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "StableDiffusionAttendAndExcitePipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "KandinskyImg2ImgCombinedPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "KandinskyInpaintCombinedPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "KandinskyV22Img2ImgCombinedPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "KandinskyV22InpaintCombinedPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "AnimateDiffPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Number-of-Frames",
+ "Generated-Video",
+ ],
+ "kwarg-logging": ["prompt", "negative_prompt", "num_frames"],
+ "kwarg-actions": [None, None, None],
+ "output-type": "video",
+ },
+ "StableVideoDiffusionPipeline": {
+ "table-schema": [
+ "Input-Image",
+ "Frames-Per-Second",
+ "Generated-Video",
+ ],
+ "kwarg-logging": ["image", "fps"],
+ "kwarg-actions": [wandb.Image, None],
+ "output-type": "video",
+ },
+ "AudioLDMPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Audio-Length-in-Seconds",
+ "Generated-Audio",
+ ],
+ "kwarg-logging": ["prompt", "negative_prompt", "audio_length_in_s"],
+ "kwarg-actions": [None, None, None],
+ "output-type": "audio",
+ },
+ "AudioLDM2Pipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Audio-Length-in-Seconds",
+ "Generated-Audio",
+ ],
+ "kwarg-logging": ["prompt", "negative_prompt", "audio_length_in_s"],
+ "kwarg-actions": [None, None, None],
+ "output-type": "audio",
+ },
+ "MusicLDMPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Audio-Length-in-Seconds",
+ "Generated-Audio",
+ ],
+ "kwarg-logging": ["prompt", "negative_prompt", "audio_length_in_s"],
+ "kwarg-actions": [None, None, None],
+ "output-type": "audio",
+ },
+ "StableDiffusionPix2PixZeroPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "PNDMPipeline": {
+ "table-schema": [
+ "Batch-Size",
+ "Number-of-Inference-Steps",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["batch_size", "num_inference_steps"],
+ "kwarg-actions": [None, None],
+ },
+ "ShapEPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Generated-Video",
+ ],
+ "kwarg-logging": ["prompt"],
+ "kwarg-actions": [None],
+ "output-type": "video",
+ },
+ "StableDiffusionImg2ImgPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "StableDiffusionInpaintPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Mask-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "mask_image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, wandb.Image, None, None],
+ },
+ "StableDiffusionDepth2ImgPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "StableDiffusionImageVariationPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "image",
+ ],
+ "kwarg-actions": [wandb.Image],
+ },
+ "StableDiffusionPipelineSafe": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "StableDiffusionUpscalePipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Upscaled-Image",
+ ],
+ "kwarg-logging": ["image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "StableDiffusionAdapterPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "StableDiffusionGLIGENPipeline": {
+ "table-schema": [
+ "Prompt",
+ "GLIGEN-Phrases",
+ "GLIGEN-Boxes",
+ "GLIGEN-Inpaint-Image",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "prompt",
+ "gligen_phrases",
+ "gligen_boxes",
+ "gligen_inpaint_image",
+ "negative_prompt",
+ ],
+ "kwarg-actions": [None, None, None, wandb.Image, None],
+ },
+ "VersatileDiffusionTextToImagePipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "VersatileDiffusionImageVariationPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None],
+ },
+ "VersatileDiffusionDualGuidedPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "LDMPipeline": {
+ "table-schema": [
+ "Batch-Size",
+ "Number-of-Inference-Steps",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["batch_size", "num_inference_steps"],
+ "kwarg-actions": [None, None],
+ },
+ "TextToVideoSDPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Number-of-Frames",
+ "Generated-Video",
+ ],
+ "kwarg-logging": ["prompt", "negative_prompt", "num_frames"],
+ "output-type": "video",
+ },
+ "TextToVideoZeroPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Number-of-Frames",
+ "Generated-Video",
+ ],
+ "kwarg-logging": ["prompt", "negative_prompt", "video_length"],
+ },
+ "AmusedPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Guidance Scale",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "prompt",
+ "guidance_scale",
+ ],
+ "kwarg-actions": [None, None],
+ },
+ "StableDiffusionXLControlNetPipeline": {
+ "table-schema": [
+ "Prompt-1",
+ "Prompt-2",
+ "Control-Image",
+ "Negative-Prompt-1",
+ "Negative-Prompt-2",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "prompt",
+ "prompt_2",
+ "image",
+ "negative_prompt",
+ "negative_prompt_2",
+ ],
+ "kwarg-actions": [None, None, wandb.Image, None, None],
+ },
+ "StableDiffusionXLControlNetImg2ImgPipeline": {
+ "table-schema": [
+ "Prompt-1",
+ "Prompt-2",
+ "Input-Image",
+ "Control-Image",
+ "Negative-Prompt-1",
+ "Negative-Prompt-2",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "prompt",
+ "prompt_2",
+ "image",
+ "control_image",
+ "negative_prompt",
+ "negative_prompt_2",
+ ],
+ "kwarg-actions": [None, None, wandb.Image, wandb.Image, None, None],
+ },
+ "Kandinsky3Pipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "prompt",
+ "negative_prompt",
+ ],
+ "kwarg-actions": [None, None],
+ },
+ "Kandinsky3Img2ImgPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Input-Image",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "prompt",
+ "negative_prompt",
+ "image",
+ ],
+ "kwarg-actions": [None, None, wandb.Image],
+ },
+ "StableDiffusionXLPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Prompt-2",
+ "Negative-Prompt-2",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "prompt",
+ "negative_prompt",
+ "prompt_2",
+ "negative_prompt_2",
+ ],
+ "kwarg-actions": [None, None, None, None],
+ },
+ "StableDiffusionXLImg2ImgPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Prompt-2",
+ "Negative-Prompt-2",
+ "Input-Image",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "prompt",
+ "negative_prompt",
+ "prompt_2",
+ "negative_prompt_2",
+ "image",
+ ],
+ "kwarg-actions": [None, None, None, None, wandb.Image],
+ },
+}
+
+
+class DiffusersMultiModalPipelineResolver:
+ """Resolver for request and responses from [HuggingFace Diffusers](https://huggingface.co/docs/diffusers/index) multi-modal Diffusion Pipelines, providing necessary data transformations, formatting, and logging.
+
+ This resolver is internally involved in the
+ `__call__` for `wandb.integration.diffusers.pipeline_resolver.DiffusersPipelineResolver`.
+ This is based on `wandb.sdk.integration_utils.auto_logging.RequestResponseResolver`.
+
+ Args:
+ pipeline_name: (str) The name of the Diffusion Pipeline.
+ """
+
+ def __init__(self, pipeline_name: str, pipeline_call_count: int) -> None:
+ self.pipeline_name = pipeline_name
+ self.pipeline_call_count = pipeline_call_count
+ columns = []
+ if pipeline_name in SUPPORTED_MULTIMODAL_PIPELINES:
+ columns += SUPPORTED_MULTIMODAL_PIPELINES[pipeline_name]["table-schema"]
+ else:
+ wandb.Error("Pipeline not supported for logging")
+ self.wandb_table = wandb.Table(columns=columns)
+
+ def __call__(
+ self,
+ args: Sequence[Any],
+ kwargs: Dict[str, Any],
+ response: Response,
+ start_time: float,
+ time_elapsed: float,
+ ) -> Any:
+ """Main call method for the `DiffusersPipelineResolver` class.
+
+ Args:
+ args: (Sequence[Any]) List of arguments.
+ kwargs: (Dict[str, Any]) Dictionary of keyword arguments.
+ response: (wandb.sdk.integration_utils.auto_logging.Response) The response from
+ the request.
+ start_time: (float) Time when request started.
+ time_elapsed: (float) Time elapsed for the request.
+
+ Returns:
+ Packed data as a dictionary for logging to wandb, None if an exception occurred.
+ """
+ try:
+ # Get the pipeline and the args
+ pipeline, args = args[0], args[1:]
+
+ # Update the Kwargs so that they can be logged easily
+ kwargs = get_updated_kwargs(pipeline, args, kwargs)
+
+ # Get the pipeline configs
+ pipeline_configs = dict(pipeline.config)
+ pipeline_configs["pipeline-name"] = self.pipeline_name
+
+ if "workflow" not in wandb.config:
+ wandb.config.update(
+ {
+ "workflow": [
+ {
+ "pipeline": pipeline_configs,
+ "params": kwargs,
+ "stage": f"Pipeline-Call-{self.pipeline_call_count}",
+ }
+ ]
+ }
+ )
+ else:
+ existing_workflow = wandb.config.workflow
+ updated_workflow = existing_workflow + [
+ {
+ "pipeline": pipeline_configs,
+ "params": kwargs,
+ "stage": f"Pipeline-Call-{self.pipeline_call_count}",
+ }
+ ]
+ wandb.config.update(
+ {"workflow": updated_workflow}, allow_val_change=True
+ )
+
+ # Return the WandB loggable dict
+ return self.prepare_loggable_dict(pipeline, response, kwargs)
+ except Exception as e:
+ logger.warning(e)
+ return None
+
+ def get_output_images(self, response: Response) -> List:
+ """Unpack the generated images, audio, video, etc. from the Diffusion Pipeline's response.
+
+ Args:
+ response: (wandb.sdk.integration_utils.auto_logging.Response) The response from
+ the request.
+
+ Returns:
+ List of generated images, audio, video, etc.
+ """
+ if "output-type" not in SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]:
+ return response.images
+ else:
+ if (
+ SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]["output-type"]
+ == "video"
+ ):
+ if self.pipeline_name in ["ShapEPipeline"]:
+ return response.images
+ return response.frames
+ elif (
+ SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]["output-type"]
+ == "audio"
+ ):
+ return response.audios
+
+ def log_media(self, image: Any, loggable_kwarg_chunks: List, idx: int) -> None:
+ """Log the generated images, audio, video, etc. from the Diffusion Pipeline's response along with an optional caption to a media panel in the run.
+
+ Args:
+ image: (Any) The generated images, audio, video, etc. from the Diffusion
+ Pipeline's response.
+ loggable_kwarg_chunks: (List) Loggable chunks of kwargs.
+ """
+ if "output-type" not in SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]:
+ try:
+ caption = ""
+ if self.pipeline_name in [
+ "StableDiffusionXLPipeline",
+ "StableDiffusionXLImg2ImgPipeline",
+ ]:
+ prompt_index = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][
+ "kwarg-logging"
+ ].index("prompt")
+ prompt2_index = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][
+ "kwarg-logging"
+ ].index("prompt_2")
+ caption = f"Prompt-1: {loggable_kwarg_chunks[prompt_index][idx]}\nPrompt-2: {loggable_kwarg_chunks[prompt2_index][idx]}"
+ else:
+ prompt_index = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][
+ "kwarg-logging"
+ ].index("prompt")
+ caption = loggable_kwarg_chunks[prompt_index][idx]
+ except ValueError:
+ caption = None
+ wandb.log(
+ {
+ f"Generated-Image/Pipeline-Call-{self.pipeline_call_count}": wandb.Image(
+ image, caption=caption
+ )
+ }
+ )
+ else:
+ if (
+ SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]["output-type"]
+ == "video"
+ ):
+ try:
+ prompt_index = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][
+ "kwarg-logging"
+ ].index("prompt")
+ caption = loggable_kwarg_chunks[prompt_index][idx]
+ except ValueError:
+ caption = None
+ wandb.log(
+ {
+ f"Generated-Video/Pipeline-Call-{self.pipeline_call_count}": wandb.Video(
+ postprocess_pils_to_np(image), fps=4, caption=caption
+ )
+ }
+ )
+ elif (
+ SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]["output-type"]
+ == "audio"
+ ):
+ try:
+ prompt_index = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][
+ "kwarg-logging"
+ ].index("prompt")
+ caption = loggable_kwarg_chunks[prompt_index][idx]
+ except ValueError:
+ caption = None
+ wandb.log(
+ {
+ f"Generated-Audio/Pipeline-Call-{self.pipeline_call_count}": wandb.Audio(
+ image, sample_rate=16000, caption=caption
+ )
+ }
+ )
+
+ def add_data_to_table(
+ self, image: Any, loggable_kwarg_chunks: List, idx: int
+ ) -> None:
+ """Populate the row of the `wandb.Table`.
+
+ Args:
+ image: (Any) The generated images, audio, video, etc. from the Diffusion
+ Pipeline's response.
+ loggable_kwarg_chunks: (List) Loggable chunks of kwargs.
+ idx: (int) Chunk index.
+ """
+ table_row = []
+ kwarg_actions = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][
+ "kwarg-actions"
+ ]
+ for column_idx, loggable_kwarg_chunk in enumerate(loggable_kwarg_chunks):
+ if kwarg_actions[column_idx] is None:
+ table_row.append(
+ loggable_kwarg_chunk[idx]
+ if loggable_kwarg_chunk[idx] is not None
+ else ""
+ )
+ else:
+ table_row.append(kwarg_actions[column_idx](loggable_kwarg_chunk[idx]))
+ if "output-type" not in SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]:
+ table_row.append(wandb.Image(image))
+ else:
+ if (
+ SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]["output-type"]
+ == "video"
+ ):
+ table_row.append(wandb.Video(postprocess_pils_to_np(image), fps=4))
+ elif (
+ SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]["output-type"]
+ == "audio"
+ ):
+ table_row.append(wandb.Audio(image, sample_rate=16000))
+ self.wandb_table.add_data(*table_row)
+
+ def prepare_loggable_dict(
+ self, pipeline: Any, response: Response, kwargs: Dict[str, Any]
+ ) -> Dict[str, Any]:
+ """Prepare the loggable dictionary, which is the packed data as a dictionary for logging to wandb, None if an exception occurred.
+
+ Args:
+ pipeline: (Any) The Diffusion Pipeline.
+ response: (wandb.sdk.integration_utils.auto_logging.Response) The response from
+ the request.
+ kwargs: (Dict[str, Any]) Dictionary of keyword arguments.
+
+ Returns:
+ Packed data as a dictionary for logging to wandb, None if an exception occurred.
+ """
+ # Unpack the generated images, audio, video, etc. from the Diffusion Pipeline's response.
+ images = self.get_output_images(response)
+ if (
+ self.pipeline_name == "StableDiffusionXLPipeline"
+ and kwargs["output_type"] == "latent"
+ ):
+ images = decode_sdxl_t2i_latents(pipeline, response.images)
+
+ # Account for exception pipelines for text-to-video
+ if self.pipeline_name in ["TextToVideoSDPipeline", "TextToVideoZeroPipeline"]:
+ video = postprocess_np_arrays_for_video(
+ images, normalize=self.pipeline_name == "TextToVideoZeroPipeline"
+ )
+ wandb.log(
+ {
+ f"Generated-Video/Pipeline-Call-{self.pipeline_call_count}": wandb.Video(
+ video, fps=4, caption=kwargs["prompt"]
+ )
+ }
+ )
+ loggable_kwarg_ids = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][
+ "kwarg-logging"
+ ]
+ table_row = [
+ kwargs[loggable_kwarg_ids[idx]]
+ for idx in range(len(loggable_kwarg_ids))
+ ]
+ table_row.append(wandb.Video(video, fps=4))
+ self.wandb_table.add_data(*table_row)
+ else:
+ loggable_kwarg_ids = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][
+ "kwarg-logging"
+ ]
+ # chunkify loggable kwargs
+ loggable_kwarg_chunks = []
+ for loggable_kwarg_id in loggable_kwarg_ids:
+ loggable_kwarg_chunks.append(
+ kwargs[loggable_kwarg_id]
+ if isinstance(kwargs[loggable_kwarg_id], list)
+ else [kwargs[loggable_kwarg_id]]
+ )
+ # chunkify the generated media
+ images = chunkify(images, len(loggable_kwarg_chunks[0]))
+ for idx in range(len(loggable_kwarg_chunks[0])):
+ for image in images[idx]:
+ # Log media to media panel
+ self.log_media(image, loggable_kwarg_chunks, idx)
+ # Populate the row of the wandb_table
+ self.add_data_to_table(image, loggable_kwarg_chunks, idx)
+ return {
+ f"Result-Table/Pipeline-Call-{self.pipeline_call_count}": self.wandb_table
+ }
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/diffusers/resolvers/utils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/diffusers/resolvers/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..82a6aac045ba9739af9d0ab342a63e33252b63e0
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/diffusers/resolvers/utils.py
@@ -0,0 +1,102 @@
+import inspect
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence
+
+import wandb
+from wandb.util import get_module
+
+if TYPE_CHECKING:
+ np_array = get_module("numpy.array")
+ torch_float_tensor = get_module("torch.FloatTensor")
+
+
+def chunkify(input_list, chunk_size) -> List:
+ chunk_size = max(1, chunk_size)
+ return [
+ input_list[i : i + chunk_size] for i in range(0, len(input_list), chunk_size)
+ ]
+
+
+def get_updated_kwargs(
+ pipeline: Any, args: Sequence[Any], kwargs: Dict[str, Any]
+) -> Dict[str, Any]:
+ pipeline_call_parameters = list(
+ inspect.signature(pipeline.__call__).parameters.items()
+ )
+ for idx, arg in enumerate(args):
+ kwargs[pipeline_call_parameters[idx][0]] = arg
+ for pipeline_parameter in pipeline_call_parameters:
+ if pipeline_parameter[0] not in kwargs:
+ kwargs[pipeline_parameter[0]] = pipeline_parameter[1].default
+ if "generator" in kwargs:
+ generator = kwargs["generator"]
+ kwargs["generator"] = (
+ {
+ "seed": generator.initial_seed(),
+ "device": generator.device,
+ "random_state": generator.get_state().cpu().numpy().tolist(),
+ }
+ if generator is not None
+ else None
+ )
+ if "ip_adapter_image" in kwargs:
+ if kwargs["ip_adapter_image"] is not None:
+ wandb.log({"IP-Adapter-Image": wandb.Image(kwargs["ip_adapter_image"])})
+ return kwargs
+
+
+def postprocess_pils_to_np(image: List) -> "np_array":
+ np = get_module(
+ "numpy",
+ required="Please ensure NumPy is installed. You can run `pip install numpy` to install it.",
+ )
+ return np.stack(
+ [np.transpose(np.array(img).astype("uint8"), axes=(2, 0, 1)) for img in image],
+ axis=0,
+ )
+
+
+def postprocess_np_arrays_for_video(
+ images: List["np_array"], normalize: Optional[bool] = False
+) -> "np_array":
+ np = get_module(
+ "numpy",
+ required="Please ensure NumPy is installed. You can run `pip install numpy` to install it.",
+ )
+ images = [(img * 255).astype("uint8") for img in images] if normalize else images
+ return np.transpose(np.stack((images), axis=0), axes=(0, 3, 1, 2))
+
+
+def decode_sdxl_t2i_latents(pipeline: Any, latents: "torch_float_tensor") -> List:
+ """Decode latents generated by [`diffusers.StableDiffusionXLPipeline`](https://huggingface.co/docs/diffusers/main/en/api/pipelines/stable_diffusion/stable_diffusion_xl#stable-diffusion-xl).
+
+ Args:
+ pipeline: (diffusers.DiffusionPipeline) The Diffusion Pipeline from
+ [`diffusers`](https://huggingface.co/docs/diffusers).
+ latents (torch.FloatTensor): The generated latents.
+
+ Returns:
+ List of `PIL` images corresponding to the generated latents.
+ """
+ torch = get_module(
+ "torch",
+ required="Please ensure PyTorch is installed. You can check out https://pytorch.org/get-started/locally/#start-locally for installation instructions.",
+ )
+ with torch.no_grad():
+ needs_upcasting = (
+ pipeline.vae.dtype == torch.float16 and pipeline.vae.config.force_upcast
+ )
+ if needs_upcasting:
+ pipeline.upcast_vae()
+ latents = latents.to(
+ next(iter(pipeline.vae.post_quant_conv.parameters())).dtype
+ )
+ images = pipeline.vae.decode(
+ latents / pipeline.vae.config.scaling_factor, return_dict=False
+ )[0]
+ if needs_upcasting:
+ pipeline.vae.to(dtype=torch.float16)
+ if pipeline.watermark is not None:
+ images = pipeline.watermark.apply_watermark(images)
+ images = pipeline.image_processor.postprocess(images, output_type="pil")
+ pipeline.maybe_free_model_hooks()
+ return images
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/dspy/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/dspy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8d5490703ce96e5cd79294c05051313939fca49
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/dspy/__init__.py
@@ -0,0 +1,5 @@
+"""W&B DSPy integration package."""
+
+from .dspy import WandbDSPyCallback
+
+__all__ = ["WandbDSPyCallback"]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/dspy/dspy.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/dspy/dspy.py
new file mode 100644
index 0000000000000000000000000000000000000000..11857fb3a176b02aa7f9355a964372cd69e88159
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/dspy/dspy.py
@@ -0,0 +1,422 @@
+"""DSPy ↔ Weights & Biases integration."""
+
+from __future__ import annotations
+
+import logging
+import os
+from collections.abc import Mapping, Sequence
+from typing import Any, Literal
+
+import wandb
+import wandb.util
+from wandb.sdk.wandb_run import Run
+
+dspy = wandb.util.get_module(
+ name="dspy",
+ required=(
+ "To use the W&B DSPy integration you need to have the `dspy` "
+ "python package installed. Install it with `uv pip install dspy`."
+ ),
+ lazy=False,
+)
+if dspy is not None:
+ assert dspy.__version__ >= "3.0.0", (
+ "DSPy 3.0.0 or higher is required. You have " + dspy.__version__
+ )
+
+
+logger = logging.getLogger(__name__)
+
+
+def _flatten_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Flatten a list of nested row dicts into flat key/value dicts.
+
+ Args:
+ rows (list[dict[str, Any]]): List of nested dictionaries to flatten.
+
+ Returns:
+ list[dict[str, Any]]: List of flattened dictionaries.
+
+ """
+
+ def _flatten(
+ d: dict[str, Any], parent_key: str = "", sep: str = "."
+ ) -> dict[str, Any]:
+ items = []
+ for k, v in d.items():
+ new_key = f"{parent_key}{sep}{k}" if parent_key else k
+ if isinstance(v, dict):
+ items.extend(_flatten(v, new_key, sep=sep).items())
+ else:
+ items.append((new_key, v))
+ return dict(items)
+
+ return [_flatten(row) for row in rows]
+
+
+class WandbDSPyCallback(dspy.utils.BaseCallback):
+ """W&B callback for tracking DSPy evaluation and optimization.
+
+ This callback logs evaluation scores, per-step predictions (optional), and
+ a table capturing the DSPy program signature over time. It can also save
+ the best program as a W&B Artifact for reproducibility.
+
+ Examples:
+ Basic usage within DSPy settings:
+
+ ```python
+ import dspy
+ import wandb
+ from wandb.integration.dspy import WandbDSPyCallback
+
+ with wandb.init(project="dspy-optimization") as run:
+ dspy.settings.callbacks.append(WandbDSPyCallback(run=run))
+ # Run your DSPy optimization/evaluation
+ ```
+ """
+
+ def __init__(self, log_results: bool = True, run: Run | None = None) -> None:
+ """Initialize the callback.
+
+ Args:
+ log_results (bool): Whether to log per-evaluation prediction tables.
+ run (Run | None): Optional W&B run to use. Defaults to the
+ current global run if available.
+
+ Raises:
+ wandb.Error: If no active run is provided or found.
+ """
+ # If no run is provided, use the current global run if available.
+ if run is None:
+ if wandb.run is None:
+ raise wandb.Error(
+ "You must call `wandb.init()` before instantiating WandbDSPyCallback()."
+ )
+ run = wandb.run
+
+ self.log_results = log_results
+
+ with wandb.wandb_lib.telemetry.context(run=run) as tel:
+ tel.feature.dspy_callback = True
+
+ self._run = run
+ self._did_log_config: bool = False
+ self._program_info: dict[str, Any] = {}
+ self._program_table: wandb.Table | None = None
+ self._row_idx: int = 0
+
+ def _flatten_dict(
+ self, nested: Any, parent_key: str = "", sep: str = "."
+ ) -> dict[str, Any]:
+ """Recursively flatten arbitrarily nested mappings and sequences.
+
+ Args:
+ nested (Any): Nested structure of mappings/lists to flatten.
+ parent_key (str): Prefix to prepend to keys in the flattened output.
+ sep (str): Key separator for nested fields.
+
+ Returns:
+ dict[str, Any]: Flattened dictionary representation.
+ """
+ flat: dict[str, Any] = {}
+
+ def _walk(obj: Any, base: str) -> None:
+ if isinstance(obj, Mapping):
+ for k, v in obj.items():
+ new_key = f"{base}{sep}{k}" if base else str(k)
+ _walk(v, new_key)
+ elif isinstance(obj, Sequence) and not isinstance(
+ obj, (str, bytes, bytearray)
+ ):
+ for idx, v in enumerate(obj):
+ new_key = f"{base}{sep}{idx}" if base else str(idx)
+ _walk(v, new_key)
+ else:
+ # Base can be empty only if the top-level is a scalar; guard against that.
+ key = base if base else ""
+ if key:
+ flat[key] = obj
+
+ _walk(nested, parent_key)
+ return flat
+
+ def _extract_fields(self, fields: list[dict[str, Any]]) -> dict[str, str]:
+ """Convert signature fields to a flat mapping of strings.
+
+ Note:
+ The input is expected to be a dict-like mapping from field names to
+ field metadata. Values are stringified for logging.
+
+ Args:
+ fields (list[dict[str, Any]]): Mapping of field name to metadata.
+
+ Returns:
+ dict[str, str]: Mapping of field name to string value.
+ """
+ return {k: str(v) for k, v in fields.items()}
+
+ def _extract_program_info(self, program_obj: Any) -> dict[str, Any]:
+ """Extract signature-related info from a DSPy program.
+
+ Attempts to read the program signature, instructions, input and output
+ fields from a DSPy `Predict` parameter if available.
+
+ Args:
+ program_obj (Any): DSPy program/module instance.
+
+ Returns:
+ dict[str, Any]: Flattened dictionary of signature metadata.
+ """
+ info_dict = {}
+
+ if program_obj is None:
+ return info_dict
+
+ try:
+ sig = next(
+ param.signature
+ for _, param in program_obj.named_parameters()
+ if isinstance(param, dspy.Predict)
+ )
+
+ if getattr(sig, "signature", None):
+ info_dict["signature"] = sig.signature
+ if getattr(sig, "instructions", None):
+ info_dict["instructions"] = sig.instructions
+ if getattr(sig, "input_fields", None):
+ input_fields = sig.input_fields
+ info_dict["input_fields"] = self._extract_fields(input_fields)
+ if getattr(sig, "output_fields", None):
+ output_fields = sig.output_fields
+ info_dict["output_fields"] = self._extract_fields(output_fields)
+
+ return self._flatten_dict(info_dict)
+ except Exception as e:
+ logger.warning(
+ "Failed to extract program info from Evaluate instance: %s", e
+ )
+ return info_dict
+
+ def on_evaluate_start(
+ self,
+ call_id: str,
+ instance: Any,
+ inputs: dict[str, Any],
+ ) -> None:
+ """Handle start of a DSPy evaluation call.
+
+ Logs non-private fields from the evaluator instance to W&B config and
+ captures program signature info for later logging.
+
+ Args:
+ call_id (str): Unique identifier for the evaluation call.
+ instance (Any): The evaluation instance (e.g., `dspy.Evaluate`).
+ inputs (dict[str, Any]): Inputs passed to the evaluation (may
+ include a `program` key with the DSPy program).
+ """
+ if not self._did_log_config:
+ instance_vars = vars(instance) if hasattr(instance, "__dict__") else {}
+ serializable = {
+ k: v for k, v in instance_vars.items() if not k.startswith("_")
+ }
+ if "devset" in serializable:
+ # we don't want to log the devset in the config
+ del serializable["devset"]
+
+ self._run.config.update(serializable)
+ self._did_log_config = True
+
+ # 2) Build/append program signature tables from the 'program' inputs
+ if program_obj := inputs.get("program"):
+ self._program_info = self._extract_program_info(program_obj)
+
+ def on_evaluate_end(
+ self,
+ call_id: str,
+ outputs: Any | None,
+ exception: Exception | None = None,
+ ) -> None:
+ """Handle end of a DSPy evaluation call.
+
+ If available, logs a numeric `score` metric and (optionally) per-step
+ prediction tables. Always appends a row to the program-signature table.
+
+ Args:
+ call_id (str): Unique identifier for the evaluation call.
+ outputs (Any | None): Evaluation outputs; supports
+ `dspy.evaluate.evaluate.EvaluationResult`.
+ exception (Exception | None): Exception raised during evaluation, if any.
+ """
+ # The `BaseCallback` does not define the interface for the `outputs` parameter,
+ # Currently, we know of `EvaluationResult` which is a subclass of `dspy.Prediction`.
+ # We currently support this type and will warn the user if a different type is passed.
+ score: float | None = None
+ if exception is None:
+ if isinstance(outputs, dspy.evaluate.evaluate.EvaluationResult):
+ # log the float score as a wandb metric
+ score = outputs.score
+ wandb.log({"score": float(score)}, step=self._row_idx)
+
+ # Log the predictions as a separate table for each eval end.
+ # We know that results if of type `list[tuple["dspy.Example", "dspy.Example", Any]]`
+ results = outputs.results
+ if self.log_results:
+ rows = self._parse_results(results)
+ if rows:
+ self._log_predictions_table(rows)
+ else:
+ wandb.termwarn(
+ f"on_evaluate_end received unexpected outputs type: {type(outputs)}. "
+ "Expected dspy.evaluate.evaluate.EvaluationResult; skipping logging score and `log_results`."
+ )
+ else:
+ wandb.termwarn(
+ f"on_evaluate_end received exception: {exception}. "
+ "Skipping logging score and `log_results`."
+ )
+
+ # Log the program signature iteratively
+ if self._program_table is None:
+ columns = ["step", *self._program_info.keys()]
+ if isinstance(score, float):
+ columns.append("score")
+ self._program_table = wandb.Table(columns=columns, log_mode="INCREMENTAL")
+
+ if self._program_table is not None:
+ values = list(self._program_info.values())
+ if isinstance(score, float):
+ values.append(score)
+
+ self._program_table.add_data(
+ self._row_idx,
+ *values,
+ )
+ self._run.log(
+ {"program_signature": self._program_table}, step=self._row_idx
+ )
+
+ self._row_idx += 1
+
+ def _parse_results(
+ self,
+ results: list[tuple[dspy.Example, dspy.Prediction | dspy.Completions, bool]],
+ ) -> list[dict[str, Any]]:
+ """Normalize evaluation results into serializable row dicts.
+
+ Args:
+ results (list[tuple]): Sequence of `(example, prediction, is_correct)`
+ tuples from DSPy evaluation.
+
+ Returns:
+ list[dict[str, Any]]: Rows with `example`, `prediction`, `is_correct`.
+ """
+ _rows: list[dict[str, Any]] = []
+ for example, prediction, is_correct in results:
+ if isinstance(prediction, dspy.Prediction):
+ prediction_dict = prediction.toDict()
+ if isinstance(prediction, dspy.Completions):
+ prediction_dict = prediction.items()
+
+ row: dict[str, Any] = {
+ "example": example.toDict(),
+ "prediction": prediction_dict,
+ "is_correct": is_correct,
+ }
+ _rows.append(row)
+
+ return _rows
+
+ def _log_predictions_table(self, rows: list[dict[str, Any]]) -> None:
+ """Log a W&B Table of predictions for the current evaluation step.
+
+ Args:
+ rows (list[dict[str, Any]]): Prediction rows to log.
+ """
+ rows = _flatten_rows(rows)
+ columns = list(rows[0].keys())
+
+ data: list[list[Any]] = [list(row.values()) for row in rows]
+
+ preds_table = wandb.Table(columns=columns, data=data, log_mode="IMMUTABLE")
+ self._run.log({f"predictions_{self._row_idx}": preds_table}, step=self._row_idx)
+
+ def log_best_model(
+ self,
+ model: dspy.Module,
+ *,
+ save_program: bool = True,
+ save_dir: str | None = None,
+ filetype: Literal["json", "pkl"] = "json",
+ aliases: Sequence[str] = ("best", "latest"),
+ artifact_name: str = "dspy-program",
+ ) -> None:
+ """Save and log the best DSPy program as a W&B Artifact.
+
+ You can choose to save the full program (architecture + state) or only
+ the state to a single file (JSON or pickle).
+
+ Args:
+ model (dspy.Module): DSPy module to save.
+ save_program (bool): Save full program directory if True; otherwise
+ save only the state file. Defaults to `True`.
+ save_dir (str): Directory to store program files before logging. Defaults to a
+ subdirectory `dspy_program` within the active run's files directory
+ (i.e., `wandb.run.dir`).
+ filetype (Literal["json", "pkl"]): State file format when
+ `save_program` is False. Defaults to `json`.
+ aliases (Sequence[str]): Aliases for the logged Artifact version. Defaults to `("best", "latest")`.
+ artifact_name (str): Base name for the Artifact. Defaults to `dspy-program`.
+
+ Examples:
+ Save the complete program and add aliases:
+
+ ```python
+ callback.log_best_model(
+ optimized_program, save_program=True, aliases=("best", "production")
+ )
+ ```
+
+ Save only the state as JSON:
+
+ ```python
+ callback.log_best_model(
+ optimized_program, save_program=False, filetype="json"
+ )
+ ```
+ """
+ # Derive metadata to help discoverability in the UI
+ info_dict = self._extract_program_info(model)
+ metadata = {
+ "dspy_version": getattr(dspy, "__version__", "unknown"),
+ "module_class": model.__class__.__name__,
+ **info_dict,
+ }
+ artifact = wandb.Artifact(
+ name=f"{artifact_name}-{self._run.id}",
+ type="model",
+ metadata=metadata,
+ )
+
+ # Resolve and normalize the save directory in a cross-platform way
+ if save_dir is None:
+ save_dir = os.path.join(self._run.dir, "dspy_program")
+ save_dir = os.path.normpath(save_dir)
+
+ try:
+ os.makedirs(save_dir, exist_ok=True)
+ except Exception as exc:
+ wandb.termwarn(
+ f"Could not create or access directory '{save_dir}': {exc}. Skipping artifact logging."
+ )
+ return
+ # Save per requested mode
+ if save_program:
+ model.save(save_dir, save_program=True)
+ artifact.add_dir(save_dir)
+ else:
+ filename = f"program.{filetype}"
+ file_path = os.path.join(save_dir, filename)
+ model.save(file_path, save_program=False)
+ artifact.add_file(file_path)
+
+ self._run.log_artifact(artifact, aliases=list(aliases))
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/fastai/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/fastai/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d12d71d58183b0ce679c2bbb0e4e917fed791e2c
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/fastai/__init__.py
@@ -0,0 +1,243 @@
+"""Hooks that add fast.ai v1 Learners to Weights & Biases through a callback.
+
+Requested logged data can be configured through the callback constructor.
+
+Examples:
+ WandbCallback can be used when initializing the Learner::
+
+ ```
+ from wandb.fastai import WandbCallback
+ [...]
+ learn = Learner(data, ..., callback_fns=WandbCallback)
+ learn.fit(epochs)
+ ```
+
+ Custom parameters can be given using functools.partial::
+
+ ```
+ from wandb.fastai import WandbCallback
+ from functools import partial
+ [...]
+ learn = Learner(data, ..., callback_fns=partial(WandbCallback, ...))
+ learn.fit(epochs)
+ ```
+
+ Finally, it is possible to use WandbCallback only when starting
+ training. In this case it must be instantiated::
+
+ ```
+ learn.fit(..., callbacks=WandbCallback(learn))
+ ```
+
+ or, with custom parameters::
+
+ ```
+ learn.fit(..., callbacks=WandbCallback(learn, ...))
+ ```
+"""
+
+import random
+import sys
+from pathlib import Path
+from typing import Any, Literal, Optional
+
+import fastai
+from fastai.callbacks import TrackerCallback
+
+import wandb
+from wandb.sdk.lib import ipython
+
+try:
+ import matplotlib
+
+ if not ipython.in_jupyter():
+ matplotlib.use("Agg") # non-interactive backend (avoid tkinter issues)
+ import matplotlib.pyplot as plt
+except ImportError:
+ wandb.termwarn("matplotlib required if logging sample image predictions")
+
+
+class WandbCallback(TrackerCallback):
+ """Callback for saving model topology, losses & metrics.
+
+ Optionally logs weights, gradients, sample predictions and best trained model.
+
+ Args:
+ learn (fastai.basic_train.Learner): the fast.ai learner to hook.
+ log (str): "gradients", "parameters", "all", or None. Losses & metrics are always logged.
+ save_model (bool): save model at the end of each epoch. It will also load best model at the end of training.
+ monitor (str): metric to monitor for saving best model. None uses default TrackerCallback monitor value.
+ mode (str): "auto", "min" or "max" to compare "monitor" values and define best model.
+ input_type (str): "images" or None. Used to display sample predictions.
+ validation_data (list): data used for sample predictions if input_type is set.
+ predictions (int): number of predictions to make if input_type is set and validation_data is None.
+ seed (int): initialize random generator for sample predictions if input_type is set and validation_data is None.
+ """
+
+ # Record if watch has been called previously (even in another instance)
+ _watch_called = False
+
+ def __init__(
+ self,
+ learn: "fastai.basic_train.Learner",
+ log: Optional[Literal["gradients", "parameters", "all"]] = "gradients",
+ save_model: bool = True,
+ monitor: Optional[str] = None,
+ mode: Literal["auto", "min", "max"] = "auto",
+ input_type: Optional[Literal["images"]] = None,
+ validation_data: Optional[list] = None,
+ predictions: int = 36,
+ seed: int = 12345,
+ ) -> None:
+ # Check if wandb.init has been called
+ if wandb.run is None:
+ raise ValueError("You must call wandb.init() before WandbCallback()")
+
+ # Adapted from fast.ai "SaveModelCallback"
+ if monitor is None:
+ # use default TrackerCallback monitor value
+ super().__init__(learn, mode=mode)
+ else:
+ super().__init__(learn, monitor=monitor, mode=mode)
+ self.save_model = save_model
+ self.model_path = Path(wandb.run.dir) / "bestmodel.pth"
+
+ self.log = log
+ self.input_type = input_type
+ self.best = None
+
+ # Select items for sample predictions to see evolution along training
+ self.validation_data = validation_data
+ if input_type and not self.validation_data:
+ wandb_random = random.Random(seed) # For repeatability
+ predictions = min(predictions, len(learn.data.valid_ds))
+ indices = wandb_random.sample(range(len(learn.data.valid_ds)), predictions)
+ self.validation_data = [learn.data.valid_ds[i] for i in indices]
+
+ def on_train_begin(self, **kwargs: Any) -> None:
+ """Call watch method to log model topology, gradients & weights."""
+ # Set self.best, method inherited from "TrackerCallback" by "SaveModelCallback"
+ super().on_train_begin()
+
+ # Ensure we don't call "watch" multiple times
+ if not WandbCallback._watch_called:
+ WandbCallback._watch_called = True
+
+ # Logs model topology and optionally gradients and weights
+ wandb.watch(self.learn.model, log=self.log)
+
+ def on_epoch_end(
+ self, epoch: int, smooth_loss: float, last_metrics: list, **kwargs: Any
+ ) -> None:
+ """Log training loss, validation loss and custom metrics & log prediction samples & save model."""
+ if self.save_model:
+ # Adapted from fast.ai "SaveModelCallback"
+ current = self.get_monitor_value()
+ if current is not None and self.operator(current, self.best):
+ wandb.termlog(
+ f"Better model found at epoch {epoch} with {self.monitor} value: {current}."
+ )
+ self.best = current
+
+ # Save within wandb folder
+ with self.model_path.open("wb") as model_file:
+ self.learn.save(model_file)
+
+ # Log sample predictions if learn.predict is available
+ if self.validation_data:
+ try:
+ self._wandb_log_predictions()
+ except FastaiError as e:
+ wandb.termwarn(e.message)
+ self.validation_data = None # prevent from trying again on next loop
+ except Exception as e:
+ wandb.termwarn(f"Unable to log prediction samples.\n{e}")
+ self.validation_data = None # prevent from trying again on next loop
+
+ # Log losses & metrics
+ # Adapted from fast.ai "CSVLogger"
+ logs = {
+ name: stat
+ for name, stat in list(
+ zip(self.learn.recorder.names, [epoch, smooth_loss] + last_metrics)
+ )
+ }
+ wandb.log(logs)
+
+ def on_train_end(self, **kwargs: Any) -> None:
+ """Load the best model."""
+ if self.save_model:
+ # Adapted from fast.ai "SaveModelCallback"
+ if self.model_path.is_file():
+ with self.model_path.open("rb") as model_file:
+ self.learn.load(model_file, purge=False)
+ wandb.termlog(f"Loaded best saved model from {self.model_path}")
+
+ def _wandb_log_predictions(self) -> None:
+ """Log prediction samples."""
+ pred_log = []
+
+ if self.validation_data is None:
+ return
+
+ for x, y in self.validation_data:
+ try:
+ pred = self.learn.predict(x)
+ except Exception:
+ raise FastaiError(
+ 'Unable to run "predict" method from Learner to log prediction samples.'
+ )
+
+ # scalar -> likely to be a category
+ # tensor of dim 1 -> likely to be multicategory
+ if not pred[1].shape or pred[1].dim() == 1:
+ pred_log.append(
+ wandb.Image(
+ x.data,
+ caption=f"Ground Truth: {y}\nPrediction: {pred[0]}",
+ )
+ )
+
+ # most vision datasets have a "show" function we can use
+ elif hasattr(x, "show"):
+ # log input data
+ pred_log.append(wandb.Image(x.data, caption="Input data", grouping=3))
+
+ # log label and prediction
+ for im, capt in ((pred[0], "Prediction"), (y, "Ground Truth")):
+ # Resize plot to image resolution
+ # from https://stackoverflow.com/a/13714915
+ my_dpi = 100
+ fig = plt.figure(frameon=False, dpi=my_dpi)
+ h, w = x.size
+ fig.set_size_inches(w / my_dpi, h / my_dpi)
+ ax = plt.Axes(fig, [0.0, 0.0, 1.0, 1.0])
+ ax.set_axis_off()
+ fig.add_axes(ax)
+
+ # Superpose label or prediction to input image
+ x.show(ax=ax, y=im)
+ pred_log.append(wandb.Image(fig, caption=capt))
+ plt.close(fig)
+
+ # likely to be an image
+ elif hasattr(y, "shape") and (
+ (len(y.shape) == 2) or (len(y.shape) == 3 and y.shape[0] in [1, 3, 4])
+ ):
+ pred_log.extend(
+ [
+ wandb.Image(x.data, caption="Input data", grouping=3),
+ wandb.Image(pred[0].data, caption="Prediction"),
+ wandb.Image(y.data, caption="Ground Truth"),
+ ]
+ )
+
+ # we just log input data
+ else:
+ pred_log.append(wandb.Image(x.data, caption="Input data"))
+
+ wandb.log({"Prediction Samples": pred_log}, commit=False)
+
+
+class FastaiError(wandb.Error):
+ pass
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/gym/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/gym/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0624e4def25ab1e51044221f577066c7939108b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/gym/__init__.py
@@ -0,0 +1,98 @@
+import re
+import sys
+from typing import Literal, Optional
+
+import wandb
+import wandb.util
+
+_gym_version_lt_0_26: Optional[bool] = None
+_gymnasium_version_lt_1_0_0: Optional[bool] = None
+
+_required_error_msg = (
+ "Couldn't import the gymnasium python package, install with `pip install gymnasium`"
+)
+GymLib = Literal["gym", "gymnasium"]
+
+
+def monitor():
+ """Monitor a gym environment.
+
+ Supports both gym and gymnasium.
+ """
+ gym_lib: Optional[GymLib] = None
+
+ # gym is not maintained anymore, gymnasium is the drop-in replacement - prefer it
+ if wandb.util.get_module("gymnasium") is not None:
+ gym_lib = "gymnasium"
+ elif wandb.util.get_module("gym") is not None:
+ gym_lib = "gym"
+
+ if gym_lib is None:
+ raise wandb.Error(_required_error_msg)
+
+ global _gym_version_lt_0_26
+ global _gymnasium_version_lt_1_0_0
+
+ if _gym_version_lt_0_26 is None or _gymnasium_version_lt_1_0_0 is None:
+ if gym_lib == "gym":
+ import gym
+ else:
+ import gymnasium as gym # type: ignore
+
+ from packaging.version import parse
+
+ gym_lib_version = parse(gym.__version__)
+ _gym_version_lt_0_26 = gym_lib_version < parse("0.26.0")
+ _gymnasium_version_lt_1_0_0 = gym_lib_version < parse("1.0.0a1")
+
+ path = "path" # Default path
+ if gym_lib == "gymnasium" and not _gymnasium_version_lt_1_0_0:
+ vcr_recorder_attribute = "RecordVideo"
+ wrappers = wandb.util.get_module(
+ f"{gym_lib}.wrappers",
+ required=_required_error_msg,
+ )
+ recorder = getattr(wrappers, vcr_recorder_attribute)
+ else:
+ vcr = wandb.util.get_module(
+ f"{gym_lib}.wrappers.monitoring.video_recorder",
+ required=_required_error_msg,
+ )
+ # Breaking change in gym 0.26.0
+ if _gym_version_lt_0_26:
+ vcr_recorder_attribute = "ImageEncoder"
+ recorder = getattr(vcr, vcr_recorder_attribute)
+ path = "output_path" # Override path for older gym versions
+ else:
+ vcr_recorder_attribute = "VideoRecorder"
+ recorder = getattr(vcr, vcr_recorder_attribute)
+
+ recorder.orig_close = recorder.close
+
+ def close(self):
+ recorder.orig_close(self)
+ if not self.enabled:
+ return
+ if wandb.run:
+ m = re.match(r".+(video\.\d+).+", getattr(self, path))
+ key = m.group(1) if m else "videos"
+ wandb.log({key: wandb.Video(getattr(self, path))})
+
+ def del_(self):
+ self.orig_close()
+
+ if not _gym_version_lt_0_26:
+ recorder.__del__ = del_
+ recorder.close = close
+
+ if gym_lib == "gymnasium" and not _gymnasium_version_lt_1_0_0:
+ wrapper_name = vcr_recorder_attribute
+ else:
+ wrapper_name = f"monitoring.video_recorder.{vcr_recorder_attribute}"
+
+ wandb.patched["gym"].append(
+ [
+ f"{gym_lib}.wrappers.{wrapper_name}",
+ "close",
+ ]
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/huggingface/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/huggingface/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..943249ebe22686fcbdfaa6708c33e15ec875bccc
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/huggingface/__init__.py
@@ -0,0 +1,3 @@
+__all__ = ("autolog",)
+
+from .huggingface import autolog
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/huggingface/huggingface.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/huggingface/huggingface.py
new file mode 100644
index 0000000000000000000000000000000000000000..d44cf2cbb51d009821e26924ab944a953a1ff866
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/huggingface/huggingface.py
@@ -0,0 +1,18 @@
+import logging
+
+from wandb.sdk.integration_utils.auto_logging import AutologAPI
+
+from .resolver import HuggingFacePipelineRequestResponseResolver
+
+logger = logging.getLogger(__name__)
+
+resolver = HuggingFacePipelineRequestResponseResolver()
+
+autolog = AutologAPI(
+ name="transformers",
+ symbols=("Pipeline.__call__",),
+ resolver=resolver,
+ telemetry_feature="hf_pipeline_autolog",
+)
+
+autolog.get_latest_id = resolver.get_latest_id
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/huggingface/resolver.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/huggingface/resolver.py
new file mode 100644
index 0000000000000000000000000000000000000000..2acbdabe56e5e86c1d4442c99b7e9232d5621a48
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/huggingface/resolver.py
@@ -0,0 +1,213 @@
+import logging
+import os
+from datetime import datetime
+from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
+
+import pytz
+
+import wandb
+from wandb.sdk.integration_utils.auto_logging import Response
+from wandb.sdk.lib.runid import generate_id
+
+logger = logging.getLogger(__name__)
+
+SUPPORTED_PIPELINE_TASKS = [
+ "text-classification",
+ "sentiment-analysis",
+ "question-answering",
+ "summarization",
+ "translation",
+ "text2text-generation",
+ "text-generation",
+ # "conversational",
+]
+
+PIPELINES_WITH_TOP_K = [
+ "text-classification",
+ "sentiment-analysis",
+ "question-answering",
+]
+
+
+class HuggingFacePipelineRequestResponseResolver:
+ """Resolver for HuggingFace's pipeline request and responses, providing necessary data transformations and formatting.
+
+ This is based off (from wandb.sdk.integration_utils.auto_logging import RequestResponseResolver)
+ """
+
+ autolog_id = None
+
+ def __call__(
+ self,
+ args: Sequence[Any],
+ kwargs: Dict[str, Any],
+ response: Response,
+ start_time: float,
+ time_elapsed: float,
+ ) -> Optional[Dict[str, Any]]:
+ """Main call method for this class.
+
+ :param args: list of arguments
+ :param kwargs: dictionary of keyword arguments
+ :param response: the response from the request
+ :param start_time: time when request started
+ :param time_elapsed: time elapsed for the request
+ :returns: packed data as a dictionary for logging to wandb, None if an exception occurred
+ """
+ try:
+ pipe, input_data = args[:2]
+ task = pipe.task
+
+ # Translation tasks are in the form of `translation_x_to_y`
+ if task in SUPPORTED_PIPELINE_TASKS or task.startswith("translation"):
+ model = self._get_model(pipe)
+ if model is None:
+ return None
+ model_alias = model.name_or_path
+ timestamp = datetime.now(pytz.utc)
+
+ input_data, response = self._transform_task_specific_data(
+ task, input_data, response
+ )
+ formatted_data = self._format_data(task, input_data, response, kwargs)
+ packed_data = self._create_table(
+ formatted_data, model_alias, timestamp, time_elapsed
+ )
+ table_name = os.environ.get("WANDB_AUTOLOG_TABLE_NAME", f"{task}")
+ # TODO: Let users decide the name in a way that does not use an environment variable
+
+ return {
+ table_name: wandb.Table(
+ columns=packed_data[0], data=packed_data[1:]
+ )
+ }
+
+ logger.warning(
+ f"The task: `{task}` is not yet supported.\nPlease contact `wandb` to notify us if you would like support for this task"
+ )
+ except Exception as e:
+ logger.warning(e)
+ return None
+
+ # TODO: This should have a dependency on PreTrainedModel. i.e. isinstance(PreTrainedModel)
+ # from transformers.modeling_utils import PreTrainedModel
+ # We do not want this dependency explicitly in our codebase so we make a very general
+ # assumption about the structure of the pipeline which may have unintended consequences
+ def _get_model(self, pipe) -> Optional[Any]:
+ """Extracts model from the pipeline.
+
+ :param pipe: the HuggingFace pipeline
+ :returns: Model if available, None otherwise
+ """
+ model = pipe.model
+ try:
+ return model.model
+ except AttributeError:
+ logger.info(
+ "Model does not have a `.model` attribute. Assuming `pipe.model` is the correct model."
+ )
+ return model
+
+ @staticmethod
+ def _transform_task_specific_data(
+ task: str, input_data: Union[List[Any], Any], response: Union[List[Any], Any]
+ ) -> Tuple[Union[List[Any], Any], Union[List[Any], Any]]:
+ """Transform input and response data based on specific tasks.
+
+ :param task: the task name
+ :param input_data: the input data
+ :param response: the response data
+ :returns: tuple of transformed input_data and response
+ """
+ if task == "question-answering":
+ input_data = input_data if isinstance(input_data, list) else [input_data]
+ input_data = [data.__dict__ for data in input_data]
+ elif task == "conversational":
+ # We only grab the latest input/output pair from the conversation
+ # Logging the whole conversation renders strangely.
+ input_data = input_data if isinstance(input_data, list) else [input_data]
+ input_data = [data.__dict__["past_user_inputs"][-1] for data in input_data]
+
+ response = response if isinstance(response, list) else [response]
+ response = [data.__dict__["generated_responses"][-1] for data in response]
+ return input_data, response
+
+ def _format_data(
+ self,
+ task: str,
+ input_data: Union[List[Any], Any],
+ response: Union[List[Any], Any],
+ kwargs: Dict[str, Any],
+ ) -> List[Dict[str, Any]]:
+ """Formats input data, response, and kwargs into a list of dictionaries.
+
+ :param task: the task name
+ :param input_data: the input data
+ :param response: the response data
+ :param kwargs: dictionary of keyword arguments
+ :returns: list of dictionaries containing formatted data
+ """
+ input_data = input_data if isinstance(input_data, list) else [input_data]
+ response = response if isinstance(response, list) else [response]
+
+ formatted_data = []
+ for i_text, r_text in zip(input_data, response):
+ # Unpack single element responses for better rendering in wandb UI when it is a task without top_k
+ # top_k = 1 would unpack the response into a single element while top_k > 1 would be a list
+ # this would cause the UI to not properly concatenate the tables of the same task by omitting the elements past the first
+ if (
+ (isinstance(r_text, list))
+ and (len(r_text) == 1)
+ and task not in PIPELINES_WITH_TOP_K
+ ):
+ r_text = r_text[0]
+ formatted_data.append(
+ {"input": i_text, "response": r_text, "kwargs": kwargs}
+ )
+ return formatted_data
+
+ def _create_table(
+ self,
+ formatted_data: List[Dict[str, Any]],
+ model_alias: str,
+ timestamp: float,
+ time_elapsed: float,
+ ) -> List[List[Any]]:
+ """Creates a table from formatted data, model alias, timestamp, and elapsed time.
+
+ :param formatted_data: list of dictionaries containing formatted data
+ :param model_alias: alias of the model
+ :param timestamp: timestamp of the data
+ :param time_elapsed: time elapsed from the beginning
+ :returns: list of lists, representing a table of data. [0]th element = columns. [1]st element = data
+ """
+ header = [
+ "ID",
+ "Model Alias",
+ "Timestamp",
+ "Elapsed Time",
+ "Input",
+ "Response",
+ "Kwargs",
+ ]
+ table = [header]
+ autolog_id = generate_id(length=16)
+
+ for data in formatted_data:
+ row = [
+ autolog_id,
+ model_alias,
+ timestamp,
+ time_elapsed,
+ data["input"],
+ data["response"],
+ data["kwargs"],
+ ]
+ table.append(row)
+
+ self.autolog_id = autolog_id
+
+ return table
+
+ def get_latest_id(self):
+ return self.autolog_id
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/keras/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/keras/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8699d6805b92dab3381456270a6449b2078d983b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/keras/__init__.py
@@ -0,0 +1,11 @@
+"""Tools for integrating `wandb` with [`Keras`](https://keras.io/)."""
+
+__all__ = (
+ "WandbCallback",
+ "WandbMetricsLogger",
+ "WandbModelCheckpoint",
+ "WandbEvalCallback",
+)
+
+from .callbacks import WandbEvalCallback, WandbMetricsLogger, WandbModelCheckpoint
+from .keras import WandbCallback # TODO: legacy callback to be deprecated
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/keras/callbacks/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/keras/callbacks/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6035bd4c9c5067e553404a5a4bb818ef582a36a8
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/keras/callbacks/__init__.py
@@ -0,0 +1,5 @@
+__all__ = ("WandbMetricsLogger", "WandbModelCheckpoint", "WandbEvalCallback")
+
+from .metrics_logger import WandbMetricsLogger
+from .model_checkpoint import WandbModelCheckpoint
+from .tables_builder import WandbEvalCallback
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/keras/callbacks/metrics_logger.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/keras/callbacks/metrics_logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..b51f5bfd7af7a134268529d617fd68daf5adcce9
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/keras/callbacks/metrics_logger.py
@@ -0,0 +1,129 @@
+from typing import Any, Dict, Literal, Optional, Union
+
+import tensorflow as tf # type: ignore
+from tensorflow.keras import callbacks
+
+import wandb
+from wandb.integration.keras.keras import patch_tf_keras
+from wandb.sdk.lib import telemetry
+
+LogStrategy = Literal["epoch", "batch"]
+
+
+patch_tf_keras()
+
+
+class WandbMetricsLogger(callbacks.Callback):
+ """Logger that sends system metrics to W&B.
+
+ `WandbMetricsLogger` automatically logs the `logs` dictionary that callback methods
+ take as argument to wandb.
+
+ This callback automatically logs the following to a W&B run page:
+ * system (CPU/GPU/TPU) metrics,
+ * train and validation metrics defined in `model.compile`,
+ * learning rate (both for a fixed value or a learning rate scheduler)
+
+ Notes:
+ If you resume training by passing `initial_epoch` to `model.fit` and you are using a
+ learning rate scheduler, make sure to pass `initial_global_step` to
+ `WandbMetricsLogger`. The `initial_global_step` is `step_size * initial_step`, where
+ `step_size` is number of training steps per epoch. `step_size` can be calculated as
+ the product of the cardinality of the training dataset and the batch size.
+
+ Args:
+ log_freq: ("epoch", "batch", or int) if "epoch", logs metrics
+ at the end of each epoch. If "batch", logs metrics at the end
+ of each batch. If an integer, logs metrics at the end of that
+ many batches. Defaults to "epoch".
+ initial_global_step: (int) Use this argument to correctly log the
+ learning rate when you resume training from some `initial_epoch`,
+ and a learning rate scheduler is used. This can be computed as
+ `step_size * initial_step`. Defaults to 0.
+ """
+
+ def __init__(
+ self,
+ log_freq: Union[LogStrategy, int] = "epoch",
+ initial_global_step: int = 0,
+ *args: Any,
+ **kwargs: Any,
+ ) -> None:
+ super().__init__(*args, **kwargs)
+
+ if wandb.run is None:
+ raise wandb.Error(
+ "You must call `wandb.init()` before WandbMetricsLogger()"
+ )
+
+ with telemetry.context(run=wandb.run) as tel:
+ tel.feature.keras_metrics_logger = True
+
+ if log_freq == "batch":
+ log_freq = 1
+
+ self.logging_batch_wise = isinstance(log_freq, int)
+ self.log_freq: Any = log_freq if self.logging_batch_wise else None
+ self.global_batch = 0
+ self.global_step = initial_global_step
+
+ if self.logging_batch_wise:
+ # define custom x-axis for batch logging.
+ wandb.define_metric("batch/batch_step")
+ # set all batch metrics to be logged against batch_step.
+ wandb.define_metric("batch/*", step_metric="batch/batch_step")
+ else:
+ # define custom x-axis for epoch-wise logging.
+ wandb.define_metric("epoch/epoch")
+ # set all epoch-wise metrics to be logged against epoch.
+ wandb.define_metric("epoch/*", step_metric="epoch/epoch")
+
+ def _get_lr(self) -> Union[float, None]:
+ if isinstance(
+ self.model.optimizer.learning_rate,
+ (tf.Variable, tf.Tensor),
+ ) or (
+ hasattr(self.model.optimizer.learning_rate, "shape")
+ and self.model.optimizer.learning_rate.shape == ()
+ ):
+ return float(self.model.optimizer.learning_rate.numpy().item())
+ try:
+ return float(
+ self.model.optimizer.learning_rate(step=self.global_step).numpy().item()
+ )
+ except Exception as e:
+ wandb.termerror(f"Unable to log learning rate: {e}", repeat=False)
+ return None
+
+ def on_epoch_end(self, epoch: int, logs: Optional[Dict[str, Any]] = None) -> None:
+ """Called at the end of an epoch."""
+ logs = dict() if logs is None else {f"epoch/{k}": v for k, v in logs.items()}
+
+ logs["epoch/epoch"] = epoch
+
+ lr = self._get_lr()
+ if lr is not None:
+ logs["epoch/learning_rate"] = lr
+
+ wandb.log(logs)
+
+ def on_batch_end(self, batch: int, logs: Optional[Dict[str, Any]] = None) -> None:
+ self.global_step += 1
+ """An alias for `on_train_batch_end` for backwards compatibility."""
+ if self.logging_batch_wise and batch % self.log_freq == 0:
+ logs = {f"batch/{k}": v for k, v in logs.items()} if logs else {}
+ logs["batch/batch_step"] = self.global_batch
+
+ lr = self._get_lr()
+ if lr is not None:
+ logs["batch/learning_rate"] = lr
+
+ wandb.log(logs)
+
+ self.global_batch += self.log_freq
+
+ def on_train_batch_end(
+ self, batch: int, logs: Optional[Dict[str, Any]] = None
+ ) -> None:
+ """Called at the end of a training batch in `fit` methods."""
+ self.on_batch_end(batch, logs if logs else {})
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/keras/callbacks/model_checkpoint.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/keras/callbacks/model_checkpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..9990b4ffd19ad40d4f1204d5c6bc133c352c0835
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/keras/callbacks/model_checkpoint.py
@@ -0,0 +1,188 @@
+import os
+import string
+from typing import Any, Dict, List, Literal, Optional, Union
+
+import tensorflow as tf # type: ignore
+from tensorflow.keras import callbacks # type: ignore
+
+import wandb
+from wandb.sdk.lib import telemetry
+from wandb.sdk.lib.paths import StrPath
+
+from ..keras import patch_tf_keras
+
+Mode = Literal["auto", "min", "max"]
+SaveStrategy = Literal["epoch"]
+
+patch_tf_keras()
+
+
+class WandbModelCheckpoint(callbacks.ModelCheckpoint):
+ """A checkpoint that periodically saves a Keras model or model weights.
+
+ Saved weights are uploaded to W&B as a `wandb.Artifact`.
+
+ Since this callback is subclassed from `tf.keras.callbacks.ModelCheckpoint`, the
+ checkpointing logic is taken care of by the parent callback. You can learn more
+ here: https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/ModelCheckpoint
+
+ This callback is to be used in conjunction with training using `model.fit()` to save
+ a model or weights (in a checkpoint file) at some interval. The model checkpoints
+ will be logged as W&B Artifacts. You can learn more here:
+ https://docs.wandb.ai/guides/artifacts
+
+ This callback provides the following features:
+ - Save the model that has achieved "best performance" based on "monitor".
+ - Save the model at the end of every epoch regardless of the performance.
+ - Save the model at the end of epoch or after a fixed number of training batches.
+ - Save only model weights, or save the whole model.
+ - Save the model either in SavedModel format or in `.h5` format.
+
+ Args:
+ filepath: (Union[str, os.PathLike]) path to save the model file. `filepath`
+ can contain named formatting options, which will be filled by the value
+ of `epoch` and keys in `logs` (passed in `on_epoch_end`). For example:
+ if `filepath` is `model-{epoch:02d}-{val_loss:.2f}`, then the
+ model checkpoints will be saved with the epoch number and the
+ validation loss in the filename.
+ monitor: (str) The metric name to monitor. Default to "val_loss".
+ verbose: (int) Verbosity mode, 0 or 1. Mode 0 is silent, and mode 1
+ displays messages when the callback takes an action.
+ save_best_only: (bool) if `save_best_only=True`, it only saves when the model
+ is considered the "best" and the latest best model according to the
+ quantity monitored will not be overwritten. If `filepath` doesn't contain
+ formatting options like `{epoch}` then `filepath` will be overwritten by
+ each new better model locally. The model logged as an artifact will still be
+ associated with the correct `monitor`. Artifacts will be uploaded
+ continuously and versioned separately as a new best model is found.
+ save_weights_only: (bool) if True, then only the model's weights will be saved.
+ mode: (Mode) one of {'auto', 'min', 'max'}. For `val_acc`, this should be `max`,
+ for `val_loss` this should be `min`, etc.
+ save_freq: (Union[SaveStrategy, int]) `epoch` or integer. When using `'epoch'`,
+ the callback saves the model after each epoch. When using an integer, the
+ callback saves the model at end of this many batches.
+ Note that when monitoring validation metrics such as `val_acc` or `val_loss`,
+ save_freq must be set to "epoch" as those metrics are only available at the
+ end of an epoch.
+ initial_value_threshold: (Optional[float]) Floating point initial "best" value of the metric
+ to be monitored.
+ """
+
+ def __init__(
+ self,
+ filepath: StrPath,
+ monitor: str = "val_loss",
+ verbose: int = 0,
+ save_best_only: bool = False,
+ save_weights_only: bool = False,
+ mode: Mode = "auto",
+ save_freq: Union[SaveStrategy, int] = "epoch",
+ initial_value_threshold: Optional[float] = None,
+ **kwargs: Any,
+ ) -> None:
+ super().__init__(
+ filepath=filepath,
+ monitor=monitor,
+ verbose=verbose,
+ save_best_only=save_best_only,
+ save_weights_only=save_weights_only,
+ mode=mode,
+ save_freq=save_freq,
+ initial_value_threshold=initial_value_threshold,
+ **kwargs,
+ )
+ if wandb.run is None:
+ raise wandb.Error(
+ "You must call `wandb.init()` before `WandbModelCheckpoint()`"
+ )
+ with telemetry.context(run=wandb.run) as tel:
+ tel.feature.keras_model_checkpoint = True
+
+ self.save_weights_only = save_weights_only
+
+ # User-friendly warning when trying to save the best model.
+ if self.save_best_only:
+ self._check_filepath()
+
+ self._is_old_tf_keras_version: Optional[bool] = None
+
+ def on_train_batch_end(
+ self, batch: int, logs: Optional[Dict[str, float]] = None
+ ) -> None:
+ if self._should_save_on_batch(batch):
+ if self.is_old_tf_keras_version:
+ # Save the model and get filepath
+ self._save_model(epoch=self._current_epoch, logs=logs)
+ filepath = self._get_file_path(epoch=self._current_epoch, logs=logs)
+ else:
+ # Save the model and get filepath
+ self._save_model(epoch=self._current_epoch, batch=batch, logs=logs)
+ filepath = self._get_file_path(
+ epoch=self._current_epoch, batch=batch, logs=logs
+ )
+ # Log the model as artifact
+ aliases = ["latest", f"epoch_{self._current_epoch}_batch_{batch}"]
+ self._log_ckpt_as_artifact(filepath, aliases=aliases)
+
+ def on_epoch_end(self, epoch: int, logs: Optional[Dict[str, float]] = None) -> None:
+ super().on_epoch_end(epoch, logs)
+ # Check if model checkpoint is created at the end of epoch.
+ if self.save_freq == "epoch":
+ # Get filepath where the model checkpoint is saved.
+ if self.is_old_tf_keras_version:
+ filepath = self._get_file_path(epoch=epoch, logs=logs)
+ else:
+ filepath = self._get_file_path(epoch=epoch, batch=None, logs=logs)
+ # Log the model as artifact
+ aliases = ["latest", f"epoch_{epoch}"]
+ self._log_ckpt_as_artifact(filepath, aliases=aliases)
+
+ def _log_ckpt_as_artifact(
+ self, filepath: str, aliases: Optional[List[str]] = None
+ ) -> None:
+ """Log model checkpoint as W&B Artifact."""
+ try:
+ assert wandb.run is not None
+ model_checkpoint_artifact = wandb.Artifact(
+ f"run_{wandb.run.id}_model", type="model"
+ )
+ if os.path.isfile(filepath):
+ model_checkpoint_artifact.add_file(filepath)
+ elif os.path.isdir(filepath):
+ model_checkpoint_artifact.add_dir(filepath)
+ else:
+ raise FileNotFoundError(f"No such file or directory {filepath}")
+ wandb.log_artifact(model_checkpoint_artifact, aliases=aliases or [])
+ except ValueError:
+ # This error occurs when `save_best_only=True` and the model
+ # checkpoint is not saved for that epoch/batch. Since TF/Keras
+ # is giving friendly log, we can avoid clustering the stdout.
+ pass
+
+ def _check_filepath(self) -> None:
+ placeholders = []
+ for tup in string.Formatter().parse(self.filepath):
+ if tup[1] is not None:
+ placeholders.append(tup[1])
+ if len(placeholders) == 0:
+ wandb.termwarn(
+ "When using `save_best_only`, ensure that the `filepath` argument "
+ "contains formatting placeholders like `{epoch:02d}` or `{batch:02d}`. "
+ "This ensures correct interpretation of the logged artifacts.",
+ repeat=False,
+ )
+
+ @property
+ def is_old_tf_keras_version(self) -> Optional[bool]:
+ if self._is_old_tf_keras_version is None:
+ from packaging.version import parse
+
+ try:
+ if parse(tf.keras.__version__) < parse("2.6.0"):
+ self._is_old_tf_keras_version = True
+ else:
+ self._is_old_tf_keras_version = False
+ except AttributeError:
+ self._is_old_tf_keras_version = False
+
+ return self._is_old_tf_keras_version
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/keras/callbacks/tables_builder.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/keras/callbacks/tables_builder.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd19bfb314f4c06c703858aed6fe47ca12bbcefc
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/keras/callbacks/tables_builder.py
@@ -0,0 +1,228 @@
+import abc
+from typing import Any, Dict, List, Optional
+
+from tensorflow.keras.callbacks import Callback # type: ignore
+
+import wandb
+from wandb.sdk.lib import telemetry
+
+
+class WandbEvalCallback(Callback, abc.ABC):
+ """Abstract base class to build Keras callbacks for model prediction visualization.
+
+ You can build callbacks for visualizing model predictions `on_epoch_end`
+ that can be passed to `model.fit()` for classification, object detection,
+ segmentation, etc. tasks.
+
+ To use this, inherit from this base callback class and implement the
+ `add_ground_truth` and `add_model_prediction` methods.
+
+ The base class will take care of the following:
+ - Initialize `data_table` for logging the ground truth and
+ `pred_table` for predictions.
+ - The data uploaded to `data_table` is used as a reference for the
+ `pred_table`. This is to reduce the memory footprint. The `data_table_ref`
+ is a list that can be used to access the referenced data.
+ Check out the example below to see how it's done.
+ - Log the tables to W&B as W&B Artifacts.
+ - Each new `pred_table` is logged as a new version with aliases.
+
+ Example:
+ ```python
+ class WandbClfEvalCallback(WandbEvalCallback):
+ def __init__(self, validation_data, data_table_columns, pred_table_columns):
+ super().__init__(data_table_columns, pred_table_columns)
+
+ self.x = validation_data[0]
+ self.y = validation_data[1]
+
+ def add_ground_truth(self):
+ for idx, (image, label) in enumerate(zip(self.x, self.y)):
+ self.data_table.add_data(idx, wandb.Image(image), label)
+
+ def add_model_predictions(self, epoch):
+ preds = self.model.predict(self.x, verbose=0)
+ preds = tf.argmax(preds, axis=-1)
+
+ data_table_ref = self.data_table_ref
+ table_idxs = data_table_ref.get_index()
+
+ for idx in table_idxs:
+ pred = preds[idx]
+ self.pred_table.add_data(
+ epoch,
+ data_table_ref.data[idx][0],
+ data_table_ref.data[idx][1],
+ data_table_ref.data[idx][2],
+ pred,
+ )
+
+
+ model.fit(
+ x,
+ y,
+ epochs=2,
+ validation_data=(x, y),
+ callbacks=[
+ WandbClfEvalCallback(
+ validation_data=(x, y),
+ data_table_columns=["idx", "image", "label"],
+ pred_table_columns=["epoch", "idx", "image", "label", "pred"],
+ )
+ ],
+ )
+ ```
+
+ To have more fine-grained control, you can override the `on_train_begin` and
+ `on_epoch_end` methods. If you want to log the samples after N batched, you
+ can implement `on_train_batch_end` method.
+ """
+
+ def __init__(
+ self,
+ data_table_columns: List[str],
+ pred_table_columns: List[str],
+ *args: Any,
+ **kwargs: Any,
+ ) -> None:
+ super().__init__(*args, **kwargs)
+
+ if wandb.run is None:
+ raise wandb.Error(
+ "You must call `wandb.init()` first before using this callback."
+ )
+
+ with telemetry.context(run=wandb.run) as tel:
+ tel.feature.keras_wandb_eval_callback = True
+
+ self.data_table_columns = data_table_columns
+ self.pred_table_columns = pred_table_columns
+
+ def on_train_begin(self, logs: Optional[Dict[str, float]] = None) -> None:
+ # Initialize the data_table
+ self.init_data_table(column_names=self.data_table_columns)
+ # Log the ground truth data
+ self.add_ground_truth(logs)
+ # Log the data_table as W&B Artifacts
+ self.log_data_table()
+
+ def on_epoch_end(self, epoch: int, logs: Optional[Dict[str, float]] = None) -> None:
+ # Initialize the pred_table
+ self.init_pred_table(column_names=self.pred_table_columns)
+ # Log the model prediction
+ self.add_model_predictions(epoch, logs)
+ # Log the pred_table as W&B Artifacts
+ self.log_pred_table()
+
+ @abc.abstractmethod
+ def add_ground_truth(self, logs: Optional[Dict[str, float]] = None) -> None:
+ """Add ground truth data to `data_table`.
+
+ Use this method to write the logic for adding validation/training data to
+ `data_table` initialized using `init_data_table` method.
+
+ Example:
+ ```python
+ for idx, data in enumerate(dataloader):
+ self.data_table.add_data(idx, data)
+ ```
+ This method is called once `on_train_begin` or equivalent hook.
+ """
+ raise NotImplementedError(f"{self.__class__.__name__}.add_ground_truth")
+
+ @abc.abstractmethod
+ def add_model_predictions(
+ self, epoch: int, logs: Optional[Dict[str, float]] = None
+ ) -> None:
+ """Add a prediction from a model to `pred_table`.
+
+ Use this method to write the logic for adding model prediction for validation/
+ training data to `pred_table` initialized using `init_pred_table` method.
+
+ Example:
+ ```python
+ # Assuming the dataloader is not shuffling the samples.
+ for idx, data in enumerate(dataloader):
+ preds = model.predict(data)
+ self.pred_table.add_data(
+ self.data_table_ref.data[idx][0],
+ self.data_table_ref.data[idx][1],
+ preds,
+ )
+ ```
+ This method is called `on_epoch_end` or equivalent hook.
+ """
+ raise NotImplementedError(f"{self.__class__.__name__}.add_model_predictions")
+
+ def init_data_table(self, column_names: List[str]) -> None:
+ """Initialize the W&B Tables for validation data.
+
+ Call this method `on_train_begin` or equivalent hook. This is followed by adding
+ data to the table row or column wise.
+
+ Args:
+ column_names: (list) Column names for W&B Tables.
+ """
+ self.data_table = wandb.Table(columns=column_names, allow_mixed_types=True)
+
+ def init_pred_table(self, column_names: List[str]) -> None:
+ """Initialize the W&B Tables for model evaluation.
+
+ Call this method `on_epoch_end` or equivalent hook. This is followed by adding
+ data to the table row or column wise.
+
+ Args:
+ column_names: (list) Column names for W&B Tables.
+ """
+ self.pred_table = wandb.Table(columns=column_names)
+
+ def log_data_table(
+ self, name: str = "val", type: str = "dataset", table_name: str = "val_data"
+ ) -> None:
+ """Log the `data_table` as W&B artifact and call `use_artifact` on it.
+
+ This lets the evaluation table use the reference of already uploaded data
+ (images, text, scalar, etc.) without re-uploading.
+
+ Args:
+ name: (str) A human-readable name for this artifact, which is how you can
+ identify this artifact in the UI or reference it in use_artifact calls.
+ (default is 'val')
+ type: (str) The type of the artifact, which is used to organize and
+ differentiate artifacts. (default is 'dataset')
+ table_name: (str) The name of the table as will be displayed in the UI.
+ (default is 'val_data').
+ """
+ data_artifact = wandb.Artifact(name, type=type)
+ data_artifact.add(self.data_table, table_name)
+
+ # Calling `use_artifact` uploads the data to W&B.
+ assert wandb.run is not None
+ wandb.run.use_artifact(data_artifact)
+ data_artifact.wait()
+
+ # We get the reference table.
+ self.data_table_ref = data_artifact.get(table_name)
+
+ def log_pred_table(
+ self,
+ type: str = "evaluation",
+ table_name: str = "eval_data",
+ aliases: Optional[List[str]] = None,
+ ) -> None:
+ """Log the W&B Tables for model evaluation.
+
+ The table will be logged multiple times creating new version. Use this
+ to compare models at different intervals interactively.
+
+ Args:
+ type: (str) The type of the artifact, which is used to organize and
+ differentiate artifacts. (default is 'evaluation')
+ table_name: (str) The name of the table as will be displayed in the UI.
+ (default is 'eval_data')
+ aliases: (List[str]) List of aliases for the prediction table.
+ """
+ assert wandb.run is not None
+ pred_artifact = wandb.Artifact(f"run_{wandb.run.id}_pred", type=type)
+ pred_artifact.add(self.pred_table, table_name)
+ wandb.run.log_artifact(pred_artifact, aliases=aliases or ["latest"])
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/keras/keras.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/keras/keras.py
new file mode 100644
index 0000000000000000000000000000000000000000..3dde8f71ed6a64c24790704ad4f3bf97e83ddd83
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/keras/keras.py
@@ -0,0 +1,1086 @@
+"""keras init."""
+
+import logging
+import operator
+import os
+import shutil
+import sys
+from itertools import chain
+
+import numpy as np
+import tensorflow as tf
+import tensorflow.keras.backend as K # noqa: N812
+
+import wandb
+from wandb.proto.wandb_deprecated import Deprecated
+from wandb.sdk.integration_utils.data_logging import ValidationDataLogger
+from wandb.sdk.lib.deprecate import deprecate
+from wandb.util import add_import_hook
+
+
+def _check_keras_version():
+ from keras import __version__ as keras_version
+ from packaging.version import parse
+
+ if parse(keras_version) < parse("2.4.0"):
+ wandb.termwarn(
+ f"Keras version {keras_version} is not fully supported. Required keras >= 2.4.0"
+ )
+
+
+def _can_compute_flops() -> bool:
+ """FLOPS computation is restricted to TF 2.x as it requires tf.compat.v1."""
+ from packaging.version import parse
+
+ if parse(tf.__version__) >= parse("2.0.0"):
+ return True
+
+ return False
+
+
+if "keras" in sys.modules:
+ _check_keras_version()
+else:
+ add_import_hook("keras", _check_keras_version)
+
+
+logger = logging.getLogger(__name__)
+
+
+def is_dataset(data):
+ dataset_ops = wandb.util.get_module("tensorflow.python.data.ops.dataset_ops")
+ if dataset_ops and hasattr(dataset_ops, "DatasetV2"):
+ dataset_types = (dataset_ops.DatasetV2,)
+ if hasattr(dataset_ops, "DatasetV1"):
+ dataset_types = dataset_types + (dataset_ops.DatasetV1,)
+ return isinstance(data, dataset_types)
+ else:
+ return False
+
+
+def is_generator_like(data):
+ # Checks if data is a generator, Sequence, or Iterator.
+
+ types = (tf.keras.utils.Sequence,)
+ iterator_ops = wandb.util.get_module("tensorflow.python.data.ops.iterator_ops")
+ if iterator_ops:
+ types = types + (iterator_ops.Iterator,)
+ # EagerIterator was in tensorflow < 2
+ if hasattr(iterator_ops, "EagerIterator"):
+ types = types + (iterator_ops.EagerIterator,)
+ elif hasattr(iterator_ops, "IteratorV2"):
+ types = types + (iterator_ops.IteratorV2,)
+ return hasattr(data, "next") or hasattr(data, "__next__") or isinstance(data, types)
+
+
+def patch_tf_keras(): # noqa: C901
+ from packaging.version import parse
+ from tensorflow.python.eager import context
+
+ if parse("2.6.0") <= parse(tf.__version__) < parse("2.13.0"):
+ keras_engine = "keras.engine"
+ try:
+ from keras.engine import training
+ from keras.engine import training_arrays_v1 as training_arrays
+ from keras.engine import training_generator_v1 as training_generator
+ except (ImportError, AttributeError):
+ wandb.termerror("Unable to patch Tensorflow/Keras")
+ logger.exception("exception while trying to patch_tf_keras")
+ return
+ else:
+ keras_engine = "tensorflow.python.keras.engine"
+
+ from tensorflow.python.keras.engine import training
+
+ try:
+ from tensorflow.python.keras.engine import (
+ training_arrays_v1 as training_arrays,
+ )
+ from tensorflow.python.keras.engine import (
+ training_generator_v1 as training_generator,
+ )
+ except (ImportError, AttributeError):
+ try:
+ from tensorflow.python.keras.engine import (
+ training_arrays,
+ training_generator,
+ )
+ except (ImportError, AttributeError):
+ wandb.termerror("Unable to patch Tensorflow/Keras")
+ logger.exception("exception while trying to patch_tf_keras")
+ return
+
+ # Tensorflow 2.1
+ training_v2_1 = wandb.util.get_module("tensorflow.python.keras.engine.training_v2")
+ # Tensorflow 2.2
+ training_v2_2 = wandb.util.get_module(f"{keras_engine}.training_v1")
+
+ if training_v2_1:
+ old_v2 = training_v2_1.Loop.fit
+ elif training_v2_2:
+ old_v2 = training.Model.fit
+
+ old_arrays = training_arrays.fit_loop
+ old_generator = training_generator.fit_generator
+
+ def set_wandb_attrs(cbk, val_data):
+ if isinstance(cbk, WandbCallback):
+ if is_generator_like(val_data):
+ cbk.generator = val_data
+ elif is_dataset(val_data):
+ if context.executing_eagerly():
+ cbk.generator = iter(val_data)
+ else:
+ wandb.termwarn(
+ "Found a validation dataset in graph mode, can't patch Keras."
+ )
+ elif isinstance(val_data, tuple) and isinstance(val_data[0], tf.Tensor):
+ # Graph mode dataset generator
+ def gen():
+ while True:
+ yield K.get_session().run(val_data)
+
+ cbk.generator = gen()
+ else:
+ cbk.validation_data = val_data
+
+ def new_arrays(*args, **kwargs):
+ cbks = kwargs.get("callbacks", [])
+ val_inputs = kwargs.get("val_inputs")
+ val_targets = kwargs.get("val_targets")
+ # TODO: these could be generators, why index 0?
+ if val_inputs and val_targets:
+ for cbk in cbks:
+ set_wandb_attrs(cbk, (val_inputs[0], val_targets[0]))
+ return old_arrays(*args, **kwargs)
+
+ def new_generator(*args, **kwargs):
+ cbks = kwargs.get("callbacks", [])
+ val_data = kwargs.get("validation_data")
+ if val_data:
+ for cbk in cbks:
+ set_wandb_attrs(cbk, val_data)
+ return old_generator(*args, **kwargs)
+
+ def new_v2(*args, **kwargs):
+ cbks = kwargs.get("callbacks", [])
+ val_data = kwargs.get("validation_data")
+ if val_data:
+ for cbk in cbks:
+ set_wandb_attrs(cbk, val_data)
+ return old_v2(*args, **kwargs)
+
+ training_arrays.orig_fit_loop = old_arrays
+ training_arrays.fit_loop = new_arrays
+ training_generator.orig_fit_generator = old_generator
+ training_generator.fit_generator = new_generator
+ wandb.patched["keras"].append([f"{keras_engine}.training_arrays", "fit_loop"])
+ wandb.patched["keras"].append(
+ [f"{keras_engine}.training_generator", "fit_generator"]
+ )
+
+ if training_v2_1:
+ training_v2_1.Loop.fit = new_v2
+ wandb.patched["keras"].append(
+ ["tensorflow.python.keras.engine.training_v2.Loop", "fit"]
+ )
+ elif training_v2_2:
+ training.Model.fit = new_v2
+ wandb.patched["keras"].append([f"{keras_engine}.training.Model", "fit"])
+
+
+def _array_has_dtype(array):
+ return hasattr(array, "dtype")
+
+
+def _update_if_numeric(metrics, key, values):
+ if not _array_has_dtype(values):
+ _warn_not_logging(key)
+ return
+
+ if not is_numeric_array(values):
+ _warn_not_logging_non_numeric(key)
+ return
+
+ metrics[key] = wandb.Histogram(values)
+
+
+def is_numeric_array(array):
+ return np.issubdtype(array.dtype, np.number)
+
+
+def _warn_not_logging_non_numeric(name):
+ wandb.termwarn(
+ f"Non-numeric values found in layer: {name}, not logging this layer",
+ repeat=False,
+ )
+
+
+def _warn_not_logging(name):
+ wandb.termwarn(
+ f"Layer {name} has undetermined datatype not logging this layer",
+ repeat=False,
+ )
+
+
+tf_logger = tf.get_logger()
+
+patch_tf_keras()
+
+
+### For gradient logging ###
+
+
+def _get_custom_optimizer_parent_class():
+ from packaging.version import parse
+
+ if parse(tf.__version__) >= parse("2.9.0"):
+ custom_optimizer_parent_class = tf.keras.optimizers.legacy.Optimizer
+ else:
+ custom_optimizer_parent_class = tf.keras.optimizers.Optimizer
+
+ return custom_optimizer_parent_class
+
+
+_custom_optimizer_parent_class = _get_custom_optimizer_parent_class()
+
+
+class _CustomOptimizer(_custom_optimizer_parent_class):
+ def __init__(self):
+ super().__init__(name="CustomOptimizer")
+ self._resource_apply_dense = tf.function(self._resource_apply_dense)
+ self._resource_apply_sparse = tf.function(self._resource_apply_sparse)
+
+ def _resource_apply_dense(self, grad, var):
+ var.assign(grad)
+
+ # this needs to be implemented to prevent a NotImplementedError when
+ # using Lookup layers.
+ def _resource_apply_sparse(self, grad, var, indices):
+ pass
+
+ def get_config(self):
+ return super().get_config()
+
+
+class _GradAccumulatorCallback(tf.keras.callbacks.Callback):
+ """Accumulates gradients during a fit() call when used in conjunction with the CustomOptimizer above."""
+
+ def set_model(self, model):
+ super().set_model(model)
+ self.og_weights = model.get_weights()
+ self.grads = [np.zeros(tuple(w.shape)) for w in model.trainable_weights]
+
+ def on_batch_end(self, batch, logs=None):
+ for g, w in zip(self.grads, self.model.trainable_weights):
+ g += w.numpy()
+ self.model.set_weights(self.og_weights)
+
+ def get_grads(self):
+ return [g.copy() for g in self.grads]
+
+
+###
+
+
+class WandbCallback(tf.keras.callbacks.Callback):
+ """`WandbCallback` automatically integrates keras with wandb.
+
+ Example:
+ ```python
+ model.fit(
+ X_train,
+ y_train,
+ validation_data=(X_test, y_test),
+ callbacks=[WandbCallback()],
+ )
+ ```
+
+ `WandbCallback` will automatically log history data from any
+ metrics collected by keras: loss and anything passed into `keras_model.compile()`.
+
+ `WandbCallback` will set summary metrics for the run associated with the "best" training
+ step, where "best" is defined by the `monitor` and `mode` attributes. This defaults
+ to the epoch with the minimum `val_loss`. `WandbCallback` will by default save the model
+ associated with the best `epoch`.
+
+ `WandbCallback` can optionally log gradient and parameter histograms.
+
+ `WandbCallback` can optionally save training and validation data for wandb to visualize.
+
+ Args:
+ monitor: (str) name of metric to monitor. Defaults to `val_loss`.
+ mode: (str) one of {`auto`, `min`, `max`}.
+ `min` - save model when monitor is minimized
+ `max` - save model when monitor is maximized
+ `auto` - try to guess when to save the model (default).
+ save_model:
+ True - save a model when monitor beats all previous epochs
+ False - don't save models
+ save_graph: (boolean) if True save model graph to wandb (default to True).
+ save_weights_only: (boolean) if True, then only the model's weights will be
+ saved (`model.save_weights(filepath)`), else the full model
+ is saved (`model.save(filepath)`).
+ log_weights: (boolean) if True save histograms of the model's layer's weights.
+ log_gradients: (boolean) if True log histograms of the training gradients
+ training_data: (tuple) Same format `(X,y)` as passed to `model.fit`. This is needed
+ for calculating gradients - this is mandatory if `log_gradients` is `True`.
+ validation_data: (tuple) Same format `(X,y)` as passed to `model.fit`. A set of data
+ for wandb to visualize. If this is set, every epoch, wandb will
+ make a small number of predictions and save the results for later visualization. In case
+ you are working with image data, please also set `input_type` and `output_type` in order
+ to log correctly.
+ generator: (generator) a generator that returns validation data for wandb to visualize. This
+ generator should return tuples `(X,y)`. Either `validate_data` or generator should
+ be set for wandb to visualize specific data examples. In case you are working with image data,
+ please also set `input_type` and `output_type` in order to log correctly.
+ validation_steps: (int) if `validation_data` is a generator, how many
+ steps to run the generator for the full validation set.
+ labels: (list) If you are visualizing your data with wandb this list of labels
+ will convert numeric output to understandable string if you are building a
+ multiclass classifier. If you are making a binary classifier you can pass in
+ a list of two labels ["label for false", "label for true"]. If `validate_data`
+ and generator are both false, this won't do anything.
+ predictions: (int) the number of predictions to make for visualization each epoch, max
+ is 100.
+ input_type: (string) type of the model input to help visualization. can be one of:
+ (`image`, `images`, `segmentation_mask`, `auto`).
+ output_type: (string) type of the model output to help visualization. can be one of:
+ (`image`, `images`, `segmentation_mask`, `label`).
+ log_evaluation: (boolean) if True, save a Table containing validation data and the
+ model's predictions at each epoch. See `validation_indexes`,
+ `validation_row_processor`, and `output_row_processor` for additional details.
+ class_colors: ([float, float, float]) if the input or output is a segmentation mask,
+ an array containing an rgb tuple (range 0-1) for each class.
+ log_batch_frequency: (integer) if None, callback will log every epoch.
+ If set to integer, callback will log training metrics every `log_batch_frequency`
+ batches.
+ log_best_prefix: (string) if None, no extra summary metrics will be saved.
+ If set to a string, the monitored metric and epoch will be prepended with this value
+ and stored as summary metrics.
+ validation_indexes: ([wandb.data_types._TableLinkMixin]) an ordered list of index keys to associate
+ with each validation example. If log_evaluation is True and `validation_indexes` is provided,
+ then a Table of validation data will not be created and instead each prediction will
+ be associated with the row represented by the `TableLinkMixin`. The most common way to obtain
+ such keys are is use `Table.get_index()` which will return a list of row keys.
+ validation_row_processor: (Callable) a function to apply to the validation data, commonly used to visualize the data.
+ The function will receive an `ndx` (int) and a `row` (dict). If your model has a single input,
+ then `row["input"]` will be the input data for the row. Else, it will be keyed based on the name of the
+ input slot. If your fit function takes a single target, then `row["target"]` will be the target data for the row. Else,
+ it will be keyed based on the name of the output slots. For example, if your input data is a single ndarray,
+ but you wish to visualize the data as an Image, then you can provide `lambda ndx, row: {"img": wandb.Image(row["input"])}`
+ as the processor. Ignored if log_evaluation is False or `validation_indexes` are present.
+ output_row_processor: (Callable) same as `validation_row_processor`, but applied to the model's output. `row["output"]` will contain
+ the results of the model output.
+ infer_missing_processors: (bool) Determines if `validation_row_processor` and `output_row_processor`
+ should be inferred if missing. Defaults to True. If `labels` are provided, we will attempt to infer classification-type
+ processors where appropriate.
+ log_evaluation_frequency: (int) Determines the frequency which evaluation results will be logged. Default 0 (only at the end of training).
+ Set to 1 to log every epoch, 2 to log every other epoch, and so on. Has no effect when log_evaluation is False.
+ compute_flops: (bool) Compute the FLOPs of your Keras Sequential or Functional model in GigaFLOPs unit.
+ """
+
+ def __init__(
+ self,
+ monitor="val_loss",
+ verbose=0,
+ mode="auto",
+ save_weights_only=False,
+ log_weights=False,
+ log_gradients=False,
+ save_model=True,
+ training_data=None,
+ validation_data=None,
+ labels=None,
+ predictions=36,
+ generator=None,
+ input_type=None,
+ output_type=None,
+ log_evaluation=False,
+ validation_steps=None,
+ class_colors=None,
+ log_batch_frequency=None,
+ log_best_prefix="best_",
+ save_graph=True,
+ validation_indexes=None,
+ validation_row_processor=None,
+ prediction_row_processor=None,
+ infer_missing_processors=True,
+ log_evaluation_frequency=0,
+ compute_flops=False,
+ **kwargs,
+ ):
+ if wandb.run is None:
+ raise wandb.Error("You must call wandb.init() before WandbCallback()")
+
+ deprecate(
+ field_name=Deprecated.keras_callback,
+ warning_message=(
+ "WandbCallback is deprecated and will be removed in a future release. "
+ "Please use the WandbMetricsLogger, WandbModelCheckpoint, and WandbEvalCallback "
+ "callbacks instead. "
+ "See https://docs.wandb.ai/guides/integrations/keras for more information."
+ ),
+ )
+
+ with wandb.wandb_lib.telemetry.context(run=wandb.run) as tel:
+ tel.feature.keras = True
+ self.validation_data = None
+ # This is kept around for legacy reasons
+ if validation_data is not None:
+ if is_generator_like(validation_data):
+ generator = validation_data
+ else:
+ self.validation_data = validation_data
+ if labels is None:
+ labels = []
+ self.labels = labels
+ self.predictions = min(predictions, 100)
+
+ self.monitor = monitor
+ self.verbose = verbose
+ self.save_weights_only = save_weights_only
+ self.save_graph = save_graph
+
+ wandb.save("model-best.h5")
+ self.filepath = os.path.join(wandb.run.dir, "model-best.h5")
+ self.save_model = save_model
+ if save_model:
+ deprecate(
+ field_name=Deprecated.keras_callback__save_model,
+ warning_message=(
+ "The save_model argument by default saves the model in the HDF5 format that cannot save "
+ "custom objects like subclassed models and custom layers. This behavior will be deprecated "
+ "in a future release in favor of the SavedModel format. Meanwhile, the HDF5 model is saved "
+ "as W&B files and the SavedModel as W&B Artifacts."
+ ),
+ )
+
+ self.save_model_as_artifact = True
+ self.log_weights = log_weights
+ self.log_gradients = log_gradients
+ self.training_data = training_data
+ self.generator = generator
+ self._graph_rendered = False
+
+ data_type = kwargs.get("data_type", None)
+ if data_type is not None:
+ deprecate(
+ field_name=Deprecated.keras_callback__data_type,
+ warning_message=(
+ "The data_type argument of wandb.keras.WandbCallback is deprecated "
+ "and will be removed in a future release. Please use input_type instead.\n"
+ "Setting input_type = data_type."
+ ),
+ )
+ input_type = data_type
+ self.input_type = input_type
+ self.output_type = output_type
+ self.log_evaluation = log_evaluation
+ self.validation_steps = validation_steps
+ self.class_colors = np.array(class_colors) if class_colors is not None else None
+ self.log_batch_frequency = log_batch_frequency
+ self.log_best_prefix = log_best_prefix
+ self.compute_flops = compute_flops
+
+ self._prediction_batch_size = None
+
+ if self.log_gradients:
+ if int(tf.__version__.split(".")[0]) < 2:
+ raise Exception("Gradient logging requires tensorflow 2.0 or higher.")
+ if self.training_data is None:
+ raise ValueError(
+ "training_data argument is required for gradient logging."
+ )
+ if isinstance(self.training_data, (list, tuple)):
+ if len(self.training_data) != 2:
+ raise ValueError("training data must be a tuple of length two")
+ self._training_data_x, self._training_data_y = self.training_data
+ else:
+ self._training_data_x = (
+ self.training_data
+ ) # generator, tf.data.Dataset etc
+ self._training_data_y = None
+
+ # From Keras
+ if mode not in ["auto", "min", "max"]:
+ wandb.termwarn(
+ f"WandbCallback mode {mode} is unknown, fallback to auto mode."
+ )
+ mode = "auto"
+
+ if mode == "min":
+ self.monitor_op = operator.lt
+ self.best = float("inf")
+ elif mode == "max":
+ self.monitor_op = operator.gt
+ self.best = float("-inf")
+ else:
+ if "acc" in self.monitor or self.monitor.startswith("fmeasure"):
+ self.monitor_op = operator.gt
+ self.best = float("-inf")
+ else:
+ self.monitor_op = operator.lt
+ self.best = float("inf")
+ # Get the previous best metric for resumed runs
+ previous_best = wandb.run.summary.get(f"{self.log_best_prefix}{self.monitor}")
+ if previous_best is not None:
+ self.best = previous_best
+
+ self._validation_data_logger = None
+ self._validation_indexes = validation_indexes
+ self._validation_row_processor = validation_row_processor
+ self._prediction_row_processor = prediction_row_processor
+ self._infer_missing_processors = infer_missing_processors
+ self._log_evaluation_frequency = log_evaluation_frequency
+ self._model_trained_since_last_eval = False
+
+ def _build_grad_accumulator_model(self):
+ inputs = self.model.inputs
+ outputs = self.model(inputs)
+ grad_acc_model = tf.keras.models.Model(inputs, outputs)
+ grad_acc_model.compile(loss=self.model.loss, optimizer=_CustomOptimizer())
+
+ # make sure magic doesn't think this is a user model
+ grad_acc_model._wandb_internal_model = True
+
+ self._grad_accumulator_model = grad_acc_model
+ self._grad_accumulator_callback = _GradAccumulatorCallback()
+
+ def _implements_train_batch_hooks(self):
+ return self.log_batch_frequency is not None
+
+ def _implements_test_batch_hooks(self):
+ return self.log_batch_frequency is not None
+
+ def _implements_predict_batch_hooks(self):
+ return self.log_batch_frequency is not None
+
+ def set_params(self, params):
+ self.params = params
+
+ def set_model(self, model):
+ super().set_model(model)
+ if self.input_type == "auto" and len(model.inputs) == 1:
+ self.input_type = wandb.util.guess_data_type(
+ model.inputs[0].shape, risky=True
+ )
+ if self.input_type and self.output_type is None and len(model.outputs) == 1:
+ self.output_type = wandb.util.guess_data_type(model.outputs[0].shape)
+ if self.log_gradients:
+ self._build_grad_accumulator_model()
+
+ def _attempt_evaluation_log(self, commit=True):
+ if self.log_evaluation and self._validation_data_logger:
+ try:
+ if not self.model:
+ wandb.termwarn("WandbCallback unable to read model from trainer")
+ else:
+ self._validation_data_logger.log_predictions(
+ predictions=self._validation_data_logger.make_predictions(
+ self.model.predict
+ ),
+ commit=commit,
+ )
+ self._model_trained_since_last_eval = False
+ except Exception as e:
+ wandb.termwarn("Error during prediction logging for epoch: " + str(e))
+
+ def on_epoch_end(self, epoch, logs=None):
+ if logs is None:
+ logs = {}
+ if self.log_weights:
+ wandb.log(self._log_weights(), commit=False)
+
+ if self.log_gradients:
+ wandb.log(self._log_gradients(), commit=False)
+
+ if self.input_type in (
+ "image",
+ "images",
+ "segmentation_mask",
+ ) or self.output_type in ("image", "images", "segmentation_mask"):
+ if self.generator:
+ self.validation_data = next(self.generator)
+ if self.validation_data is None:
+ wandb.termwarn(
+ "No validation_data set, pass a generator to the callback."
+ )
+ elif self.validation_data and len(self.validation_data) > 0:
+ wandb.log(
+ {"examples": self._log_images(num_images=self.predictions)},
+ commit=False,
+ )
+
+ if (
+ self._log_evaluation_frequency > 0
+ and epoch % self._log_evaluation_frequency == 0
+ ):
+ self._attempt_evaluation_log(commit=False)
+
+ wandb.log({"epoch": epoch}, commit=False)
+ wandb.log(logs, commit=True)
+
+ self.current = logs.get(self.monitor)
+ if self.current and self.monitor_op(self.current, self.best):
+ if self.log_best_prefix:
+ wandb.run.summary[f"{self.log_best_prefix}{self.monitor}"] = (
+ self.current
+ )
+ wandb.run.summary["{}{}".format(self.log_best_prefix, "epoch")] = epoch
+ if self.verbose and not self.save_model:
+ wandb.termlog(
+ f"Epoch {epoch:05d}: {self.monitor} improved from {self.best:.5f} to {self.current:.5f}"
+ )
+ if self.save_model:
+ self._save_model(epoch)
+
+ if self.save_model and self.save_model_as_artifact:
+ self._save_model_as_artifact(epoch)
+
+ self.best = self.current
+
+ # This is what keras used pre tensorflow.keras
+ def on_batch_begin(self, batch, logs=None):
+ pass
+
+ # This is what keras used pre tensorflow.keras
+ def on_batch_end(self, batch, logs=None):
+ if self.save_graph and not self._graph_rendered:
+ # Couldn't do this in train_begin because keras may still not be built
+ wandb.run.summary["graph"] = wandb.Graph.from_keras(self.model)
+ self._graph_rendered = True
+
+ if self.log_batch_frequency and batch % self.log_batch_frequency == 0:
+ wandb.log(logs, commit=True)
+
+ def on_train_batch_begin(self, batch, logs=None):
+ self._model_trained_since_last_eval = True
+
+ def on_train_batch_end(self, batch, logs=None):
+ if self.save_graph and not self._graph_rendered:
+ # Couldn't do this in train_begin because keras may still not be built
+ wandb.run.summary["graph"] = wandb.Graph.from_keras(self.model)
+ self._graph_rendered = True
+
+ if self.log_batch_frequency and batch % self.log_batch_frequency == 0:
+ wandb.log(logs, commit=True)
+
+ def on_test_begin(self, logs=None):
+ pass
+
+ def on_test_end(self, logs=None):
+ pass
+
+ def on_test_batch_begin(self, batch, logs=None):
+ pass
+
+ def on_test_batch_end(self, batch, logs=None):
+ pass
+
+ def on_train_begin(self, logs=None):
+ if self.log_evaluation:
+ try:
+ validation_data = None
+ if self.validation_data:
+ validation_data = self.validation_data
+ elif self.generator:
+ if not self.validation_steps:
+ wandb.termwarn(
+ "WandbCallback is unable to log validation data. "
+ "When using a generator for validation_data, you must pass validation_steps"
+ )
+ else:
+ x = None
+ y_true = None
+ for _ in range(self.validation_steps):
+ bx, by_true = next(self.generator)
+ if x is None:
+ x, y_true = bx, by_true
+ else:
+ x, y_true = (
+ np.append(x, bx, axis=0),
+ np.append(y_true, by_true, axis=0),
+ )
+ validation_data = (x, y_true)
+ else:
+ wandb.termwarn(
+ "WandbCallback is unable to read validation_data from trainer "
+ "and therefore cannot log validation data. Ensure Keras is properly "
+ "patched by calling `from wandb.keras import WandbCallback` at the top of your script."
+ )
+ if validation_data:
+ self._validation_data_logger = ValidationDataLogger(
+ inputs=validation_data[0],
+ targets=validation_data[1],
+ indexes=self._validation_indexes,
+ validation_row_processor=self._validation_row_processor,
+ prediction_row_processor=self._prediction_row_processor,
+ class_labels=self.labels,
+ infer_missing_processors=self._infer_missing_processors,
+ )
+ except Exception as e:
+ wandb.termwarn(
+ "Error initializing ValidationDataLogger in WandbCallback. "
+ f"Skipping logging validation data. Error: {str(e)}"
+ )
+
+ if self.compute_flops and _can_compute_flops():
+ try:
+ wandb.summary["GFLOPs"] = self.get_flops()
+ except Exception:
+ logger.exception("Error computing FLOPs")
+ wandb.termwarn("Unable to compute FLOPs for this model.")
+
+ def on_train_end(self, logs=None):
+ if self._model_trained_since_last_eval:
+ self._attempt_evaluation_log()
+
+ def on_predict_begin(self, logs=None):
+ pass
+
+ def on_predict_end(self, logs=None):
+ pass
+
+ def on_predict_batch_begin(self, batch, logs=None):
+ pass
+
+ def on_predict_batch_end(self, batch, logs=None):
+ pass
+
+ def _logits_to_captions(self, logits):
+ if logits[0].shape[-1] == 1:
+ # Scalar output from the model
+ # TODO: handle validation_y
+ if len(self.labels) == 2:
+ # User has named true and false
+ captions = [
+ self.labels[1] if logits[0] > 0.5 else self.labels[0]
+ for logit in logits
+ ]
+ else:
+ if len(self.labels) != 0:
+ wandb.termwarn(
+ "keras model is producing a single output, "
+ 'so labels should be a length two array: ["False label", "True label"].'
+ )
+ captions = [logit[0] for logit in logits]
+ else:
+ # Vector output from the model
+ # TODO: handle validation_y
+ labels = np.argmax(np.stack(logits), axis=1)
+
+ if len(self.labels) > 0:
+ # User has named the categories in self.labels
+ captions = []
+ for label in labels:
+ try:
+ captions.append(self.labels[label])
+ except IndexError:
+ captions.append(label)
+ else:
+ captions = labels
+ return captions
+
+ def _masks_to_pixels(self, masks):
+ # if its a binary mask, just return it as grayscale instead of picking the argmax
+ if len(masks[0].shape) == 2 or masks[0].shape[-1] == 1:
+ return masks
+ class_colors = (
+ self.class_colors
+ if self.class_colors is not None
+ else np.array(wandb.util.class_colors(masks[0].shape[2]))
+ )
+ imgs = class_colors[np.argmax(masks, axis=-1)]
+ return imgs
+
+ def _log_images(self, num_images=36):
+ validation_X = self.validation_data[0] # noqa: N806
+ validation_y = self.validation_data[1]
+
+ validation_length = len(validation_X)
+
+ if validation_length > num_images:
+ # pick some data at random
+ indices = np.random.choice(validation_length, num_images, replace=False)
+ else:
+ indices = range(validation_length)
+
+ test_data = []
+ test_output = []
+ for i in indices:
+ test_example = validation_X[i]
+ test_data.append(test_example)
+ test_output.append(validation_y[i])
+
+ if self.model.stateful:
+ predictions = self.model.predict(np.stack(test_data), batch_size=1)
+ self.model.reset_states()
+ else:
+ predictions = self.model.predict(
+ np.stack(test_data), batch_size=self._prediction_batch_size
+ )
+ if len(predictions) != len(test_data):
+ self._prediction_batch_size = 1
+ predictions = self.model.predict(
+ np.stack(test_data), batch_size=self._prediction_batch_size
+ )
+
+ if self.input_type == "label":
+ if self.output_type in ("image", "images", "segmentation_mask"):
+ captions = self._logits_to_captions(test_data)
+ output_image_data = (
+ self._masks_to_pixels(predictions)
+ if self.output_type == "segmentation_mask"
+ else predictions
+ )
+ reference_image_data = (
+ self._masks_to_pixels(test_output)
+ if self.output_type == "segmentation_mask"
+ else test_output
+ )
+ output_images = [
+ wandb.Image(data, caption=captions[i], grouping=2)
+ for i, data in enumerate(output_image_data)
+ ]
+ reference_images = [
+ wandb.Image(data, caption=captions[i])
+ for i, data in enumerate(reference_image_data)
+ ]
+ return list(chain.from_iterable(zip(output_images, reference_images)))
+ elif self.input_type in ("image", "images", "segmentation_mask"):
+ input_image_data = (
+ self._masks_to_pixels(test_data)
+ if self.input_type == "segmentation_mask"
+ else test_data
+ )
+ if self.output_type == "label":
+ # we just use the predicted label as the caption for now
+ captions = self._logits_to_captions(predictions)
+ return [
+ wandb.Image(data, caption=captions[i])
+ for i, data in enumerate(test_data)
+ ]
+ elif self.output_type in ("image", "images", "segmentation_mask"):
+ output_image_data = (
+ self._masks_to_pixels(predictions)
+ if self.output_type == "segmentation_mask"
+ else predictions
+ )
+ reference_image_data = (
+ self._masks_to_pixels(test_output)
+ if self.output_type == "segmentation_mask"
+ else test_output
+ )
+ input_images = [
+ wandb.Image(data, grouping=3)
+ for i, data in enumerate(input_image_data)
+ ]
+ output_images = [
+ wandb.Image(data) for i, data in enumerate(output_image_data)
+ ]
+ reference_images = [
+ wandb.Image(data) for i, data in enumerate(reference_image_data)
+ ]
+ return list(
+ chain.from_iterable(
+ zip(input_images, output_images, reference_images)
+ )
+ )
+ else:
+ # unknown output, just log the input images
+ return [wandb.Image(img) for img in test_data]
+ elif self.output_type in ("image", "images", "segmentation_mask"):
+ # unknown input, just log the predicted and reference outputs without captions
+ output_image_data = (
+ self._masks_to_pixels(predictions)
+ if self.output_type == "segmentation_mask"
+ else predictions
+ )
+ reference_image_data = (
+ self._masks_to_pixels(test_output)
+ if self.output_type == "segmentation_mask"
+ else test_output
+ )
+ output_images = [
+ wandb.Image(data, grouping=2)
+ for i, data in enumerate(output_image_data)
+ ]
+ reference_images = [
+ wandb.Image(data) for i, data in enumerate(reference_image_data)
+ ]
+ return list(chain.from_iterable(zip(output_images, reference_images)))
+
+ def _log_weights(self):
+ metrics = {}
+ for layer in self.model.layers:
+ weights = layer.get_weights()
+ if len(weights) == 1:
+ _update_if_numeric(
+ metrics, "parameters/" + layer.name + ".weights", weights[0]
+ )
+ elif len(weights) == 2:
+ _update_if_numeric(
+ metrics, "parameters/" + layer.name + ".weights", weights[0]
+ )
+ _update_if_numeric(
+ metrics, "parameters/" + layer.name + ".bias", weights[1]
+ )
+ return metrics
+
+ def _log_gradients(self):
+ # Suppress callback warnings grad accumulator
+ og_level = tf_logger.level
+ tf_logger.setLevel("ERROR")
+
+ self._grad_accumulator_model.fit(
+ self._training_data_x,
+ self._training_data_y,
+ verbose=0,
+ callbacks=[self._grad_accumulator_callback],
+ )
+ tf_logger.setLevel(og_level)
+ weights = self.model.trainable_weights
+ grads = self._grad_accumulator_callback.grads
+ metrics = {}
+ for weight, grad in zip(weights, grads):
+ metrics["gradients/" + weight.name.split(":")[0] + ".gradient"] = (
+ wandb.Histogram(grad)
+ )
+ return metrics
+
+ def _log_dataframe(self):
+ x, y_true, y_pred = None, None, None
+
+ if self.validation_data:
+ x, y_true = self.validation_data[0], self.validation_data[1]
+ y_pred = self.model.predict(x)
+ elif self.generator:
+ if not self.validation_steps:
+ wandb.termwarn(
+ "when using a generator for validation data with dataframes, "
+ "you must pass validation_steps. skipping"
+ )
+ return None
+
+ for _ in range(self.validation_steps):
+ bx, by_true = next(self.generator)
+ by_pred = self.model.predict(bx)
+ if x is None:
+ x, y_true, y_pred = bx, by_true, by_pred
+ else:
+ x, y_true, y_pred = (
+ np.append(x, bx, axis=0),
+ np.append(y_true, by_true, axis=0),
+ np.append(y_pred, by_pred, axis=0),
+ )
+
+ if self.input_type in ("image", "images") and self.output_type == "label":
+ return wandb.image_categorizer_dataframe(
+ x=x, y_true=y_true, y_pred=y_pred, labels=self.labels
+ )
+ elif (
+ self.input_type in ("image", "images")
+ and self.output_type == "segmentation_mask"
+ ):
+ return wandb.image_segmentation_dataframe(
+ x=x,
+ y_true=y_true,
+ y_pred=y_pred,
+ labels=self.labels,
+ class_colors=self.class_colors,
+ )
+ else:
+ wandb.termwarn(
+ f"unknown dataframe type for input_type={self.input_type} and output_type={self.output_type}"
+ )
+ return None
+
+ def _save_model(self, epoch):
+ if wandb.run.disabled:
+ return
+ if self.verbose > 0:
+ wandb.termlog(
+ f"Epoch {epoch:05d}: {self.monitor} improved from {self.best:.5f} to {self.current:.5f}, "
+ f"saving model to {self.filepath}"
+ )
+
+ try:
+ if self.save_weights_only:
+ self.model.save_weights(self.filepath, overwrite=True)
+ else:
+ self.model.save(self.filepath, overwrite=True)
+ # Was getting `RuntimeError: Unable to create link` in TF 1.13.1
+ # also saw `TypeError: can't pickle _thread.RLock objects`
+ except (ImportError, RuntimeError, TypeError, AttributeError):
+ logger.exception("Error saving model in the h5py format")
+ wandb.termerror(
+ "Can't save model in the h5py format. The model will be saved as "
+ "as an W&B Artifact in the 'tf' format."
+ )
+
+ def _save_model_as_artifact(self, epoch):
+ if wandb.run.disabled:
+ return
+
+ # Save the model in the SavedModel format.
+ # TODO: Replace this manual artifact creation with the `log_model` method
+ # after `log_model` is released from beta.
+ self.model.save(self.filepath[:-3], overwrite=True, save_format="tf")
+
+ # Log the model as artifact.
+ name = wandb.util.make_artifact_name_safe(f"model-{wandb.run.name}")
+ model_artifact = wandb.Artifact(name, type="model")
+ model_artifact.add_dir(self.filepath[:-3])
+ wandb.run.log_artifact(model_artifact, aliases=["latest", f"epoch_{epoch}"])
+
+ # Remove the SavedModel from wandb dir as we don't want to log it to save memory.
+ shutil.rmtree(self.filepath[:-3])
+
+ def get_flops(self) -> float:
+ """Calculate FLOPS [GFLOPs] for a tf.keras.Model or tf.keras.Sequential model in inference mode.
+
+ It uses tf.compat.v1.profiler under the hood.
+ """
+ if not hasattr(self, "model"):
+ raise wandb.Error("self.model must be set before using this method.")
+
+ if not isinstance(
+ self.model, (tf.keras.models.Sequential, tf.keras.models.Model)
+ ):
+ raise TypeError(
+ "Calculating FLOPS is only supported for "
+ "`tf.keras.Model` and `tf.keras.Sequential` instances."
+ )
+
+ from tensorflow.python.framework.convert_to_constants import (
+ convert_variables_to_constants_v2_as_graph,
+ )
+
+ # Compute FLOPs for one sample
+ batch_size = 1
+ inputs = [
+ tf.TensorSpec([batch_size] + inp.shape[1:], inp.dtype)
+ for inp in self.model.inputs
+ ]
+
+ # convert tf.keras model into frozen graph to count FLOPs about operations used at inference
+ real_model = tf.function(self.model).get_concrete_function(inputs)
+ frozen_func, _ = convert_variables_to_constants_v2_as_graph(real_model)
+
+ # Calculate FLOPs with tf.profiler
+ run_meta = tf.compat.v1.RunMetadata()
+ opts = (
+ tf.compat.v1.profiler.ProfileOptionBuilder(
+ tf.compat.v1.profiler.ProfileOptionBuilder().float_operation()
+ )
+ .with_empty_output()
+ .build()
+ )
+
+ flops = tf.compat.v1.profiler.profile(
+ graph=frozen_func.graph, run_meta=run_meta, cmd="scope", options=opts
+ )
+
+ # convert to GFLOPs
+ return (flops.total_float_ops / 1e9) / 2
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/kfp/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/kfp/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f3a362ca0fc895bce03dccdfeaa3274a9b5963d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/kfp/__init__.py
@@ -0,0 +1,6 @@
+__all__ = ["wandb_log", "unpatch_kfp"]
+
+from .kfp_patch import patch_kfp, unpatch_kfp
+from .wandb_logging import wandb_log
+
+patch_kfp()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/kfp/helpers.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/kfp/helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..feebcc62ea3688a2a93818adb445f6454a6d9dc2
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/kfp/helpers.py
@@ -0,0 +1,28 @@
+import json
+
+
+def add_wandb_visualization(run, mlpipeline_ui_metadata_path):
+ """NOTE: To use this, you must modify your component to have an output called `mlpipeline_ui_metadata_path` AND call `wandb.init` yourself inside that component.
+
+ Example usage:
+
+ def my_component(..., mlpipeline_ui_metadata_path: OutputPath()):
+ import wandb
+ from wandb.integration.kfp.helpers import add_wandb_visualization
+
+ with wandb.init() as run:
+ add_wandb_visualization(run, mlpipeline_ui_metadata_path)
+
+ ... # the rest of your code here
+ """
+
+ def get_iframe_html(run):
+ return f''
+
+ iframe_html = get_iframe_html(run)
+ metadata = {
+ "outputs": [{"type": "markdown", "storage": "inline", "source": iframe_html}]
+ }
+
+ with open(mlpipeline_ui_metadata_path, "w") as metadata_file:
+ json.dump(metadata, metadata_file)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/kfp/kfp_patch.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/kfp/kfp_patch.py
new file mode 100644
index 0000000000000000000000000000000000000000..367b03afd0fd673250328fe3882fb8c2fef0550c
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/kfp/kfp_patch.py
@@ -0,0 +1,335 @@
+import inspect
+import itertools
+import textwrap
+from typing import Callable, List, Mapping, Optional
+
+import wandb
+
+try:
+ from kfp import __version__ as kfp_version
+ from kfp.components import structures
+ from kfp.components._components import _create_task_factory_from_component_spec
+ from kfp.components._python_op import _func_to_component_spec
+ from packaging.version import parse
+
+ MIN_KFP_VERSION = "1.6.1"
+
+ if parse(kfp_version) < parse(MIN_KFP_VERSION):
+ wandb.termwarn(
+ f"Your version of kfp {kfp_version} may not work. This integration requires kfp>={MIN_KFP_VERSION}"
+ )
+
+except ImportError:
+ wandb.termerror("kfp not found! Please `pip install kfp`")
+
+from .wandb_logging import wandb_log
+
+decorator_code = inspect.getsource(wandb_log)
+wandb_logging_extras = f"""
+import typing
+from typing import NamedTuple
+
+import collections
+from collections import namedtuple
+
+import kfp
+from kfp import components
+from kfp.components import InputPath, OutputPath
+
+import wandb
+
+{decorator_code}
+"""
+
+
+def full_path_exists(full_func):
+ def get_parent_child_pairs(full_func):
+ components = full_func.split(".")
+ parents, children = [], []
+ for i, _ in enumerate(components[:-1], 1):
+ parent = ".".join(components[:i])
+ child = components[i]
+ parents.append(parent)
+ children.append(child)
+ return zip(parents, children)
+
+ for parent, child in get_parent_child_pairs(full_func):
+ module = wandb.util.get_module(parent)
+ if not module or not hasattr(module, child) or getattr(module, child) is None:
+ return False
+ return True
+
+
+def patch(module_name, func):
+ module = wandb.util.get_module(module_name)
+ success = False
+
+ full_func = f"{module_name}.{func.__name__}"
+ if not full_path_exists(full_func):
+ wandb.termerror(
+ f"Failed to patch {module_name}.{func.__name__}! Please check if this package/module is installed!"
+ )
+ else:
+ wandb.patched.setdefault(module.__name__, [])
+ # if already patched, do not patch again
+ if [module, func.__name__] not in wandb.patched[module.__name__]:
+ setattr(module, f"orig_{func.__name__}", getattr(module, func.__name__))
+ setattr(module, func.__name__, func)
+ wandb.patched[module.__name__].append([module, func.__name__])
+ success = True
+
+ return success
+
+
+def unpatch(module_name):
+ if module_name in wandb.patched:
+ for module, func in wandb.patched[module_name]:
+ setattr(module, func, getattr(module, f"orig_{func}"))
+ wandb.patched[module_name] = []
+
+
+def unpatch_kfp():
+ unpatch("kfp.components")
+ unpatch("kfp.components._python_op")
+ unpatch("wandb.integration.kfp")
+
+
+def patch_kfp():
+ to_patch = [
+ (
+ "kfp.components",
+ create_component_from_func,
+ ),
+ (
+ "kfp.components._python_op",
+ create_component_from_func,
+ ),
+ (
+ "kfp.components._python_op",
+ _get_function_source_definition,
+ ),
+ ("kfp.components._python_op", strip_type_hints),
+ ]
+
+ successes = []
+ for module_name, func in to_patch:
+ success = patch(module_name, func)
+ successes.append(success)
+ if not all(successes):
+ wandb.termerror(
+ "Failed to patch one or more kfp functions. Patching @wandb_log decorator to no-op."
+ )
+ patch("wandb.integration.kfp", wandb_log)
+
+
+def wandb_log(
+ func=None,
+ # /, # py38 only
+ log_component_file=True,
+):
+ """Wrap a standard python function and log to W&B.
+
+ NOTE: Because patching failed, this decorator is a no-op.
+ """
+ from functools import wraps
+
+ def decorator(func):
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ return func(*args, **kwargs)
+
+ return wrapper
+
+ if func is None:
+ return decorator
+ else:
+ return decorator(func)
+
+
+def _get_function_source_definition(func: Callable) -> str:
+ """Get the source code of a function.
+
+ This function is modified from KFP. The original source is below:
+ https://github.com/kubeflow/pipelines/blob/b6406b02f45cdb195c7b99e2f6d22bf85b12268b/sdk/python/kfp/components/_python_op.py#L300-L319.
+ """
+ func_code = inspect.getsource(func)
+
+ # Function might be defined in some indented scope (e.g. in another
+ # function). We need to handle this and properly dedent the function source
+ # code
+ func_code = textwrap.dedent(func_code)
+ func_code_lines = func_code.split("\n")
+
+ # For wandb, allow decorators (so we can use the @wandb_log decorator)
+ func_code_lines = itertools.dropwhile(
+ lambda x: not (x.startswith(("def", "@wandb_log"))),
+ func_code_lines,
+ )
+
+ if not func_code_lines:
+ raise ValueError(
+ f'Failed to dedent and clean up the source of function "{func.__name__}". '
+ "It is probably not properly indented."
+ )
+
+ return "\n".join(func_code_lines)
+
+
+def create_component_from_func(
+ func: Callable,
+ output_component_file: Optional[str] = None,
+ base_image: Optional[str] = None,
+ packages_to_install: Optional[List[str]] = None,
+ annotations: Optional[Mapping[str, str]] = None,
+):
+ '''Convert a Python function to a component and returns a task factory.
+
+ The returned task factory accepts arguments and returns a task object.
+
+ This function is modified from KFP. The original source is below:
+ https://github.com/kubeflow/pipelines/blob/b6406b02f45cdb195c7b99e2f6d22bf85b12268b/sdk/python/kfp/components/_python_op.py#L998-L1110.
+
+ Args:
+ func: The python function to convert
+ base_image: Optional. Specify a custom Docker container image to use in the component. For lightweight components, the image needs to have python 3.5+. Default is the python image corresponding to the current python environment.
+ output_component_file: Optional. Write a component definition to a local file. The produced component file can be loaded back by calling :code:`load_component_from_file` or :code:`load_component_from_uri`.
+ packages_to_install: Optional. List of [versioned] python packages to pip install before executing the user function.
+ annotations: Optional. Allows adding arbitrary key-value data to the component specification.
+
+ Returns:
+ A factory function with a strongly-typed signature taken from the python function.
+ Once called with the required arguments, the factory constructs a task instance that can run the original function in a container.
+
+ Examples:
+ The function name and docstring are used as component name and description. Argument and return annotations are used as component input/output types::
+
+ def add(a: float, b: float) -> float:
+ """Return sum of two arguments"""
+ return a + b
+
+
+ # add_op is a task factory function that creates a task object when given arguments
+ add_op = create_component_from_func(
+ func=add,
+ base_image="python:3.7", # Optional
+ output_component_file="add.component.yaml", # Optional
+ packages_to_install=["pandas==0.24"], # Optional
+ )
+
+ # The component spec can be accessed through the .component_spec attribute:
+ add_op.component_spec.save("add.component.yaml")
+
+ # The component function can be called with arguments to create a task:
+ add_task = add_op(1, 3)
+
+ # The resulting task has output references, corresponding to the component outputs.
+ # When the function only has a single anonymous return value, the output name is "Output":
+ sum_output_ref = add_task.outputs["Output"]
+
+ # These task output references can be passed to other component functions, constructing a computation graph:
+ task2 = add_op(sum_output_ref, 5)
+
+
+ :code:`create_component_from_func` function can also be used as decorator::
+
+ @create_component_from_func
+ def add_op(a: float, b: float) -> float:
+ """Return sum of two arguments"""
+ return a + b
+
+ To declare a function with multiple return values, use the :code:`NamedTuple` return annotation syntax::
+
+ from typing import NamedTuple
+
+
+ def add_multiply_two_numbers(a: float, b: float) -> NamedTuple(
+ "Outputs", [("sum", float), ("product", float)]
+ ):
+ """Return sum and product of two arguments"""
+ return (a + b, a * b)
+
+
+ add_multiply_op = create_component_from_func(add_multiply_two_numbers)
+
+ # The component function can be called with arguments to create a task:
+ add_multiply_task = add_multiply_op(1, 3)
+
+ # The resulting task has output references, corresponding to the component outputs:
+ sum_output_ref = add_multiply_task.outputs["sum"]
+
+ # These task output references can be passed to other component functions, constructing a computation graph:
+ task2 = add_multiply_op(sum_output_ref, 5)
+
+ Bigger data should be read from files and written to files.
+ Use the :py:class:`kfp.components.InputPath` parameter annotation to tell the system that the function wants to consume the corresponding input data as a file. The system will download the data, write it to a local file and then pass the **path** of that file to the function.
+ Use the :py:class:`kfp.components.OutputPath` parameter annotation to tell the system that the function wants to produce the corresponding output data as a file. The system will prepare and pass the **path** of a file where the function should write the output data. After the function exits, the system will upload the data to the storage system so that it can be passed to downstream components.
+
+ You can specify the type of the consumed/produced data by specifying the type argument to :py:class:`kfp.components.InputPath` and :py:class:`kfp.components.OutputPath`. The type can be a python type or an arbitrary type name string. :code:`OutputPath('CatBoostModel')` means that the function states that the data it has written to a file has type :code:`CatBoostModel`. :code:`InputPath('CatBoostModel')` means that the function states that it expect the data it reads from a file to have type 'CatBoostModel'. When the pipeline author connects inputs to outputs the system checks whether the types match.
+ Every kind of data can be consumed as a file input. Conversely, bigger data should not be consumed by value as all value inputs pass through the command line.
+
+ Example of a component function declaring file input and output::
+
+ def catboost_train_classifier(
+ training_data_path: InputPath(
+ "CSV"
+ ), # Path to input data file of type "CSV"
+ trained_model_path: OutputPath(
+ "CatBoostModel"
+ ), # Path to output data file of type "CatBoostModel"
+ number_of_trees: int = 100, # Small output of type "Integer"
+ ) -> NamedTuple(
+ "Outputs",
+ [
+ ("Accuracy", float), # Small output of type "Float"
+ ("Precision", float), # Small output of type "Float"
+ ("JobUri", "URI"), # Small output of type "URI"
+ ],
+ ):
+ """Train CatBoost classification model"""
+ ...
+
+ return (accuracy, precision, recall)
+ '''
+ core_packages = ["wandb", "kfp"]
+
+ if not packages_to_install:
+ packages_to_install = core_packages
+ else:
+ packages_to_install += core_packages
+
+ component_spec = _func_to_component_spec(
+ func=func,
+ extra_code=wandb_logging_extras,
+ base_image=base_image,
+ packages_to_install=packages_to_install,
+ )
+ if annotations:
+ component_spec.metadata = structures.MetadataSpec(
+ annotations=annotations,
+ )
+
+ if output_component_file:
+ component_spec.save(output_component_file)
+
+ return _create_task_factory_from_component_spec(component_spec)
+
+
+def strip_type_hints(source_code: str) -> str:
+ """Strip type hints from source code.
+
+ This function is modified from KFP. The original source is below:
+ https://github.com/kubeflow/pipelines/blob/b6406b02f45cdb195c7b99e2f6d22bf85b12268b/sdk/python/kfp/components/_python_op.py#L237-L248.
+ """
+ # For wandb, do not strip type hints
+
+ # try:
+ # return _strip_type_hints_using_lib2to3(source_code)
+ # except Exception as ex:
+ # print('Error when stripping type annotations: ' + str(ex))
+
+ # try:
+ # return _strip_type_hints_using_strip_hints(source_code)
+ # except Exception as ex:
+ # print('Error when stripping type annotations: ' + str(ex))
+
+ return source_code
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/kfp/wandb_logging.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/kfp/wandb_logging.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d0edf3eac211b59908bc3aa4849a459c2da2148
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/kfp/wandb_logging.py
@@ -0,0 +1,182 @@
+def wandb_log( # noqa: C901
+ func=None,
+ # /, # py38 only
+ log_component_file=True,
+):
+ """Wrap a standard python function and log to W&B."""
+ import json
+ import os
+ from functools import wraps
+ from inspect import Parameter, signature
+
+ from kfp import components
+ from kfp.components import (
+ InputArtifact,
+ InputBinaryFile,
+ InputPath,
+ InputTextFile,
+ OutputArtifact,
+ OutputBinaryFile,
+ OutputPath,
+ OutputTextFile,
+ )
+
+ import wandb
+ from wandb.sdk.lib import telemetry as wb_telemetry
+
+ output_types = (OutputArtifact, OutputBinaryFile, OutputPath, OutputTextFile)
+ input_types = (InputArtifact, InputBinaryFile, InputPath, InputTextFile)
+
+ def isinstance_namedtuple(x):
+ t = type(x)
+ b = t.__bases__
+ if len(b) != 1 or b[0] is not tuple:
+ return False
+ f = getattr(t, "_fields", None)
+ if not isinstance(f, tuple):
+ return False
+ return all(isinstance(n, str) for n in f)
+
+ def get_iframe_html(run):
+ return f''
+
+ def get_link_back_to_kubeflow():
+ wandb_kubeflow_url = os.getenv("WANDB_KUBEFLOW_URL")
+ return f"{wandb_kubeflow_url}/#/runs/details/{{workflow.uid}}"
+
+ def log_input_scalar(name, data, run=None):
+ run.config[name] = data
+ wandb.termlog(f"Setting config: {name} to {data}")
+
+ def log_input_artifact(name, data, type, run=None):
+ artifact = wandb.Artifact(name, type=type)
+ artifact.add_file(data)
+ run.use_artifact(artifact)
+ wandb.termlog(f"Using artifact: {name}")
+
+ def log_output_scalar(name, data, run=None):
+ if isinstance_namedtuple(data):
+ for k, v in zip(data._fields, data):
+ run.log({f"{func.__name__}.{k}": v})
+ else:
+ run.log({name: data})
+
+ def log_output_artifact(name, data, type, run=None):
+ artifact = wandb.Artifact(name, type=type)
+ artifact.add_file(data)
+ run.log_artifact(artifact)
+ wandb.termlog(f"Logging artifact: {name}")
+
+ def _log_component_file(func, run=None):
+ name = func.__name__
+ output_component_file = f"{name}.yml"
+ components._python_op.func_to_component_file(func, output_component_file)
+ artifact = wandb.Artifact(name, type="kubeflow_component_file")
+ artifact.add_file(output_component_file)
+ run.log_artifact(artifact)
+ wandb.termlog(f"Logging component file: {output_component_file}")
+
+ # Add `mlpipeline_ui_metadata_path` to signature to show W&B run in "ML Visualizations tab"
+ sig = signature(func)
+ no_default = []
+ has_default = []
+
+ for param in sig.parameters.values():
+ if param.default is param.empty:
+ no_default.append(param)
+ else:
+ has_default.append(param)
+
+ new_params = tuple(
+ (
+ *no_default,
+ Parameter(
+ "mlpipeline_ui_metadata_path",
+ annotation=OutputPath(),
+ kind=Parameter.POSITIONAL_OR_KEYWORD,
+ ),
+ *has_default,
+ )
+ )
+ new_sig = sig.replace(parameters=new_params)
+ new_anns = {param.name: param.annotation for param in new_params}
+ if "return" in func.__annotations__:
+ new_anns["return"] = func.__annotations__["return"]
+
+ def decorator(func):
+ input_scalars = {}
+ input_artifacts = {}
+ output_scalars = {}
+ output_artifacts = {}
+
+ for name, ann in func.__annotations__.items():
+ if name == "return":
+ output_scalars[name] = ann
+ elif isinstance(ann, output_types):
+ output_artifacts[name] = ann
+ elif isinstance(ann, input_types):
+ input_artifacts[name] = ann
+ else:
+ input_scalars[name] = ann
+
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ bound = new_sig.bind(*args, **kwargs)
+ bound.apply_defaults()
+
+ mlpipeline_ui_metadata_path = bound.arguments["mlpipeline_ui_metadata_path"]
+ del bound.arguments["mlpipeline_ui_metadata_path"]
+
+ with wandb.init(
+ job_type=func.__name__,
+ group="{{workflow.annotations.pipelines.kubeflow.org/run_name}}",
+ ) as run:
+ # Link back to the kfp UI
+ kubeflow_url = get_link_back_to_kubeflow()
+ run.notes = kubeflow_url
+ run.config["LINK_TO_KUBEFLOW_RUN"] = kubeflow_url
+
+ iframe_html = get_iframe_html(run)
+ metadata = {
+ "outputs": [
+ {
+ "type": "markdown",
+ "storage": "inline",
+ "source": iframe_html,
+ }
+ ]
+ }
+
+ with open(mlpipeline_ui_metadata_path, "w") as metadata_file:
+ json.dump(metadata, metadata_file)
+
+ if log_component_file:
+ _log_component_file(func, run=run)
+
+ for name, _ in input_scalars.items():
+ log_input_scalar(name, kwargs[name], run)
+
+ for name, ann in input_artifacts.items():
+ log_input_artifact(name, kwargs[name], ann.type, run)
+
+ with wb_telemetry.context(run=run) as tel:
+ tel.feature.kfp_wandb_log = True
+
+ result = func(*bound.args, **bound.kwargs)
+
+ for name, _ in output_scalars.items():
+ log_output_scalar(name, result, run)
+
+ for name, ann in output_artifacts.items():
+ log_output_artifact(name, kwargs[name], ann.type, run)
+
+ return result
+
+ wrapper.__signature__ = new_sig
+ wrapper.__annotations__ = new_anns
+ return wrapper
+
+ if func is None:
+ return decorator
+ else:
+ return decorator(func)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/langchain/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/langchain/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..aaec971a312e9369e1740f0b31e31782bb9b9e3f
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/langchain/__init__.py
@@ -0,0 +1,3 @@
+__all__ = ("WandbTracer",)
+
+from .wandb_tracer import WandbTracer
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/langchain/wandb_tracer.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/langchain/wandb_tracer.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c9a5ff31ce4d1effd6f2d28101b328257f0c577
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/langchain/wandb_tracer.py
@@ -0,0 +1,49 @@
+"""This module contains an integration with the LangChain library.
+
+Specifically, it exposes a `WandbTracer` class that can be used to stream
+LangChain activity to W&B. The intended usage pattern is to call
+`tracer = WandbTracer()` at the top of the script/notebook, and call
+`tracer.finish()` at the end of the script/notebook.
+ This will stream all LangChain activity to W&B.
+
+Technical Note:
+LangChain is in very rapid development - meaning their APIs and schemas are actively changing.
+As a matter of precaution, any call to LangChain apis, or use of their returned data is wrapped
+in a try/except block. This is to ensure that if a breaking change is introduced, the W&B
+integration will not break user code. The one exception to the rule is at import time. If
+LangChain is not installed, or the symbols are not in the same place, the appropriate error
+will be raised when importing this module.
+"""
+
+from packaging import version
+
+import wandb.util
+from wandb.proto.wandb_deprecated import Deprecated
+from wandb.sdk.lib import deprecate
+
+langchain = wandb.util.get_module(
+ name="langchain",
+ required="To use the LangChain WandbTracer you need to have the `langchain` python "
+ "package installed. Please install it with `pip install langchain`.",
+)
+
+if version.parse(langchain.__version__) < version.parse("0.0.188"):
+ raise ValueError(
+ "The Weights & Biases Langchain integration does not support versions 0.0.187 and lower. "
+ "To ensure proper functionality, please use version 0.0.188 or higher."
+ )
+
+# isort: off
+from langchain.callbacks.tracers import WandbTracer # noqa: E402
+
+
+class WandbTracer(WandbTracer):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ deprecate.deprecate(
+ field_name=Deprecated.langchain_tracer,
+ warning_message="This feature is deprecated and has been moved to `langchain`. Enable tracing by setting "
+ "LANGCHAIN_WANDB_TRACING=true in your environment. See the documentation at "
+ "https://python.langchain.com/docs/ecosystem/integrations/agent_with_wandb_tracing for guidance. "
+ "Replace your current import with `from langchain.callbacks.tracers import WandbTracer`.",
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/lightgbm/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/lightgbm/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc1029563baa721fbdbc2c2809974b59203008ee
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/lightgbm/__init__.py
@@ -0,0 +1,239 @@
+"""W&B callback for lightgbm.
+
+Really simple callback to get logging for each tree
+
+Example usage:
+
+param_list = [("eta", 0.08), ("max_depth", 6), ("subsample", 0.8), ("colsample_bytree", 0.8), ("alpha", 8), ("num_class", 10)]
+config.update(dict(param_list))
+lgb = lgb.train(param_list, d_train, callbacks=[wandb_callback()])
+"""
+
+from pathlib import Path
+from typing import TYPE_CHECKING, Callable
+
+import lightgbm # type: ignore
+from lightgbm import Booster
+
+import wandb
+from wandb.sdk.lib import telemetry as wb_telemetry
+
+MINIMIZE_METRICS = [
+ "l1",
+ "l2",
+ "rmse",
+ "mape",
+ "huber",
+ "fair",
+ "poisson",
+ "gamma",
+ "binary_logloss",
+]
+
+MAXIMIZE_METRICS = ["map", "auc", "average_precision"]
+
+
+if TYPE_CHECKING:
+ from typing import Any, Dict, List, NamedTuple, Tuple, Union
+
+ # Note: upstream lightgbm has this defined incorrectly
+ _EvalResultTuple = Union[
+ Tuple[str, str, float, bool], Tuple[str, str, float, bool, float]
+ ]
+
+ class CallbackEnv(NamedTuple):
+ model: Any
+ params: Dict
+ iteration: int
+ begin_interation: int
+ end_iteration: int
+ evaluation_result_list: List[_EvalResultTuple]
+
+
+def _define_metric(data: str, metric_name: str) -> None:
+ """Capture model performance at the best step.
+
+ instead of the last step, of training in your `wandb.summary`
+ """
+ if "loss" in str.lower(metric_name):
+ wandb.define_metric(f"{data}_{metric_name}", summary="min")
+ elif str.lower(metric_name) in MINIMIZE_METRICS:
+ wandb.define_metric(f"{data}_{metric_name}", summary="min")
+ elif str.lower(metric_name) in MAXIMIZE_METRICS:
+ wandb.define_metric(f"{data}_{metric_name}", summary="max")
+
+
+def _checkpoint_artifact(
+ model: "Booster", iteration: int, aliases: "List[str]"
+) -> None:
+ """Upload model checkpoint as W&B artifact."""
+ # NOTE: type ignore required because wandb.run is improperly inferred as None type
+ model_name = f"model_{wandb.run.id}" # type: ignore
+ model_path = Path(wandb.run.dir) / f"model_ckpt_{iteration}.txt" # type: ignore
+
+ model.save_model(model_path, num_iteration=iteration)
+
+ model_artifact = wandb.Artifact(name=model_name, type="model")
+ model_artifact.add_file(str(model_path))
+ wandb.log_artifact(model_artifact, aliases=aliases)
+
+
+def _log_feature_importance(model: "Booster") -> None:
+ """Log feature importance."""
+ feat_imps = model.feature_importance()
+ feats = model.feature_name()
+ fi_data = [[feat, feat_imp] for feat, feat_imp in zip(feats, feat_imps)]
+ table = wandb.Table(data=fi_data, columns=["Feature", "Importance"])
+ wandb.log(
+ {
+ "Feature Importance": wandb.plot.bar(
+ table, "Feature", "Importance", title="Feature Importance"
+ )
+ },
+ commit=False,
+ )
+
+
+class _WandbCallback:
+ """Internal class to handle `wandb_callback` logic.
+
+ This callback is adapted form the LightGBM's `_RecordEvaluationCallback`.
+ """
+
+ def __init__(self, log_params: bool = True, define_metric: bool = True) -> None:
+ self.order = 20
+ self.before_iteration = False
+ self.log_params = log_params
+ self.define_metric_bool = define_metric
+
+ def _init(self, env: "CallbackEnv") -> None:
+ with wb_telemetry.context() as tel:
+ tel.feature.lightgbm_wandb_callback = True
+
+ # log the params as W&B config.
+ if self.log_params:
+ wandb.config.update(env.params)
+
+ # use `define_metric` to set the wandb summary to the best metric value.
+ for item in env.evaluation_result_list:
+ if self.define_metric_bool:
+ if len(item) == 4:
+ data_name, eval_name = item[:2]
+ _define_metric(data_name, eval_name)
+ else:
+ data_name, eval_name = item[1].split()
+ _define_metric(data_name, f"{eval_name}-mean")
+ _define_metric(data_name, f"{eval_name}-stdv")
+
+ def __call__(self, env: "CallbackEnv") -> None:
+ if env.iteration == env.begin_iteration: # type: ignore
+ self._init(env)
+
+ for item in env.evaluation_result_list:
+ if len(item) == 4:
+ data_name, eval_name, result = item[:3]
+ wandb.log(
+ {data_name + "_" + eval_name: result},
+ commit=False,
+ )
+ else:
+ data_name, eval_name = item[1].split()
+ res_mean = item[2]
+ res_stdv = item[4]
+ wandb.log(
+ {
+ data_name + "_" + eval_name + "-mean": res_mean,
+ data_name + "_" + eval_name + "-stdv": res_stdv,
+ },
+ commit=False,
+ )
+
+ # call `commit=True` to log the data as a single W&B step.
+ wandb.log({"iteration": env.iteration}, commit=True)
+
+
+def wandb_callback(log_params: bool = True, define_metric: bool = True) -> Callable:
+ """Automatically integrates LightGBM with wandb.
+
+ Args:
+ log_params: (boolean) if True (default) logs params passed to lightgbm.train as W&B config
+ define_metric: (boolean) if True (default) capture model performance at the best step, instead of the last step, of training in your `wandb.summary`
+
+ Passing `wandb_callback` to LightGBM will:
+ - log params passed to lightgbm.train as W&B config (default).
+ - log evaluation metrics collected by LightGBM, such as rmse, accuracy etc to Weights & Biases
+ - Capture the best metric in `wandb.summary` when `define_metric=True` (default).
+
+ Use `log_summary` as an extension of this callback.
+
+ Example:
+ ```python
+ params = {
+ "boosting_type": "gbdt",
+ "objective": "regression",
+ }
+ gbm = lgb.train(
+ params,
+ lgb_train,
+ num_boost_round=10,
+ valid_sets=lgb_eval,
+ valid_names=("validation"),
+ callbacks=[wandb_callback()],
+ )
+ ```
+ """
+ return _WandbCallback(log_params, define_metric)
+
+
+def log_summary(
+ model: Booster, feature_importance: bool = True, save_model_checkpoint: bool = False
+) -> None:
+ """Log useful metrics about lightgbm model after training is done.
+
+ Args:
+ model: (Booster) is an instance of lightgbm.basic.Booster.
+ feature_importance: (boolean) if True (default), logs the feature importance plot.
+ save_model_checkpoint: (boolean) if True saves the best model and upload as W&B artifacts.
+
+ Using this along with `wandb_callback` will:
+
+ - log `best_iteration` and `best_score` as `wandb.summary`.
+ - log feature importance plot.
+ - save and upload your best trained model to Weights & Biases Artifacts (when `save_model_checkpoint = True`)
+
+ Example:
+ ```python
+ params = {
+ "boosting_type": "gbdt",
+ "objective": "regression",
+ }
+ gbm = lgb.train(
+ params,
+ lgb_train,
+ num_boost_round=10,
+ valid_sets=lgb_eval,
+ valid_names=("validation"),
+ callbacks=[wandb_callback()],
+ )
+
+ log_summary(gbm)
+ ```
+ """
+ if wandb.run is None:
+ raise wandb.Error("You must call wandb.init() before WandbCallback()")
+
+ if not isinstance(model, Booster):
+ raise wandb.Error("Model should be an instance of lightgbm.basic.Booster")
+
+ wandb.run.summary["best_iteration"] = model.best_iteration
+ wandb.run.summary["best_score"] = model.best_score
+
+ # Log feature importance
+ if feature_importance:
+ _log_feature_importance(model)
+
+ if save_model_checkpoint:
+ _checkpoint_artifact(model, model.best_iteration, aliases=["best"])
+
+ with wb_telemetry.context() as tel:
+ tel.feature.lightgbm_log_summary = True
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/lightning/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/lightning/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/lightning/fabric/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/lightning/fabric/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..eff7554e1131034c637c8cfef591756211b8a898
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/lightning/fabric/__init__.py
@@ -0,0 +1,3 @@
+from wandb.integration.lightning.fabric.logger import WandbLogger
+
+__all__ = ("WandbLogger",)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/lightning/fabric/logger.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/lightning/fabric/logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..21e326241c75ecfedb2ceb5cd8e39b0bc1c0b0f2
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/lightning/fabric/logger.py
@@ -0,0 +1,763 @@
+import os
+from argparse import Namespace
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Dict, List, Literal, Mapping, Optional, Union
+
+from packaging import version
+from typing_extensions import override
+
+import wandb
+from wandb import Artifact
+from wandb.sdk.lib import telemetry
+
+try:
+ import lightning
+ import torch.nn as nn
+ from lightning.fabric.loggers.logger import Logger, rank_zero_experiment
+ from lightning.fabric.utilities.exceptions import MisconfigurationException
+ from lightning.fabric.utilities.logger import (
+ _add_prefix,
+ _convert_params,
+ _sanitize_callable_params,
+ )
+ from lightning.fabric.utilities.rank_zero import rank_zero_only, rank_zero_warn
+ from lightning.fabric.utilities.types import _PATH
+ from torch import Tensor
+ from torch.nn import Module
+
+ if version.parse(lightning.__version__) > version.parse("2.1.3"):
+ wandb.termwarn(
+ """This integration is tested and supported for lightning Fabric 2.1.3.
+ Please report any issues to https://github.com/wandb/wandb/issues with the tag `lightning-fabric`.""",
+ repeat=False,
+ )
+
+ if TYPE_CHECKING:
+ from lightning.pytorch.callbacks.model_checkpoint import ModelCheckpoint
+
+except ImportError as e:
+ wandb.Error(e)
+
+
+class WandbLogger(Logger):
+ r"""Log using `Weights and Biases `_.
+
+ **Installation and set-up**
+
+ Install with pip:
+
+ .. code-block:: bash
+
+ pip install wandb
+
+ Create a `WandbLogger` instance:
+
+ .. code-block:: python
+
+ from lightning.fabric.loggers import WandbLogger
+
+ wandb_logger = WandbLogger(project="MNIST")
+
+ Pass the logger instance to the `Trainer`:
+
+ .. code-block:: python
+
+ trainer = Trainer(logger=wandb_logger)
+
+ A new W&B run will be created when training starts if you have not created one manually before with `wandb.init()`.
+
+ **Log metrics**
+
+ Log from :class:`~lightning.pytorch.core.LightningModule`:
+
+ .. code-block:: python
+
+ class LitModule(LightningModule):
+ def training_step(self, batch, batch_idx):
+ self.log("train/loss", loss)
+
+ Use directly wandb module:
+
+ .. code-block:: python
+
+ wandb.log({"train/loss": loss})
+
+ **Log hyper-parameters**
+
+ Save :class:`~lightning.pytorch.core.LightningModule` parameters:
+
+ .. code-block:: python
+
+ class LitModule(LightningModule):
+ def __init__(self, *args, **kwarg):
+ self.save_hyperparameters()
+
+ Add other config parameters:
+
+ .. code-block:: python
+
+ # add one parameter
+ wandb_logger.experiment.config["key"] = value
+
+ # add multiple parameters
+ wandb_logger.experiment.config.update({key1: val1, key2: val2})
+
+ # use directly wandb module
+ wandb.config["key"] = value
+ wandb.config.update()
+
+ **Log gradients, parameters and model topology**
+
+ Call the `watch` method for automatically tracking gradients:
+
+ .. code-block:: python
+
+ # log gradients and model topology
+ wandb_logger.watch(model)
+
+ # log gradients, parameter histogram and model topology
+ wandb_logger.watch(model, log="all")
+
+ # change log frequency of gradients and parameters (100 steps by default)
+ wandb_logger.watch(model, log_freq=500)
+
+ # do not log graph (in case of errors)
+ wandb_logger.watch(model, log_graph=False)
+
+ The `watch` method adds hooks to the model which can be removed at the end of training:
+
+ .. code-block:: python
+
+ wandb_logger.experiment.unwatch(model)
+
+ **Log model checkpoints**
+
+ Log model checkpoints at the end of training:
+
+ .. code-block:: python
+
+ wandb_logger = WandbLogger(log_model=True)
+
+ Log model checkpoints as they get created during training:
+
+ .. code-block:: python
+
+ wandb_logger = WandbLogger(log_model="all")
+
+ Custom checkpointing can be set up through :class:`~lightning.pytorch.callbacks.ModelCheckpoint`:
+
+ .. code-block:: python
+
+ # log model only if `val_accuracy` increases
+ wandb_logger = WandbLogger(log_model="all")
+ checkpoint_callback = ModelCheckpoint(monitor="val_accuracy", mode="max")
+ trainer = Trainer(logger=wandb_logger, callbacks=[checkpoint_callback])
+
+ `latest` and `best` aliases are automatically set to easily retrieve a model checkpoint:
+
+ .. code-block:: python
+
+ # reference can be retrieved in artifacts panel
+ # "VERSION" can be a version (ex: "v2") or an alias ("latest or "best")
+ checkpoint_reference = "USER/PROJECT/MODEL-RUN_ID:VERSION"
+
+ # download checkpoint locally (if not already cached)
+ run = wandb.init(project="MNIST")
+ artifact = run.use_artifact(checkpoint_reference, type="model")
+ artifact_dir = artifact.download()
+
+ # load checkpoint
+ model = LitModule.load_from_checkpoint(Path(artifact_dir) / "model.ckpt")
+
+ **Log media**
+
+ Log text with:
+
+ .. code-block:: python
+
+ # using columns and data
+ columns = ["input", "label", "prediction"]
+ data = [["cheese", "english", "english"], ["fromage", "french", "spanish"]]
+ wandb_logger.log_text(key="samples", columns=columns, data=data)
+
+ # using a pandas DataFrame
+ wandb_logger.log_text(key="samples", dataframe=my_dataframe)
+
+ Log images with:
+
+ .. code-block:: python
+
+ # using tensors, numpy arrays or PIL images
+ wandb_logger.log_image(key="samples", images=[img1, img2])
+
+ # adding captions
+ wandb_logger.log_image(
+ key="samples", images=[img1, img2], caption=["tree", "person"]
+ )
+
+ # using file path
+ wandb_logger.log_image(key="samples", images=["img_1.jpg", "img_2.jpg"])
+
+ More arguments can be passed for logging segmentation masks and bounding boxes. Refer to
+ `Image Overlays documentation `_.
+
+ **Log Tables**
+
+ `W&B Tables `_ can be used to log,
+ query and analyze tabular data.
+
+ They support any type of media (text, image, video, audio, molecule, html, etc) and are great for storing,
+ understanding and sharing any form of data, from datasets to model predictions.
+
+ .. code-block:: python
+
+ columns = ["caption", "image", "sound"]
+ data = [
+ ["cheese", wandb.Image(img_1), wandb.Audio(snd_1)],
+ ["wine", wandb.Image(img_2), wandb.Audio(snd_2)],
+ ]
+ wandb_logger.log_table(key="samples", columns=columns, data=data)
+
+
+ **Downloading and Using Artifacts**
+
+ To download an artifact without starting a run, call the ``download_artifact``
+ function on the class:
+
+ .. code-block:: python
+
+ artifact_dir = wandb_logger.download_artifact(artifact="path/to/artifact")
+
+ To download an artifact and link it to an ongoing run call the ``download_artifact``
+ function on the logger instance:
+
+ .. code-block:: python
+
+ class MyModule(LightningModule):
+ def any_lightning_module_function_or_hook(self):
+ self.logger.download_artifact(artifact="path/to/artifact")
+
+ To link an artifact from a previous run you can use ``use_artifact`` function:
+
+ .. code-block:: python
+
+ wandb_logger.use_artifact(artifact="path/to/artifact")
+
+ See Also:
+ - `Demo in Google Colab `__ with hyperparameter search and model logging
+ - `W&B Documentation `__
+
+ Args:
+ name: Display name for the run.
+ save_dir: Path where data is saved.
+ version: Sets the version, mainly used to resume a previous run.
+ offline: Run offline (data can be streamed later to wandb servers).
+ dir: Same as save_dir.
+ id: Same as version.
+ anonymous: Enables or explicitly disables anonymous logging.
+ project: The name of the project to which this run will belong. If not set, the environment variable
+ `WANDB_PROJECT` will be used as a fallback. If both are not set, it defaults to ``'lightning_logs'``.
+ log_model: Log checkpoints created by :class:`~lightning.pytorch.callbacks.ModelCheckpoint`
+ as W&B artifacts. `latest` and `best` aliases are automatically set.
+
+ * if ``log_model == 'all'``, checkpoints are logged during training.
+ * if ``log_model == True``, checkpoints are logged at the end of training, except when
+ `~lightning.pytorch.callbacks.ModelCheckpoint.save_top_k` ``== -1``
+ which also logs every checkpoint during training.
+ * if ``log_model == False`` (default), no checkpoint is logged.
+
+ prefix: A string to put at the beginning of metric keys.
+ experiment: WandB experiment object. Automatically set when creating a run.
+ checkpoint_name: Name of the model checkpoint artifact being logged.
+ log_checkpoint_on: When to log model checkpoints as W&B artifacts. Only used if ``log_model`` is ``True``.
+ Options: ``"success"``, ``"all"``. Default: ``"success"``.
+ \**kwargs: Arguments passed to :func:`wandb.init` like `entity`, `group`, `tags`, etc.
+
+ Raises:
+ ModuleNotFoundError:
+ If required WandB package is not installed on the device.
+ MisconfigurationException:
+ If both ``log_model`` and ``offline`` is set to ``True``.
+
+ """
+
+ LOGGER_JOIN_CHAR = "-"
+
+ def __init__(
+ self,
+ name: Optional[str] = None,
+ save_dir: _PATH = ".",
+ version: Optional[str] = None,
+ offline: bool = False,
+ dir: Optional[_PATH] = None,
+ id: Optional[str] = None,
+ anonymous: Optional[bool] = None,
+ project: Optional[str] = None,
+ log_model: Union[Literal["all"], bool] = False,
+ experiment: Optional["wandb.Run"] = None,
+ prefix: str = "",
+ checkpoint_name: Optional[str] = None,
+ log_checkpoint_on: Union[Literal["success"], Literal["all"]] = "success",
+ **kwargs: Any,
+ ) -> None:
+ if offline and log_model:
+ raise MisconfigurationException(
+ f"Providing log_model={log_model} and offline={offline} is an invalid configuration"
+ " since model checkpoints cannot be uploaded in offline mode.\n"
+ "Hint: Set `offline=False` to log your model."
+ )
+
+ super().__init__()
+ self._offline = offline
+ self._log_model = log_model
+ self._prefix = prefix
+ self._experiment = experiment
+ self._logged_model_time: Dict[str, float] = {}
+ self._checkpoint_callback: Optional[ModelCheckpoint] = None
+
+ # paths are processed as strings
+ if save_dir is not None:
+ save_dir = os.fspath(save_dir)
+ elif dir is not None:
+ dir = os.fspath(dir)
+
+ project = project or os.environ.get("WANDB_PROJECT", "lightning_fabric_logs")
+
+ # set wandb init arguments
+ self._wandb_init: Dict[str, Any] = {
+ "name": name,
+ "project": project,
+ "dir": save_dir or dir,
+ "id": version or id,
+ "resume": "allow",
+ "anonymous": ("allow" if anonymous else None),
+ }
+ self._wandb_init.update(**kwargs)
+ # extract parameters
+ self._project = self._wandb_init.get("project")
+ self._save_dir = self._wandb_init.get("dir")
+ self._name = self._wandb_init.get("name")
+ self._id = self._wandb_init.get("id")
+ self._checkpoint_name = checkpoint_name
+ self._log_checkpoint_on = log_checkpoint_on
+
+ def __getstate__(self) -> Dict[str, Any]:
+ # Hack: If the 'spawn' launch method is used, the logger will get pickled and this `__getstate__` gets called.
+ # We create an experiment here in the main process, and attach to it in the worker process.
+ # Using wandb-service, we persist the same experiment even if multiple `Trainer.fit/test/validate` calls
+ # are made.
+ _ = self.experiment
+
+ state = self.__dict__.copy()
+ # args needed to reload correct experiment
+ if self._experiment is not None:
+ state["_id"] = getattr(self._experiment, "id", None)
+ state["_attach_id"] = getattr(self._experiment, "_attach_id", None)
+ state["_name"] = self._experiment.name
+
+ # cannot be pickled
+ state["_experiment"] = None
+ return state
+
+ @property
+ @rank_zero_experiment
+ def experiment(self) -> "wandb.Run":
+ r"""Actual wandb object.
+
+ To use wandb features in your :class:`~lightning.pytorch.core.LightningModule`, do the
+ following.
+
+ Example::
+
+ .. code-block:: python
+
+ self.logger.experiment.some_wandb_function()
+
+ """
+ if self._experiment is None:
+ if self._offline:
+ os.environ["WANDB_MODE"] = "dryrun"
+
+ attach_id = getattr(self, "_attach_id", None)
+ if wandb.run is not None:
+ # wandb process already created in this instance
+ rank_zero_warn(
+ "There is a wandb run already in progress and newly created instances of `WandbLogger` will reuse"
+ " this run. If this is not desired, call `wandb.finish()` before instantiating `WandbLogger`."
+ )
+ self._experiment = wandb.run
+ elif attach_id is not None and hasattr(wandb, "_attach"):
+ # attach to wandb process referenced
+ self._experiment = wandb._attach(attach_id)
+ else:
+ # create new wandb process
+ self._experiment = wandb.init(**self._wandb_init)
+
+ # define default x-axis
+ if isinstance(self._experiment, wandb.Run) and getattr(
+ self._experiment, "define_metric", None
+ ):
+ self._experiment.define_metric("trainer/global_step")
+ self._experiment.define_metric(
+ "*", step_metric="trainer/global_step", step_sync=True
+ )
+
+ self._experiment._label(repo="lightning_fabric_logger") # pylint: disable=protected-access
+ with telemetry.context(run=self._experiment) as tel:
+ tel.feature.lightning_fabric_logger = True
+ return self._experiment
+
+ def watch(
+ self,
+ model: nn.Module,
+ log: str = "gradients",
+ log_freq: int = 100,
+ log_graph: bool = True,
+ ) -> None:
+ self.experiment.watch(model, log=log, log_freq=log_freq, log_graph=log_graph)
+
+ @override
+ @rank_zero_only
+ def log_hyperparams(self, params: Union[Dict[str, Any], Namespace]) -> None: # type: ignore[override]
+ params = _convert_params(params)
+ params = _sanitize_callable_params(params)
+ self.experiment.config.update(params, allow_val_change=True)
+
+ @override
+ @rank_zero_only
+ def log_metrics(
+ self, metrics: Mapping[str, float], step: Optional[int] = None
+ ) -> None:
+ assert rank_zero_only.rank == 0, "experiment tried to log from global_rank != 0"
+
+ metrics = _add_prefix(metrics, self._prefix, self.LOGGER_JOIN_CHAR)
+ if step is not None:
+ self.experiment.log(dict(metrics, **{"trainer/global_step": step}))
+ else:
+ self.experiment.log(metrics)
+
+ @rank_zero_only
+ def log_table(
+ self,
+ key: str,
+ columns: Optional[List[str]] = None,
+ data: Optional[List[List[Any]]] = None,
+ dataframe: Any = None,
+ step: Optional[int] = None,
+ ) -> None:
+ """Log a Table containing any object type (text, image, audio, video, molecule, html, etc).
+
+ Can be defined either with `columns` and `data` or with `dataframe`.
+
+ """
+ metrics = {key: wandb.Table(columns=columns, data=data, dataframe=dataframe)}
+ self.log_metrics(metrics, step)
+
+ @rank_zero_only
+ def log_text(
+ self,
+ key: str,
+ columns: Optional[List[str]] = None,
+ data: Optional[List[List[str]]] = None,
+ dataframe: Any = None,
+ step: Optional[int] = None,
+ ) -> None:
+ """Log text as a Table.
+
+ Can be defined either with `columns` and `data` or with `dataframe`.
+
+ """
+ self.log_table(key, columns, data, dataframe, step)
+
+ @rank_zero_only
+ def log_html(
+ self, key: str, htmls: List[Any], step: Optional[int] = None, **kwargs: Any
+ ) -> None:
+ """Log html files.
+
+ Optional kwargs are lists passed to each html (ex: inject).
+
+ """
+ if not isinstance(htmls, list):
+ raise TypeError(f'Expected a list as "htmls", found {type(htmls)}')
+ n = len(htmls)
+ for k, v in kwargs.items():
+ if len(v) != n:
+ raise ValueError(f"Expected {n} items but only found {len(v)} for {k}")
+ kwarg_list = [{k: kwargs[k][i] for k in kwargs} for i in range(n)]
+
+ metrics = {
+ key: [wandb.Html(html, **kwarg) for html, kwarg in zip(htmls, kwarg_list)]
+ }
+ self.log_metrics(metrics, step) # type: ignore[arg-type]
+
+ @rank_zero_only
+ def log_image(
+ self, key: str, images: List[Any], step: Optional[int] = None, **kwargs: Any
+ ) -> None:
+ """Log images (tensors, numpy arrays, PIL Images or file paths).
+
+ Optional kwargs are lists passed to each image (ex: caption, masks, boxes).
+
+ """
+ if not isinstance(images, list):
+ raise TypeError(f'Expected a list as "images", found {type(images)}')
+ n = len(images)
+ for k, v in kwargs.items():
+ if len(v) != n:
+ raise ValueError(f"Expected {n} items but only found {len(v)} for {k}")
+ kwarg_list = [{k: kwargs[k][i] for k in kwargs} for i in range(n)]
+
+ metrics = {
+ key: [wandb.Image(img, **kwarg) for img, kwarg in zip(images, kwarg_list)]
+ }
+ self.log_metrics(metrics, step) # type: ignore[arg-type]
+
+ @rank_zero_only
+ def log_audio(
+ self, key: str, audios: List[Any], step: Optional[int] = None, **kwargs: Any
+ ) -> None:
+ r"""Log audios (numpy arrays, or file paths).
+
+ Args:
+ key: The key to be used for logging the audio files
+ audios: The list of audio file paths, or numpy arrays to be logged
+ step: The step number to be used for logging the audio files
+ \**kwargs: Optional kwargs are lists passed to each ``Wandb.Audio`` instance (ex: caption, sample_rate).
+
+ Optional kwargs are lists passed to each audio (ex: caption, sample_rate).
+
+ """
+ if not isinstance(audios, list):
+ raise TypeError(f'Expected a list as "audios", found {type(audios)}')
+ n = len(audios)
+ for k, v in kwargs.items():
+ if len(v) != n:
+ raise ValueError(f"Expected {n} items but only found {len(v)} for {k}")
+ kwarg_list = [{k: kwargs[k][i] for k in kwargs} for i in range(n)]
+
+ metrics = {
+ key: [
+ wandb.Audio(audio, **kwarg) for audio, kwarg in zip(audios, kwarg_list)
+ ]
+ }
+ self.log_metrics(metrics, step) # type: ignore[arg-type]
+
+ @rank_zero_only
+ def log_video(
+ self, key: str, videos: List[Any], step: Optional[int] = None, **kwargs: Any
+ ) -> None:
+ """Log videos (numpy arrays, or file paths).
+
+ Args:
+ key: The key to be used for logging the video files
+ videos: The list of video file paths, or numpy arrays to be logged
+ step: The step number to be used for logging the video files
+ **kwargs: Optional kwargs are lists passed to each Wandb.Video instance (ex: caption, fps, format).
+
+ Optional kwargs are lists passed to each video (ex: caption, fps, format).
+
+ """
+ if not isinstance(videos, list):
+ raise TypeError(f'Expected a list as "videos", found {type(videos)}')
+ n = len(videos)
+ for k, v in kwargs.items():
+ if len(v) != n:
+ raise ValueError(f"Expected {n} items but only found {len(v)} for {k}")
+ kwarg_list = [{k: kwargs[k][i] for k in kwargs} for i in range(n)]
+
+ metrics = {
+ key: [
+ wandb.Video(video, **kwarg) for video, kwarg in zip(videos, kwarg_list)
+ ]
+ }
+ self.log_metrics(metrics, step) # type: ignore[arg-type]
+
+ @property
+ @override
+ def save_dir(self) -> Optional[str]:
+ """Gets the save directory.
+
+ Returns:
+ The path to the save directory.
+
+ """
+ return self._save_dir
+
+ @property
+ @override
+ def name(self) -> Optional[str]:
+ """The project name of this experiment.
+
+ Returns:
+ The name of the project the current experiment belongs to. This name is not the same as `wandb.Run`'s
+ name. To access wandb's internal experiment name, use ``logger.experiment.name`` instead.
+
+ """
+ return self._project
+
+ @property
+ @override
+ def version(self) -> Optional[str]:
+ """Gets the id of the experiment.
+
+ Returns:
+ The id of the experiment if the experiment exists else the id given to the constructor.
+
+ """
+ # don't create an experiment if we don't have one
+ return self._experiment.id if self._experiment else self._id
+
+ @property
+ def log_dir(self) -> Optional[str]:
+ """Gets the save directory.
+
+ Returns:
+ The path to the save directory.
+
+ """
+ return self.save_dir
+
+ @property
+ def group_separator(self) -> str:
+ """Return the default separator used by the logger to group the data into subfolders."""
+ return self.LOGGER_JOIN_CHAR
+
+ @property
+ def root_dir(self) -> Optional[str]:
+ """Return the root directory.
+
+ Return the root directory where all versions of an experiment get saved, or `None` if the logger does not
+ save data locally.
+ """
+ return self.save_dir.parent if self.save_dir else None
+
+ def log_graph(self, model: Module, input_array: Optional[Tensor] = None) -> None:
+ """Record model graph.
+
+ Args:
+ model: the model with an implementation of ``forward``.
+ input_array: input passes to `model.forward`
+
+ This is a noop function and does not perform any operation.
+ """
+ return
+
+ @override
+ def after_save_checkpoint(self, checkpoint_callback: "ModelCheckpoint") -> None:
+ # log checkpoints as artifacts
+ if (
+ self._log_model == "all"
+ or self._log_model is True
+ and checkpoint_callback.save_top_k == -1
+ ):
+ # TODO: Replace with new Fabric Checkpoints system
+ self._scan_and_log_pytorch_checkpoints(checkpoint_callback)
+ elif self._log_model is True:
+ self._checkpoint_callback = checkpoint_callback
+
+ @staticmethod
+ @rank_zero_only
+ def download_artifact(
+ artifact: str,
+ save_dir: Optional[_PATH] = None,
+ artifact_type: Optional[str] = None,
+ use_artifact: Optional[bool] = True,
+ ) -> str:
+ """Downloads an artifact from the wandb server.
+
+ Args:
+ artifact: The path of the artifact to download.
+ save_dir: The directory to save the artifact to.
+ artifact_type: The type of artifact to download.
+ use_artifact: Whether to add an edge between the artifact graph.
+
+ Returns:
+ The path to the downloaded artifact.
+
+ """
+ if wandb.run is not None and use_artifact:
+ artifact = wandb.run.use_artifact(artifact)
+ else:
+ api = wandb.Api()
+ artifact = api.artifact(artifact, type=artifact_type)
+
+ save_dir = None if save_dir is None else os.fspath(save_dir)
+ return artifact.download(root=save_dir)
+
+ def use_artifact(
+ self, artifact: str, artifact_type: Optional[str] = None
+ ) -> "Artifact":
+ """Logs to the wandb dashboard that the mentioned artifact is used by the run.
+
+ Args:
+ artifact: The path of the artifact.
+ artifact_type: The type of artifact being used.
+
+ Returns:
+ wandb Artifact object for the artifact.
+
+ """
+ return self.experiment.use_artifact(artifact, type=artifact_type)
+
+ @override
+ @rank_zero_only
+ def save(self) -> None:
+ """Save log data."""
+ self.experiment.log({}, commit=True)
+
+ @override
+ @rank_zero_only
+ def finalize(self, status: str) -> None:
+ if self._log_checkpoint_on == "success" and status != "success":
+ # Currently, checkpoints only get logged on success
+ return
+ # log checkpoints as artifacts
+ if (
+ self._checkpoint_callback
+ and self._experiment is not None
+ and self._log_checkpoint_on in ["success", "all"]
+ ):
+ self._scan_and_log_pytorch_checkpoints(self._checkpoint_callback)
+
+ def _scan_and_log_pytorch_checkpoints(
+ self, checkpoint_callback: "ModelCheckpoint"
+ ) -> None:
+ from lightning.pytorch.loggers.utilities import _scan_checkpoints
+
+ # get checkpoints to be saved with associated score
+ checkpoints = _scan_checkpoints(checkpoint_callback, self._logged_model_time)
+
+ # log iteratively all new checkpoints
+ for t, p, s, _ in checkpoints:
+ metadata = {
+ "score": s.item() if isinstance(s, Tensor) else s,
+ "original_filename": Path(p).name,
+ checkpoint_callback.__class__.__name__: {
+ k: getattr(checkpoint_callback, k)
+ for k in [
+ "monitor",
+ "mode",
+ "save_last",
+ "save_top_k",
+ "save_weights_only",
+ "_every_n_train_steps",
+ ]
+ # ensure it does not break if `ModelCheckpoint` args change
+ if hasattr(checkpoint_callback, k)
+ },
+ }
+ if not self._checkpoint_name:
+ self._checkpoint_name = f"model-{self.experiment.id}"
+ artifact = wandb.Artifact(
+ name=self._checkpoint_name, type="model", metadata=metadata
+ )
+ artifact.add_file(p, name="model.ckpt")
+ aliases = (
+ ["latest", "best"]
+ if p == checkpoint_callback.best_model_path
+ else ["latest"]
+ )
+ self.experiment.log_model(artifact, aliases=aliases)
+ # remember logged models - timestamp needed in case filename didn't change (lastkckpt or custom name)
+ self._logged_model_time[p] = t
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/metaflow/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/metaflow/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a7dc33daec78edbe8e6c91dc5f1f0b468acabbb7
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/metaflow/__init__.py
@@ -0,0 +1,9 @@
+"""W&B Integration for Metaflow.
+
+Defines a custom step and flow decorator `wandb_log` that automatically logs
+flow parameters and artifacts to W&B.
+"""
+
+from .metaflow import wandb_log, wandb_track, wandb_use
+
+__all__ = ["wandb_log", "wandb_track", "wandb_use"]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/metaflow/data_pandas.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/metaflow/data_pandas.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ad5528152ebed557341df0dc8a48d4eea2acde0
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/metaflow/data_pandas.py
@@ -0,0 +1,74 @@
+"""Support for Pandas datatypes.
+
+May raise MissingDependencyError on import.
+"""
+
+from __future__ import annotations
+
+from typing_extensions import Any, TypeIs
+
+import wandb
+
+from . import errors
+
+try:
+ import pandas as pd
+except ImportError as e:
+ warning = (
+ "`pandas` not installed >>"
+ " @wandb_log(datasets=True) may not auto log your dataset!"
+ )
+ raise errors.MissingDependencyError(warning=warning) from e
+
+
+def is_dataframe(data: Any) -> TypeIs[pd.DataFrame]:
+ """Returns whether the data is a Pandas DataFrame."""
+ return isinstance(data, pd.DataFrame)
+
+
+def use_dataframe(
+ name: str,
+ run: wandb.Run | None,
+ testing: bool = False,
+) -> str | None:
+ """Log a dependency on a DataFrame input.
+
+ Args:
+ name: Name of the input.
+ run: The run to update.
+ testing: True in unit tests.
+ """
+ if testing:
+ return "datasets"
+ assert run
+
+ wandb.termlog(f"Using artifact: {name} (Pandas DataFrame)")
+ run.use_artifact(f"{name}:latest")
+ return None
+
+
+def track_dataframe(
+ name: str,
+ data: pd.DataFrame,
+ run: wandb.Run | None,
+ testing: bool = False,
+) -> str | None:
+ """Log a DataFrame output as an artifact.
+
+ Args:
+ name: The output's name.
+ data: The output's value.
+ run: The run to update.
+ testing: True in unit tests.
+ """
+ if testing:
+ return "pd.DataFrame"
+ assert run
+
+ artifact = wandb.Artifact(name, type="dataset")
+ with artifact.new_file(f"{name}.parquet", "wb") as f:
+ data.to_parquet(f, engine="pyarrow")
+
+ wandb.termlog(f"Logging artifact: {name} (Pandas DataFrame)")
+ run.log_artifact(artifact)
+ return None
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/metaflow/data_pytorch.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/metaflow/data_pytorch.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef2977ea7e2343aa7f6dcb23a622845ff6692729
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/metaflow/data_pytorch.py
@@ -0,0 +1,75 @@
+"""Support for PyTorch datatypes.
+
+May raise MissingDependencyError on import.
+"""
+
+from __future__ import annotations
+
+from typing_extensions import Any, TypeIs
+
+import wandb
+
+from . import errors
+
+try:
+ import torch
+ import torch.nn as nn
+except ImportError as e:
+ warning = (
+ "`torch` (PyTorch) not installed >>"
+ " @wandb_log(models=True) may not auto log your model!"
+ )
+ raise errors.MissingDependencyError(warning=warning) from e
+
+
+def is_nn_module(data: Any) -> TypeIs[nn.Module]:
+ """Returns whether the data is a PyTorch nn.Module."""
+ return isinstance(data, nn.Module)
+
+
+def use_nn_module(
+ name: str,
+ run: wandb.Run | None,
+ testing: bool = False,
+) -> str | None:
+ """Log a dependency on a PyTorch model input.
+
+ Args:
+ name: Name of the input.
+ run: The run to update.
+ testing: True in unit tests.
+ """
+ if testing:
+ return "models"
+ assert run
+
+ wandb.termlog(f"Using artifact: {name} (PyTorch nn.Module)")
+ run.use_artifact(f"{name}:latest")
+ return None
+
+
+def track_nn_module(
+ name: str,
+ data: nn.Module,
+ run: wandb.Run | None,
+ testing: bool = False,
+) -> str | None:
+ """Log a PyTorch model output as an artifact.
+
+ Args:
+ name: The output's name.
+ data: The output's value.
+ run: The run to update.
+ testing: True in unit tests.
+ """
+ if testing:
+ return "nn.Module"
+ assert run
+
+ artifact = wandb.Artifact(name, type="model")
+ with artifact.new_file(f"{name}.pkl", "wb") as f:
+ torch.save(data, f)
+
+ wandb.termlog(f"Logging artifact: {name} (PyTorch nn.Module)")
+ run.log_artifact(artifact)
+ return None
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/metaflow/data_sklearn.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/metaflow/data_sklearn.py
new file mode 100644
index 0000000000000000000000000000000000000000..98fe4576f1903ea821372f2758ef499fb7e5e9a0
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/metaflow/data_sklearn.py
@@ -0,0 +1,76 @@
+"""Support for sklearn datatypes.
+
+May raise MissingDependencyError on import.
+"""
+
+from __future__ import annotations
+
+import pickle
+
+from typing_extensions import Any, TypeIs
+
+import wandb
+
+from . import errors
+
+try:
+ from sklearn.base import BaseEstimator
+except ImportError as e:
+ warning = (
+ "`sklearn` not installed >>"
+ " @wandb_log(models=True) may not auto log your model!"
+ )
+ raise errors.MissingDependencyError(warning=warning) from e
+
+
+def is_estimator(data: Any) -> TypeIs[BaseEstimator]:
+ """Returns whether the data is an sklearn BaseEstimator."""
+ return isinstance(data, BaseEstimator)
+
+
+def use_estimator(
+ name: str,
+ run: wandb.Run | None,
+ testing: bool = False,
+) -> str | None:
+ """Log a dependency on an sklearn estimator.
+
+ Args:
+ name: Name of the input.
+ run: The run to update.
+ testing: True in unit tests.
+ """
+ if testing:
+ return "models"
+ assert run
+
+ wandb.termlog(f"Using artifact: {name} (sklearn BaseEstimator)")
+ run.use_artifact(f"{name}:latest")
+ return None
+
+
+def track_estimator(
+ name: str,
+ data: BaseEstimator,
+ run: wandb.Run | None,
+ testing: bool = False,
+) -> str | None:
+ """Log an sklearn estimator output as an artifact.
+
+ Args:
+ name: The output's name.
+ data: The output's value.
+ run: The run to update.
+ testing: True in unit tests.
+ """
+ if testing:
+ return "BaseEstimator"
+ assert run
+
+ artifact = wandb.Artifact(name, type="model")
+ with artifact.new_file(f"{name}.pkl", "wb") as f:
+ pickle.dump(data, f)
+
+ wandb.termlog(f"Logging artifact: {name} (sklearn BaseEstimator)")
+ run.log_artifact(artifact)
+ return None
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/metaflow/errors.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/metaflow/errors.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b0a3ae962cdadde195fa31c6efb4f3d0cc07d5b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/metaflow/errors.py
@@ -0,0 +1,13 @@
+import wandb
+
+
+class MissingDependencyError(Exception):
+ """An optional dependency is missing."""
+
+ def __init__(self, *args: object, warning: str) -> None:
+ super().__init__(*args)
+ self._wb_warning = warning
+
+ def warn(self) -> None:
+ """Print a warning for the problem."""
+ wandb.termwarn(self._wb_warning)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/metaflow/metaflow.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/metaflow/metaflow.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ce970d17636ce5417e81fbf9bb5b3b0a6553bd1
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/metaflow/metaflow.py
@@ -0,0 +1,327 @@
+import inspect
+import pickle
+from functools import wraps
+from pathlib import Path
+from typing import Optional, Union
+
+import wandb
+from wandb.sdk.lib import telemetry as wb_telemetry
+
+from . import errors
+
+try:
+ from metaflow import current
+except ImportError as e:
+ raise Exception(
+ "Error: `metaflow` not installed >> This integration requires metaflow!"
+ " To fix, please `pip install -Uqq metaflow`"
+ ) from e
+
+
+try:
+ from . import data_pandas
+except errors.MissingDependencyError as e:
+ e.warn()
+ data_pandas = None
+
+try:
+ from . import data_pytorch
+except errors.MissingDependencyError as e:
+ e.warn()
+ data_pytorch = None
+
+try:
+ from . import data_sklearn
+except errors.MissingDependencyError as e:
+ e.warn()
+ data_sklearn = None
+
+
+class ArtifactProxy:
+ def __init__(self, flow):
+ # do this to avoid recursion problem with __setattr__
+ self.__dict__.update(
+ {
+ "flow": flow,
+ "inputs": {},
+ "outputs": {},
+ "base": set(dir(flow)),
+ "params": {p: getattr(flow, p) for p in current.parameter_names},
+ }
+ )
+
+ def __setattr__(self, key, val):
+ self.outputs[key] = val
+ return setattr(self.flow, key, val)
+
+ def __getattr__(self, key):
+ if key not in self.base and key not in self.outputs:
+ self.inputs[key] = getattr(self.flow, key)
+ return getattr(self.flow, key)
+
+
+def _track_scalar(
+ name: str,
+ data: Union[dict, list, set, str, int, float, bool],
+ run,
+ testing: bool = False,
+) -> Optional[str]:
+ if testing:
+ return "scalar"
+
+ run.log({name: data})
+ return None
+
+
+def _track_path(
+ name: str,
+ data: Path,
+ run,
+ testing: bool = False,
+) -> Optional[str]:
+ if testing:
+ return "Path"
+
+ artifact = wandb.Artifact(name, type="dataset")
+ if data.is_dir():
+ artifact.add_dir(data)
+ elif data.is_file():
+ artifact.add_file(data)
+ run.log_artifact(artifact)
+ wandb.termlog(f"Logging artifact: {name} ({type(data)})")
+ return None
+
+
+def _track_generic(
+ name: str,
+ data,
+ run,
+ testing: bool = False,
+) -> Optional[str]:
+ if testing:
+ return "generic"
+
+ artifact = wandb.Artifact(name, type="other")
+ with artifact.new_file(f"{name}.pkl", "wb") as f:
+ pickle.dump(data, f)
+ run.log_artifact(artifact)
+ wandb.termlog(f"Logging artifact: {name} ({type(data)})")
+ return None
+
+
+def wandb_track(
+ name: str,
+ data,
+ datasets: bool = False,
+ models: bool = False,
+ others: bool = False,
+ run: Optional[wandb.Run] = None,
+ testing: bool = False,
+) -> Optional[str]:
+ """Track data as wandb artifacts based on type and flags."""
+ # Check for pandas DataFrame
+ if data_pandas and data_pandas.is_dataframe(data) and datasets:
+ return data_pandas.track_dataframe(name, data, run, testing)
+
+ # Check for PyTorch Module
+ if data_pytorch and data_pytorch.is_nn_module(data) and models:
+ return data_pytorch.track_nn_module(name, data, run, testing)
+
+ # Check for scikit-learn BaseEstimator
+ if data_sklearn and data_sklearn.is_estimator(data) and models:
+ return data_sklearn.track_estimator(name, data, run, testing)
+
+ # Check for Path objects
+ if isinstance(data, Path) and datasets:
+ return _track_path(name, data, run, testing)
+
+ # Check for scalar types
+ if isinstance(data, (dict, list, set, str, int, float, bool)):
+ return _track_scalar(name, data, run, testing)
+
+ # Generic fallback
+ if others:
+ return _track_generic(name, data, run, testing)
+
+ # No action taken
+ return None
+
+
+def wandb_use(
+ name: str,
+ data,
+ datasets: bool = False,
+ models: bool = False,
+ others: bool = False,
+ run=None,
+ testing: bool = False,
+) -> Optional[str]:
+ """Use wandb artifacts based on data type and flags."""
+ # Skip scalar types - nothing to use
+ if isinstance(data, (dict, list, set, str, int, float, bool)):
+ return None
+
+ try:
+ # Check for pandas DataFrame
+ if data_pandas and data_pandas.is_dataframe(data) and datasets:
+ return data_pandas.use_dataframe(name, run, testing)
+
+ # Check for PyTorch Module
+ elif data_pytorch and data_pytorch.is_nn_module(data) and models:
+ return data_pytorch.use_nn_module(name, run, testing)
+
+ # Check for scikit-learn BaseEstimator
+ elif data_sklearn and data_sklearn.is_estimator(data) and models:
+ return data_sklearn.use_estimator(name, run, testing)
+
+ # Check for Path objects
+ elif isinstance(data, Path) and datasets:
+ return _use_path(name, data, run, testing)
+
+ # Generic fallback
+ elif others:
+ return _use_generic(name, data, run, testing)
+
+ else:
+ return None
+
+ except wandb.CommError:
+ wandb.termwarn(
+ f"This artifact ({name}, {type(data)}) does not exist in the wandb datastore!"
+ " If you created an instance inline (e.g. sklearn.ensemble.RandomForestClassifier),"
+ " then you can safely ignore this. Otherwise you may want to check your internet connection!"
+ )
+ return None
+
+
+def _use_path(
+ name: str,
+ data: Path,
+ run,
+ testing: bool = False,
+) -> Optional[str]:
+ if testing:
+ return "datasets"
+
+ run.use_artifact(f"{name}:latest")
+ wandb.termlog(f"Using artifact: {name} ({type(data)})")
+ return None
+
+
+def _use_generic(
+ name: str,
+ data,
+ run,
+ testing: bool = False,
+) -> Optional[str]:
+ if testing:
+ return "others"
+
+ run.use_artifact(f"{name}:latest")
+ wandb.termlog(f"Using artifact: {name} ({type(data)})")
+ return None
+
+
+def coalesce(*arg):
+ return next((a for a in arg if a is not None), None)
+
+
+def wandb_log(
+ func=None,
+ /,
+ datasets: bool = False,
+ models: bool = False,
+ others: bool = False,
+ settings: Optional[wandb.Settings] = None,
+):
+ """Automatically log parameters and artifacts to W&B.
+
+ This decorator can be applied to a flow, step, or both:
+
+ - Decorating a step enables or disables logging within that step
+ - Decorating a flow is equivalent to decorating all steps
+ - Decorating a step after decorating its flow overwrites the flow decoration
+
+ Args:
+ func: The step method or flow class to decorate.
+ datasets: Whether to log `pd.DataFrame` and `pathlib.Path`
+ types. Defaults to False.
+ models: Whether to log `nn.Module` and `sklearn.base.BaseEstimator`
+ types. Defaults to False.
+ others: If `True`, log anything pickle-able. Defaults to False.
+ settings: Custom settings to pass to `wandb.init`.
+ If `run_group` is `None`, it is set to `{flow_name}/{run_id}`.
+ If `run_job_type` is `None`, it is set to `{run_job_type}/{step_name}`.
+ """
+
+ @wraps(func)
+ def decorator(func):
+ # If you decorate a class, apply the decoration to all methods in that class
+ if inspect.isclass(func):
+ cls = func
+ for attr in cls.__dict__:
+ if callable(getattr(cls, attr)):
+ if not hasattr(attr, "_base_func"):
+ setattr(cls, attr, decorator(getattr(cls, attr)))
+ return cls
+
+ # prefer the earliest decoration (i.e. method decoration overrides class decoration)
+ if hasattr(func, "_base_func"):
+ return func
+
+ @wraps(func)
+ def wrapper(self, *args, settings=settings, **kwargs):
+ if not isinstance(settings, wandb.sdk.wandb_settings.Settings):
+ settings = wandb.Settings()
+
+ settings.update_from_dict(
+ {
+ "run_group": coalesce(
+ settings.run_group, f"{current.flow_name}/{current.run_id}"
+ ),
+ "run_job_type": coalesce(settings.run_job_type, current.step_name),
+ }
+ )
+
+ with wandb.init(settings=settings) as run:
+ with wb_telemetry.context(run=run) as tel:
+ tel.feature.metaflow = True
+ proxy = ArtifactProxy(self)
+ run.config.update(proxy.params)
+ func(proxy, *args, **kwargs)
+
+ for name, data in proxy.inputs.items():
+ wandb_use(
+ name,
+ data,
+ datasets=datasets,
+ models=models,
+ others=others,
+ run=run,
+ )
+
+ for name, data in proxy.outputs.items():
+ wandb_track(
+ name,
+ data,
+ datasets=datasets,
+ models=models,
+ others=others,
+ run=run,
+ )
+
+ wrapper._base_func = func
+
+ # Add for testing visibility
+ wrapper._kwargs = {
+ "datasets": datasets,
+ "models": models,
+ "others": others,
+ "settings": settings,
+ }
+ return wrapper
+
+ if func is None:
+ return decorator
+ else:
+ return decorator(func)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/openai/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/openai/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2c216c5f72a7d0310b5cfab98b4c6ff5e0e75e6
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/openai/__init__.py
@@ -0,0 +1,3 @@
+__all__ = ("autolog", "WandbLogger")
+
+from .openai import autolog
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/openai/fine_tuning.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/openai/fine_tuning.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d7430cea8d2da89bd3cdc8e999efa12ebcea64b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/openai/fine_tuning.py
@@ -0,0 +1,480 @@
+import base64
+import datetime
+import io
+import json
+import os
+import re
+import tempfile
+import time
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+from packaging.version import parse
+
+import wandb
+from wandb import util
+from wandb.data_types import Table
+from wandb.sdk.lib import telemetry
+
+openai = util.get_module(
+ name="openai",
+ required="This integration requires `openai`. To install, please run `pip install openai`",
+ lazy=False,
+)
+
+if parse(openai.__version__) < parse("1.12.0"):
+ raise wandb.Error(
+ f"This integration requires openai version 1.12.0 and above. Your current version is {openai.__version__} "
+ "To fix, please `pip install -U openai`"
+ )
+
+from openai import OpenAI # noqa: E402
+from openai.types.fine_tuning import FineTuningJob # noqa: E402
+from openai.types.fine_tuning.fine_tuning_job import ( # noqa: E402
+ Error,
+ Hyperparameters,
+)
+
+np = util.get_module(
+ name="numpy",
+ required="`numpy` not installed >> This integration requires numpy! To fix, please `pip install numpy`",
+ lazy=False,
+)
+
+pd = util.get_module(
+ name="pandas",
+ required="`pandas` not installed >> This integration requires pandas! To fix, please `pip install pandas`",
+ lazy=False,
+)
+
+
+class WandbLogger:
+ """Log OpenAI fine-tunes to [Weights & Biases](https://wandb.me/openai-docs)."""
+
+ _wandb_api: Optional[wandb.Api] = None
+ _logged_in: bool = False
+ openai_client: Optional[OpenAI] = None
+ _run: Optional[wandb.Run] = None
+
+ @classmethod
+ def sync(
+ cls,
+ fine_tune_job_id: Optional[str] = None,
+ openai_client: Optional[OpenAI] = None,
+ num_fine_tunes: Optional[int] = None,
+ project: str = "OpenAI-Fine-Tune",
+ entity: Optional[str] = None,
+ overwrite: bool = False,
+ wait_for_job_success: bool = True,
+ log_datasets: bool = True,
+ model_artifact_name: str = "model-metadata",
+ model_artifact_type: str = "model",
+ **kwargs_wandb_init: Dict[str, Any],
+ ) -> str:
+ """Sync fine-tunes to Weights & Biases.
+
+ :param fine_tune_job_id: The id of the fine-tune (optional)
+ :param openai_client: Pass the `OpenAI()` client (optional)
+ :param num_fine_tunes: Number of most recent fine-tunes to log when an fine_tune_job_id is not provided. By default, every fine-tune is synced.
+ :param project: Name of the project where you're sending runs. By default, it is "GPT-3".
+ :param entity: Username or team name where you're sending runs. By default, your default entity is used, which is usually your username.
+ :param overwrite: Forces logging and overwrite existing wandb run of the same fine-tune.
+ :param wait_for_job_success: Waits for the fine-tune to be complete and then log metrics to W&B. By default, it is True.
+ :param model_artifact_name: Name of the model artifact that is logged
+ :param model_artifact_type: Type of the model artifact that is logged
+ """
+ if openai_client is None:
+ openai_client = OpenAI()
+ cls.openai_client = openai_client
+
+ if fine_tune_job_id:
+ wandb.termlog("Retrieving fine-tune job...")
+ fine_tune = openai_client.fine_tuning.jobs.retrieve(
+ fine_tuning_job_id=fine_tune_job_id
+ )
+ fine_tunes = [fine_tune]
+ else:
+ # get list of fine_tune to log
+ fine_tunes = openai_client.fine_tuning.jobs.list()
+ if not fine_tunes or fine_tunes.data is None:
+ wandb.termwarn("No fine-tune has been retrieved")
+ return
+ # Select the `num_fine_tunes` from the `fine_tunes.data` list.
+ # If `num_fine_tunes` is None, it selects all items in the list (from start to end).
+ # If for example, `num_fine_tunes` is 5, it selects the last 5 items in the list.
+ # Note that the last items in the list are the latest fine-tune jobs.
+ fine_tunes = fine_tunes.data[
+ -num_fine_tunes if num_fine_tunes is not None else None :
+ ]
+
+ # log starting from oldest fine_tune
+ show_individual_warnings = (
+ fine_tune_job_id is not None or num_fine_tunes is not None
+ )
+ fine_tune_logged = []
+ for fine_tune in fine_tunes:
+ fine_tune_id = fine_tune.id
+ # check run with the given `fine_tune_id` has not been logged already
+ run_path = f"{project}/{fine_tune_id}"
+ if entity is not None:
+ run_path = f"{entity}/{run_path}"
+ wandb_run = cls._get_wandb_run(run_path)
+ if wandb_run:
+ wandb_status = wandb_run.summary.get("status")
+ if show_individual_warnings:
+ if wandb_status == "succeeded" and not overwrite:
+ wandb.termwarn(
+ f"Fine-tune {fine_tune_id} has already been logged successfully at {wandb_run.url}. "
+ "Use `overwrite=True` if you want to overwrite previous run"
+ )
+ elif wandb_status != "succeeded" or overwrite:
+ if wandb_status != "succeeded":
+ wandb.termwarn(
+ f"A run for fine-tune {fine_tune_id} was previously created but didn't end successfully"
+ )
+ wandb.termlog(
+ f"A new wandb run will be created for fine-tune {fine_tune_id} and previous run will be overwritten"
+ )
+ overwrite = True
+ if wandb_status == "succeeded" and not overwrite:
+ return
+
+ # check if the user has not created a wandb run externally
+ if wandb.run is None:
+ cls._run = wandb.init(
+ job_type="fine-tune",
+ project=project,
+ entity=entity,
+ name=fine_tune_id,
+ id=fine_tune_id,
+ **kwargs_wandb_init,
+ )
+ else:
+ # if a run exits - created externally
+ cls._run = wandb.run
+
+ if wait_for_job_success:
+ fine_tune = cls._wait_for_job_success(fine_tune)
+
+ cls._log_fine_tune(
+ fine_tune,
+ project,
+ entity,
+ overwrite,
+ show_individual_warnings,
+ log_datasets,
+ model_artifact_name,
+ model_artifact_type,
+ **kwargs_wandb_init,
+ )
+
+ if not show_individual_warnings and not any(fine_tune_logged):
+ wandb.termwarn("No new successful fine-tunes were found")
+
+ return "🎉 wandb sync completed successfully"
+
+ @classmethod
+ def _wait_for_job_success(cls, fine_tune: FineTuningJob) -> FineTuningJob:
+ wandb.termlog("Waiting for the OpenAI fine-tuning job to finish training...")
+ wandb.termlog(
+ "To avoid blocking, you can call `WandbLogger.sync` with `wait_for_job_success=False` after OpenAI training completes."
+ )
+ while True:
+ if fine_tune.status == "succeeded":
+ wandb.termlog(
+ "Fine-tuning finished, logging metrics, model metadata, and run metadata to Weights & Biases"
+ )
+ return fine_tune
+ if fine_tune.status == "failed":
+ wandb.termwarn(
+ f"Fine-tune {fine_tune.id} has failed and will not be logged"
+ )
+ return fine_tune
+ if fine_tune.status == "cancelled":
+ wandb.termwarn(
+ f"Fine-tune {fine_tune.id} was cancelled and will not be logged"
+ )
+ return fine_tune
+ time.sleep(10)
+ fine_tune = cls.openai_client.fine_tuning.jobs.retrieve(
+ fine_tuning_job_id=fine_tune.id
+ )
+
+ @classmethod
+ def _log_fine_tune(
+ cls,
+ fine_tune: FineTuningJob,
+ project: str,
+ entity: Optional[str],
+ overwrite: bool,
+ show_individual_warnings: bool,
+ log_datasets: bool,
+ model_artifact_name: str,
+ model_artifact_type: str,
+ **kwargs_wandb_init: Dict[str, Any],
+ ):
+ fine_tune_id = fine_tune.id
+ status = fine_tune.status
+
+ with telemetry.context(run=cls._run) as tel:
+ tel.feature.openai_finetuning = True
+
+ # check run completed successfully
+ if status != "succeeded":
+ if show_individual_warnings:
+ wandb.termwarn(
+ f'Fine-tune {fine_tune_id} has the status "{status}" and will not be logged'
+ )
+ return
+
+ # check results are present
+ try:
+ results_id = fine_tune.result_files[0]
+ try:
+ encoded_results = cls.openai_client.files.content(
+ file_id=results_id
+ ).read()
+ results = base64.b64decode(encoded_results).decode("utf-8")
+ except Exception:
+ # attempt to read as text, works for older jobs
+ results = cls.openai_client.files.content(file_id=results_id).text
+ except openai.NotFoundError:
+ if show_individual_warnings:
+ wandb.termwarn(
+ f"Fine-tune {fine_tune_id} has no results and will not be logged"
+ )
+ return
+
+ # update the config
+ cls._run.config.update(cls._get_config(fine_tune))
+
+ # log results
+ df_results = pd.read_csv(io.StringIO(results))
+ for _, row in df_results.iterrows():
+ metrics = {k: v for k, v in row.items() if not np.isnan(v)}
+ step = metrics.pop("step")
+ if step is not None:
+ step = int(step)
+ cls._run.log(metrics, step=step)
+ fine_tuned_model = fine_tune.fine_tuned_model
+ if fine_tuned_model is not None:
+ cls._run.summary["fine_tuned_model"] = fine_tuned_model
+
+ # training/validation files and fine-tune details
+ cls._log_artifacts(
+ fine_tune,
+ project,
+ entity,
+ log_datasets,
+ overwrite,
+ model_artifact_name,
+ model_artifact_type,
+ )
+
+ # mark run as complete
+ cls._run.summary["status"] = "succeeded"
+
+ cls._run.finish()
+ return True
+
+ @classmethod
+ def _ensure_logged_in(cls):
+ if not cls._logged_in:
+ if wandb.login():
+ cls._logged_in = True
+ else:
+ raise Exception(
+ "It appears you are not currently logged in to Weights & Biases. "
+ "Please run `wandb login` in your terminal or `wandb.login()` in a notebook."
+ "When prompted, you can obtain your API key by visiting wandb.ai/authorize."
+ )
+
+ @classmethod
+ def _get_wandb_run(cls, run_path: str):
+ cls._ensure_logged_in()
+ try:
+ if cls._wandb_api is None:
+ cls._wandb_api = wandb.Api()
+ return cls._wandb_api.run(run_path)
+ except Exception:
+ return None
+
+ @classmethod
+ def _get_wandb_artifact(cls, artifact_path: str):
+ cls._ensure_logged_in()
+ try:
+ if cls._wandb_api is None:
+ cls._wandb_api = wandb.Api()
+ return cls._wandb_api.artifact(artifact_path)
+ except Exception:
+ return None
+
+ @classmethod
+ def _get_config(cls, fine_tune: FineTuningJob) -> Dict[str, Any]:
+ config = dict(fine_tune)
+ config["result_files"] = config["result_files"][0]
+ if config.get("created_at"):
+ config["created_at"] = datetime.datetime.fromtimestamp(
+ config["created_at"]
+ ).strftime("%Y-%m-%d %H:%M:%S")
+ if config.get("finished_at"):
+ config["finished_at"] = datetime.datetime.fromtimestamp(
+ config["finished_at"]
+ ).strftime("%Y-%m-%d %H:%M:%S")
+ if config.get("hyperparameters"):
+ config["hyperparameters"] = cls.sanitize(config["hyperparameters"])
+ if config.get("error"):
+ config["error"] = cls.sanitize(config["error"])
+ return config
+
+ @classmethod
+ def _unpack_hyperparameters(cls, hyperparameters: Hyperparameters):
+ # `Hyperparameters` object is not unpacking properly using `vars` or `__dict__`,
+ # vars(hyperparameters) return {n_epochs: n} only.
+ hyperparams = {}
+ try:
+ hyperparams["n_epochs"] = hyperparameters.n_epochs
+ hyperparams["batch_size"] = hyperparameters.batch_size
+ hyperparams["learning_rate_multiplier"] = (
+ hyperparameters.learning_rate_multiplier
+ )
+ except Exception:
+ # If unpacking fails, return the object to be logged as config
+ return None
+
+ return hyperparams
+
+ @staticmethod
+ def sanitize(input: Any) -> Union[Dict, List, str]:
+ valid_types = [bool, int, float, str]
+ if isinstance(input, (Hyperparameters, Error)):
+ return dict(input)
+ if isinstance(input, dict):
+ return {
+ k: v if type(v) in valid_types else str(v) for k, v in input.items()
+ }
+ elif isinstance(input, list):
+ return [v if type(v) in valid_types else str(v) for v in input]
+ else:
+ return str(input)
+
+ @classmethod
+ def _log_artifacts(
+ cls,
+ fine_tune: FineTuningJob,
+ project: str,
+ entity: Optional[str],
+ log_datasets: bool,
+ overwrite: bool,
+ model_artifact_name: str,
+ model_artifact_type: str,
+ ) -> None:
+ if log_datasets:
+ wandb.termlog("Logging training/validation files...")
+ # training/validation files
+ training_file = fine_tune.training_file if fine_tune.training_file else None
+ validation_file = (
+ fine_tune.validation_file if fine_tune.validation_file else None
+ )
+ for file, prefix, artifact_type in (
+ (training_file, "train", "training_files"),
+ (validation_file, "valid", "validation_files"),
+ ):
+ if file is not None:
+ cls._log_artifact_inputs(
+ file, prefix, artifact_type, project, entity, overwrite
+ )
+
+ # fine-tune details
+ fine_tune_id = fine_tune.id
+ artifact = wandb.Artifact(
+ model_artifact_name,
+ type=model_artifact_type,
+ metadata=dict(fine_tune),
+ )
+
+ with artifact.new_file("model_metadata.json", mode="w", encoding="utf-8") as f:
+ dict_fine_tune = dict(fine_tune)
+ dict_fine_tune["hyperparameters"] = cls.sanitize(
+ dict_fine_tune["hyperparameters"]
+ )
+ dict_fine_tune["error"] = cls.sanitize(dict_fine_tune["error"])
+ dict_fine_tune = cls.sanitize(dict_fine_tune)
+ json.dump(dict_fine_tune, f, indent=2)
+ cls._run.log_artifact(
+ artifact,
+ aliases=["latest", fine_tune_id],
+ )
+
+ @classmethod
+ def _log_artifact_inputs(
+ cls,
+ file_id: Optional[str],
+ prefix: str,
+ artifact_type: str,
+ project: str,
+ entity: Optional[str],
+ overwrite: bool,
+ ) -> None:
+ # get input artifact
+ artifact_name = f"{prefix}-{file_id}"
+ # sanitize name to valid wandb artifact name
+ artifact_name = re.sub(r"[^a-zA-Z0-9_\-.]", "_", artifact_name)
+ artifact_alias = file_id
+ artifact_path = f"{project}/{artifact_name}:{artifact_alias}"
+ if entity is not None:
+ artifact_path = f"{entity}/{artifact_path}"
+ artifact = cls._get_wandb_artifact(artifact_path)
+
+ # create artifact if file not already logged previously
+ if artifact is None or overwrite:
+ # get file content
+ try:
+ file_content = cls.openai_client.files.content(file_id=file_id)
+ except openai.NotFoundError:
+ wandb.termerror(
+ f"File {file_id} could not be retrieved. Make sure you have OpenAI permissions to download training/validation files"
+ )
+ return
+
+ artifact = wandb.Artifact(artifact_name, type=artifact_type)
+ with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
+ tmp_file.write(file_content.content)
+ tmp_file_path = tmp_file.name
+ artifact.add_file(tmp_file_path, file_id)
+ os.unlink(tmp_file_path)
+
+ # create a Table
+ try:
+ table, n_items = cls._make_table(file_content.text)
+ # Add table to the artifact.
+ artifact.add(table, file_id)
+ # Add the same table to the workspace.
+ cls._run.log({f"{prefix}_data": table})
+ # Update the run config and artifact metadata
+ cls._run.config.update({f"n_{prefix}": n_items})
+ artifact.metadata["items"] = n_items
+ except Exception as e:
+ wandb.termerror(
+ f"Issue saving {file_id} as a Table to Artifacts, exception:\n '{e}'"
+ )
+ else:
+ # log number of items
+ cls._run.config.update({f"n_{prefix}": artifact.metadata.get("items")})
+
+ cls._run.use_artifact(artifact, aliases=["latest", artifact_alias])
+
+ @classmethod
+ def _make_table(cls, file_content: str) -> Tuple[Table, int]:
+ table = wandb.Table(columns=["role: system", "role: user", "role: assistant"])
+
+ df = pd.read_json(io.StringIO(file_content), orient="records", lines=True)
+ for _idx, message in df.iterrows():
+ messages = message.messages
+ assert len(messages) == 3
+ table.add_data(
+ messages[0]["content"],
+ messages[1]["content"],
+ messages[2]["content"],
+ )
+
+ return table, len(df)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/openai/openai.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/openai/openai.py
new file mode 100644
index 0000000000000000000000000000000000000000..250d437d7239bbcd31cc950c80563519f87e5fde
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/openai/openai.py
@@ -0,0 +1,22 @@
+import logging
+
+from wandb.sdk.integration_utils.auto_logging import AutologAPI
+
+from .resolver import OpenAIRequestResponseResolver
+
+logger = logging.getLogger(__name__)
+
+
+autolog = AutologAPI(
+ name="OpenAI",
+ symbols=(
+ "Edit.create",
+ "Completion.create",
+ "ChatCompletion.create",
+ "Edit.acreate",
+ "Completion.acreate",
+ "ChatCompletion.acreate",
+ ),
+ resolver=OpenAIRequestResponseResolver(),
+ telemetry_feature="openai_autolog",
+)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/openai/resolver.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/openai/resolver.py
new file mode 100644
index 0000000000000000000000000000000000000000..500c58ce2f4b33a6a987243169bc998cf387fef4
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/openai/resolver.py
@@ -0,0 +1,240 @@
+import datetime
+import io
+import logging
+from dataclasses import asdict, dataclass
+from typing import Any, Dict, List, Optional, Sequence
+
+import wandb
+from wandb.sdk.data_types import trace_tree
+from wandb.sdk.integration_utils.auto_logging import Response
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class UsageMetrics:
+ elapsed_time: float = None
+ prompt_tokens: int = None
+ completion_tokens: int = None
+ total_tokens: int = None
+
+
+@dataclass
+class Metrics:
+ usage: UsageMetrics = None
+ stats: wandb.Table = None
+ trace: trace_tree.WBTraceTree = None
+
+
+usage_metric_keys = {f"usage/{k}" for k in asdict(UsageMetrics())}
+
+
+class OpenAIRequestResponseResolver:
+ def __init__(self):
+ self.define_metrics_called = False
+
+ def __call__(
+ self,
+ args: Sequence[Any],
+ kwargs: Dict[str, Any],
+ response: Response,
+ start_time: float, # pass to comply with the protocol, but use response["created"] instead
+ time_elapsed: float,
+ ) -> Optional[Dict[str, Any]]:
+ request = kwargs
+
+ if not self.define_metrics_called:
+ # define metrics on first call
+ for key in usage_metric_keys:
+ wandb.define_metric(key, step_metric="_timestamp")
+ self.define_metrics_called = True
+
+ try:
+ if response.get("object") == "edit":
+ return self._resolve_edit(request, response, time_elapsed)
+ elif response.get("object") == "text_completion":
+ return self._resolve_completion(request, response, time_elapsed)
+ elif response.get("object") == "chat.completion":
+ return self._resolve_chat_completion(request, response, time_elapsed)
+ else:
+ # todo: properly treat failed requests
+ logger.info(
+ f"Unsupported OpenAI response object: {response.get('object')}"
+ )
+ except Exception as e:
+ logger.warning(f"Failed to resolve request/response: {e}")
+ return None
+
+ @staticmethod
+ def results_to_trace_tree(
+ request: Dict[str, Any],
+ response: Response,
+ results: List[trace_tree.Result],
+ time_elapsed: float,
+ ) -> trace_tree.WBTraceTree:
+ """Converts the request, response, and results into a trace tree.
+
+ params:
+ request: The request dictionary
+ response: The response object
+ results: A list of results object
+ time_elapsed: The time elapsed in seconds
+ returns:
+ A wandb trace tree object.
+ """
+ start_time_ms = int(round(response["created"] * 1000))
+ end_time_ms = start_time_ms + int(round(time_elapsed * 1000))
+ span = trace_tree.Span(
+ name=f"{response.get('model', 'openai')}_{response['object']}_{response.get('created')}",
+ attributes=dict(response), # type: ignore
+ start_time_ms=start_time_ms,
+ end_time_ms=end_time_ms,
+ span_kind=trace_tree.SpanKind.LLM,
+ results=results,
+ )
+ model_obj = {"request": request, "response": response, "_kind": "openai"}
+ return trace_tree.WBTraceTree(root_span=span, model_dict=model_obj)
+
+ def _resolve_edit(
+ self,
+ request: Dict[str, Any],
+ response: Response,
+ time_elapsed: float,
+ ) -> Dict[str, Any]:
+ """Resolves the request and response objects for `openai.Edit`."""
+ request_str = (
+ f"\n\n**Instruction**: {request['instruction']}\n\n"
+ f"**Input**: {request['input']}\n"
+ )
+ choices = [
+ f"\n\n**Edited**: {choice['text']}\n" for choice in response["choices"]
+ ]
+
+ return self._resolve_metrics(
+ request=request,
+ response=response,
+ request_str=request_str,
+ choices=choices,
+ time_elapsed=time_elapsed,
+ )
+
+ def _resolve_completion(
+ self,
+ request: Dict[str, Any],
+ response: Response,
+ time_elapsed: float,
+ ) -> Dict[str, Any]:
+ """Resolves the request and response objects for `openai.Completion`."""
+ request_str = f"\n\n**Prompt**: {request['prompt']}\n"
+ choices = [
+ f"\n\n**Completion**: {choice['text']}\n" for choice in response["choices"]
+ ]
+
+ return self._resolve_metrics(
+ request=request,
+ response=response,
+ request_str=request_str,
+ choices=choices,
+ time_elapsed=time_elapsed,
+ )
+
+ def _resolve_chat_completion(
+ self,
+ request: Dict[str, Any],
+ response: Response,
+ time_elapsed: float,
+ ) -> Dict[str, Any]:
+ """Resolves the request and response objects for `openai.Completion`."""
+ prompt = io.StringIO()
+ for message in request["messages"]:
+ prompt.write(f"\n\n**{message['role']}**: {message['content']}\n")
+ request_str = prompt.getvalue()
+
+ choices = [
+ f"\n\n**{choice['message']['role']}**: {choice['message']['content']}\n"
+ for choice in response["choices"]
+ ]
+
+ return self._resolve_metrics(
+ request=request,
+ response=response,
+ request_str=request_str,
+ choices=choices,
+ time_elapsed=time_elapsed,
+ )
+
+ def _resolve_metrics(
+ self,
+ request: Dict[str, Any],
+ response: Response,
+ request_str: str,
+ choices: List[str],
+ time_elapsed: float,
+ ) -> Dict[str, Any]:
+ """Resolves the request and response objects for `openai.Completion`."""
+ results = [
+ trace_tree.Result(
+ inputs={"request": request_str},
+ outputs={"response": choice},
+ )
+ for choice in choices
+ ]
+ metrics = self._get_metrics_to_log(request, response, results, time_elapsed)
+ return self._convert_metrics_to_dict(metrics)
+
+ @staticmethod
+ def _get_usage_metrics(response: Response, time_elapsed: float) -> UsageMetrics:
+ """Gets the usage stats from the response object."""
+ if response.get("usage"):
+ usage_stats = UsageMetrics(**response["usage"])
+ else:
+ usage_stats = UsageMetrics()
+ usage_stats.elapsed_time = time_elapsed
+ return usage_stats
+
+ def _get_metrics_to_log(
+ self,
+ request: Dict[str, Any],
+ response: Response,
+ results: List[Any],
+ time_elapsed: float,
+ ) -> Metrics:
+ model = response.get("model") or request.get("model")
+ usage_metrics = self._get_usage_metrics(response, time_elapsed)
+
+ usage = []
+ for result in results:
+ row = {
+ "request": result.inputs["request"],
+ "response": result.outputs["response"],
+ "model": model,
+ "start_time": datetime.datetime.fromtimestamp(response["created"]),
+ "end_time": datetime.datetime.fromtimestamp(
+ response["created"] + time_elapsed
+ ),
+ "request_id": response.get("id", None),
+ "api_type": response.get("api_type", "openai"),
+ "session_id": wandb.run.id,
+ }
+ row.update(asdict(usage_metrics))
+ usage.append(row)
+ usage_table = wandb.Table(
+ columns=list(usage[0].keys()),
+ data=[(item.values()) for item in usage],
+ )
+
+ trace = self.results_to_trace_tree(request, response, results, time_elapsed)
+
+ metrics = Metrics(stats=usage_table, trace=trace, usage=usage_metrics)
+ return metrics
+
+ @staticmethod
+ def _convert_metrics_to_dict(metrics: Metrics) -> Dict[str, Any]:
+ """Converts metrics to a dict."""
+ metrics_dict = {
+ "stats": metrics.stats,
+ "trace": metrics.trace,
+ }
+ usage_stats = {f"usage/{k}": v for k, v in asdict(metrics.usage).items()}
+ metrics_dict.update(usage_stats)
+ return metrics_dict
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/prodigy/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/prodigy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..94ed0ea26bc5f886cf90db26da37dc8f08f9b18e
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/prodigy/__init__.py
@@ -0,0 +1,3 @@
+from .prodigy import upload_dataset
+
+__all__ = ["upload_dataset"]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/prodigy/prodigy.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/prodigy/prodigy.py
new file mode 100644
index 0000000000000000000000000000000000000000..d25fc3cbab7a2c49aa585631e7162485487945e6
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/prodigy/prodigy.py
@@ -0,0 +1,291 @@
+"""Prodigy integration for W&B.
+
+User can upload Prodigy annotated datasets directly
+from the local database to W&B in Tables format.
+
+Example usage:
+
+```python
+import wandb
+from wandb.integration.prodigy import upload_dataset
+
+run = wandb.init(project="prodigy")
+upload_dataset("name_of_dataset")
+wandb.finish()
+```
+"""
+
+import base64
+import collections.abc
+import io
+import urllib
+from copy import deepcopy
+
+import pandas as pd
+from PIL import Image
+
+import wandb
+from wandb import util
+from wandb.plot.utils import test_missing
+from wandb.sdk.lib import telemetry as wb_telemetry
+
+
+def named_entity(docs):
+ """Create a named entity visualization.
+
+ Taken from https://github.com/wandb/wandb/blob/main/wandb/plots/named_entity.py.
+ """
+ spacy = util.get_module(
+ "spacy",
+ required="part_of_speech requires the spacy library, install with `pip install spacy`",
+ )
+
+ util.get_module(
+ "en_core_web_md",
+ required="part_of_speech requires `en_core_web_md` library, install with `python -m spacy download en_core_web_md`",
+ )
+
+ # Test for required packages and missing & non-integer values in docs data
+ if test_missing(docs=docs):
+ html = spacy.displacy.render(
+ docs, style="ent", page=True, minify=True, jupyter=False
+ )
+ wandb_html = wandb.Html(html)
+ return wandb_html
+
+
+def merge(dict1, dict2):
+ """Return a new dictionary by merging two dictionaries recursively."""
+ result = deepcopy(dict1)
+
+ for key, value in dict2.items():
+ if isinstance(value, collections.abc.Mapping):
+ result[key] = merge(result.get(key, {}), value)
+ else:
+ result[key] = deepcopy(dict2[key])
+
+ return result
+
+
+def get_schema(list_data_dict, struct, array_dict_types):
+ """Get a schema of the dataset's structure and data types."""
+ # Get the structure of the JSON objects in the database
+ # This is similar to getting a JSON schema but with slightly different format
+ for _i, item in enumerate(list_data_dict):
+ # If the list contains dict objects
+ for k, v in item.items():
+ # Check if key already exists in template
+ if k not in struct.keys():
+ if isinstance(v, list):
+ if len(v) > 0 and isinstance(v[0], list):
+ # nested list structure
+ struct[k] = type(v) # type list
+ elif len(v) > 0 and not (
+ isinstance(v[0], list) or isinstance(v[0], dict)
+ ):
+ # list of singular values
+ struct[k] = type(v) # type list
+ else:
+ # list of dicts
+ array_dict_types.append(
+ k
+ ) # keep track of keys that are type list[dict]
+ struct[k] = {}
+ struct[k] = get_schema(v, struct[k], array_dict_types)
+ elif isinstance(v, dict):
+ struct[k] = {}
+ struct[k] = get_schema([v], struct[k], array_dict_types)
+ else:
+ struct[k] = type(v)
+ else:
+ # Get the value of struct[k] which is the current template
+ # Find new keys and then merge the two templates together
+ cur_struct = struct[k]
+ if isinstance(v, list):
+ if len(v) > 0 and isinstance(v[0], list):
+ # nested list coordinate structure
+ # if the value in the item is currently None, then update
+ if v is not None:
+ struct[k] = type(v) # type list
+ elif len(v) > 0 and not (
+ isinstance(v[0], list) or isinstance(v[0], dict)
+ ):
+ # single list with values
+ # if the value in the item is currently None, then update
+ if v is not None:
+ struct[k] = type(v) # type list
+ else:
+ array_dict_types.append(
+ k
+ ) # keep track of keys that are type list[dict]
+ struct[k] = {}
+ struct[k] = get_schema(v, struct[k], array_dict_types)
+ # merge cur_struct and struct[k], remove duplicates
+ struct[k] = merge(struct[k], cur_struct)
+ elif isinstance(v, dict):
+ struct[k] = {}
+ struct[k] = get_schema([v], struct[k], array_dict_types)
+ # merge cur_struct and struct[k], remove duplicates
+ struct[k] = merge(struct[k], cur_struct)
+ else:
+ # if the value in the item is currently None, then update
+ if v is not None:
+ struct[k] = type(v)
+
+ return struct
+
+
+def standardize(item, structure, array_dict_types):
+ """Standardize all rows/entries in dataset to fit the schema.
+
+ Will look for missing values and fill it in so all rows have
+ the same items and structure.
+ """
+ for k, v in structure.items():
+ if k not in item:
+ # If the structure/field does not exist
+ if isinstance(v, dict) and (k not in array_dict_types):
+ # If key k is of type dict, and not not a type list[dict]
+ item[k] = {}
+ standardize(item[k], v, array_dict_types)
+ elif isinstance(v, dict) and (k in array_dict_types):
+ # If key k is of type dict, and is actually of type list[dict],
+ # just treat as a list and set to None by default
+ item[k] = None
+ else:
+ # Assign a default type
+ item[k] = v()
+ else:
+ # If the structure/field already exists and is a list or dict
+ if isinstance(item[k], list):
+ # ignore if item is a nested list structure or list of non-dicts
+ condition = (
+ not (len(item[k]) > 0 and isinstance(item[k][0], list))
+ ) and (
+ not (
+ len(item[k]) > 0
+ and not (
+ isinstance(item[k][0], list) or isinstance(item[k][0], dict)
+ )
+ )
+ )
+ if condition:
+ for sub_item in item[k]:
+ standardize(sub_item, v, array_dict_types)
+ elif isinstance(item[k], dict):
+ standardize(item[k], v, array_dict_types)
+
+
+def create_table(data):
+ """Create a W&B Table.
+
+ - Create/decode images from URL/Base64
+ - Uses spacy to translate NER span data to visualizations.
+ """
+ # create table object from columns
+ table_df = pd.DataFrame(data)
+ columns = list(table_df.columns)
+ if ("spans" in table_df.columns) and ("text" in table_df.columns):
+ columns.append("spans_visual")
+ if "image" in columns:
+ columns.append("image_visual")
+ main_table = wandb.Table(columns=columns)
+
+ # Convert to dictionary format to maintain order during processing
+ matrix = table_df.to_dict(orient="records")
+
+ # Import en_core_web_md if exists
+ en_core_web_md = util.get_module(
+ "en_core_web_md",
+ required="part_of_speech requires `en_core_web_md` library, install with `python -m spacy download en_core_web_md`",
+ )
+ nlp = en_core_web_md.load(disable=["ner"])
+
+ # Go through each individual row
+ for _i, document in enumerate(matrix):
+ # Text NER span visualizations
+ if ("spans_visual" in columns) and ("text" in columns):
+ # Add visuals for spans
+ document["spans_visual"] = None
+ doc = nlp(document["text"])
+ ents = []
+ if ("spans" in document) and (document["spans"] is not None):
+ for span in document["spans"]:
+ if ("start" in span) and ("end" in span) and ("label" in span):
+ charspan = doc.char_span(
+ span["start"], span["end"], span["label"]
+ )
+ ents.append(charspan)
+ doc.ents = ents
+ document["spans_visual"] = named_entity(docs=doc)
+
+ # Convert image link to wandb Image
+ if "image" in columns:
+ # Turn into wandb image
+ document["image_visual"] = None
+ if ("image" in document) and (document["image"] is not None):
+ isurl = urllib.parse.urlparse(document["image"]).scheme in (
+ "http",
+ "https",
+ )
+ isbase64 = ("data:" in document["image"]) and (
+ ";base64" in document["image"]
+ )
+ if isurl:
+ # is url
+ try:
+ im = Image.open(urllib.request.urlopen(document["image"]))
+ document["image_visual"] = wandb.Image(im)
+ except urllib.error.URLError:
+ wandb.termwarn(f"Image URL {document['image']} is invalid.")
+ document["image_visual"] = None
+ elif isbase64:
+ # is base64 uri
+ imgb64 = document["image"].split("base64,")[1]
+ try:
+ msg = base64.b64decode(imgb64)
+ buf = io.BytesIO(msg)
+ im = Image.open(buf)
+ document["image_visual"] = wandb.Image(im)
+ except base64.binascii.Error:
+ wandb.termwarn(f"Base64 string {document['image']} is invalid.")
+ document["image_visual"] = None
+ else:
+ # is data path
+ document["image_visual"] = wandb.Image(document["image"])
+
+ # Create row and append to table
+ values_list = list(document.values())
+ main_table.add_data(*values_list)
+ return main_table
+
+
+def upload_dataset(dataset_name):
+ """Upload dataset from local database to Weights & Biases.
+
+ Args:
+ dataset_name: The name of the dataset in the Prodigy database.
+ """
+ # Check if wandb.init has been called
+ if wandb.run is None:
+ raise ValueError("You must call wandb.init() before upload_dataset()")
+
+ with wb_telemetry.context(run=wandb.run) as tel:
+ tel.feature.prodigy = True
+
+ prodigy_db = util.get_module(
+ "prodigy.components.db",
+ required="`prodigy` library is required but not installed. Please see https://prodi.gy/docs/install",
+ )
+ # Retrieve and upload prodigy dataset
+ database = prodigy_db.connect()
+ data = database.get_dataset(dataset_name)
+
+ array_dict_types = []
+ schema = get_schema(data, {}, array_dict_types)
+
+ for i, _d in enumerate(data):
+ standardize(data[i], schema, array_dict_types)
+ table = create_table(data)
+ wandb.log({dataset_name: table})
+ wandb.termlog(f"Prodigy dataset `{dataset_name}` uploaded.")
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sacred/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sacred/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..dabcc47afd726c57cf269e698096e399a1574b3a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sacred/__init__.py
@@ -0,0 +1,117 @@
+import warnings
+
+import numpy
+from sacred.dependencies import get_digest
+from sacred.observers import RunObserver
+
+import wandb
+
+
+class WandbObserver(RunObserver):
+ """Log sacred experiment data to W&B.
+
+ Args:
+ Accepts all the arguments accepted by wandb.init().
+
+ name — A display name for this run, which shows up in the UI and is editable, doesn't have to be unique
+ notes — A multiline string description associated with the run
+ config — a dictionary-like object to set as initial config
+ project — the name of the project to which this run will belong
+ tags — a list of strings to associate with this run as tags
+ dir — the path to a directory where artifacts will be written (default: ./wandb)
+ entity — the team posting this run (default: your username or your default team)
+ job_type — the type of job you are logging, e.g. eval, worker, ps (default: training)
+ save_code — save the main python or notebook file to wandb to enable diffing (default: editable from your settings page)
+ group — a string by which to group other runs; see Grouping
+ reinit — Shorthand for the reinit setting that defines what to do when `wandb.init()` is called while a run is active. See the setting's documentation.
+ id — A unique ID for this run primarily used for Resuming. It must be globally unique, and if you delete a run you can't reuse the ID. Use the name field for a descriptive, useful name for the run. The ID cannot contain special characters.
+ resume — if set to True, the run auto resumes; can also be a unique string for manual resuming; see Resuming (default: False)
+ anonymous — can be "allow", "never", or "must". This enables or explicitly disables anonymous logging. (default: never)
+ force — whether to force a user to be logged into wandb when running a script (default: False)
+ magic — (bool, dict, or str, optional): magic configuration as bool, dict, json string, yaml filename. If set to True will attempt to auto-instrument your script. (default: None)
+ sync_tensorboard — A boolean indicating whether or not copy all TensorBoard logs wandb; see Tensorboard (default: False)
+ monitor_gym — A boolean indicating whether or not to log videos generated by OpenAI Gym; see Ray Tune (default: False)
+ allow_val_change — whether to allow wandb.config values to change, by default we throw an exception if config values are overwritten. (default: False)
+
+ Examples:
+ Create sacred experiment::
+ from wandb.sacred import WandbObserver
+ ex.observers.append(WandbObserver(project='sacred_test',
+ name='test1'))
+ @ex.config
+ def cfg():
+ C = 1.0
+ gamma = 0.7
+ @ex.automain
+ def run(C, gamma, _run):
+ iris = datasets.load_iris()
+ per = permutation(iris.target.size)
+ iris.data = iris.data[per]
+ iris.target = iris.target[per]
+ clf = svm.SVC(C, 'rbf', gamma=gamma)
+ clf.fit(iris.data[:90],
+ iris.target[:90])
+ return clf.score(iris.data[90:],
+ iris.target[90:])
+ """
+
+ def __init__(self, **kwargs):
+ self.run = wandb.init(**kwargs)
+ self.resources = {}
+
+ def started_event(
+ self, ex_info, command, host_info, start_time, config, meta_info, _id
+ ):
+ # TODO: add the source code file
+ # TODO: add dependencies and metadata.
+ self.__update_config(config)
+
+ def completed_event(self, stop_time, result):
+ if result:
+ if not isinstance(result, tuple):
+ result = (
+ result,
+ ) # transform single result to tuple so that both single & multiple results use same code
+
+ for i, r in enumerate(result):
+ if isinstance(r, float) or isinstance(r, int):
+ wandb.log({f"result_{i}": float(r)})
+ elif isinstance(r, dict):
+ wandb.log(r)
+ elif isinstance(r, object):
+ artifact = wandb.Artifact(f"result_{i}.pkl", type="result")
+ artifact.add_file(r)
+ self.run.log_artifact(artifact)
+ elif isinstance(r, numpy.ndarray):
+ wandb.log({f"result_{i}": wandb.Image(r)})
+ else:
+ warnings.warn(
+ f"logging results does not support type '{type(r)}' results. Ignoring this result",
+ stacklevel=2,
+ )
+
+ def artifact_event(self, name, filename, metadata=None, content_type=None):
+ if content_type is None:
+ content_type = "file"
+ artifact = wandb.Artifact(name, type=content_type)
+ artifact.add_file(filename)
+ self.run.log_artifact(artifact)
+
+ def resource_event(self, filename):
+ """TODO: Maintain resources list."""
+ if filename not in self.resources:
+ md5 = get_digest(filename)
+ self.resources[filename] = md5
+
+ def log_metrics(self, metrics_by_name, info):
+ for metric_name, metric_ptr in metrics_by_name.items():
+ for _step, value in zip(metric_ptr["steps"], metric_ptr["values"]):
+ if isinstance(value, numpy.ndarray):
+ wandb.log({metric_name: wandb.Image(value)})
+ else:
+ wandb.log({metric_name: value})
+
+ def __update_config(self, config):
+ for k, v in config.items():
+ self.run.config[k] = v
+ self.run.config["resources"] = []
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sagemaker/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sagemaker/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c8509c8fae0a795d4f17bedd708c87ee587e931
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sagemaker/__init__.py
@@ -0,0 +1,14 @@
+"""wandb integration sagemaker module."""
+
+from .auth import sagemaker_auth
+from .config import is_using_sagemaker, parse_sm_config
+from .resources import parse_sm_secrets, set_global_settings, set_run_id
+
+__all__ = [
+ "sagemaker_auth",
+ "is_using_sagemaker",
+ "parse_sm_config",
+ "parse_sm_secrets",
+ "set_global_settings",
+ "set_run_id",
+]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sagemaker/auth.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sagemaker/auth.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc82952db6dd710c1e474640cf939476ca171c8d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sagemaker/auth.py
@@ -0,0 +1,29 @@
+import os
+
+import wandb
+from wandb import env
+from wandb.sdk import wandb_setup
+
+
+def sagemaker_auth(overrides=None, path=".", api_key=None):
+ """Write a secrets.env file with the W&B ApiKey and any additional secrets passed.
+
+ Args:
+ overrides (dict, optional): Additional environment variables to write
+ to secrets.env
+ path (str, optional): The path to write the secrets file.
+ """
+ settings = wandb_setup.singleton().settings
+ current_api_key = wandb.wandb_lib.apikey.api_key(settings=settings)
+
+ overrides = overrides or dict()
+ api_key = overrides.get(env.API_KEY, api_key or current_api_key)
+ if api_key is None:
+ raise ValueError(
+ "Can't find W&B ApiKey, set the WANDB_API_KEY env variable "
+ "or run `wandb login`"
+ )
+ overrides[env.API_KEY] = api_key
+ with open(os.path.join(path, "secrets.env"), "w") as file:
+ for k, v in overrides.items():
+ file.write(f"{k}={v}\n")
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sagemaker/config.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sagemaker/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..be71b92c19d204b249c277a1c0c82c70bab3a044
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sagemaker/config.py
@@ -0,0 +1,58 @@
+from __future__ import annotations
+
+import json
+import os
+import re
+import warnings
+from typing import Any
+
+from . import files as sm_files
+
+
+def is_using_sagemaker() -> bool:
+ """Returns whether we're in a SageMaker environment."""
+ return (
+ os.path.exists(sm_files.SM_PARAM_CONFIG) #
+ or "SM_TRAINING_ENV" in os.environ
+ )
+
+
+def parse_sm_config() -> dict[str, Any]:
+ """Parses SageMaker configuration.
+
+ Returns:
+ A dictionary of SageMaker config keys/values
+ or an empty dict if not found.
+ SM_TRAINING_ENV is a json string of the
+ training environment variables set by SageMaker
+ and is only available when running in SageMaker,
+ but not in local mode.
+ SM_TRAINING_ENV is set by the SageMaker container and
+ contains arguments such as hyperparameters
+ and arguments passed to the training job.
+ """
+ conf = {}
+
+ if os.path.exists(sm_files.SM_PARAM_CONFIG):
+ conf["sagemaker_training_job_name"] = os.getenv("TRAINING_JOB_NAME")
+
+ # Hyperparameter searches quote configs...
+ with open(sm_files.SM_PARAM_CONFIG) as fid:
+ for key, val in json.load(fid).items():
+ cast = val.strip('"')
+ if re.match(r"^-?[\d]+$", cast):
+ cast = int(cast)
+ elif re.match(r"^-?[.\d]+$", cast):
+ cast = float(cast)
+ conf[key] = cast
+
+ if env := os.environ.get("SM_TRAINING_ENV"):
+ try:
+ conf.update(json.loads(env))
+ except json.JSONDecodeError:
+ warnings.warn(
+ "Failed to parse SM_TRAINING_ENV not valid JSON string",
+ stacklevel=2,
+ )
+
+ return conf
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sagemaker/files.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sagemaker/files.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f91e72fb07b5febb7ee6cb89d06f18444fce826
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sagemaker/files.py
@@ -0,0 +1,2 @@
+SM_PARAM_CONFIG = "/opt/ml/input/config/hyperparameters.json"
+SM_SECRETS = "secrets.env"
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sagemaker/resources.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sagemaker/resources.py
new file mode 100644
index 0000000000000000000000000000000000000000..4410c755772eead22a846cf25a5beed6fca6cc45
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sagemaker/resources.py
@@ -0,0 +1,63 @@
+from __future__ import annotations
+
+import os
+import secrets
+import socket
+import string
+
+import wandb
+
+from . import config
+from . import files as sm_files
+
+
+def set_run_id(run_settings: wandb.Settings) -> bool:
+ """Set a run ID and group when using SageMaker.
+
+ Returns whether the ID and group were updated.
+ """
+ # Added in https://github.com/wandb/wandb/pull/3290.
+ #
+ # Prevents SageMaker from overriding the run ID configured
+ # in environment variables. Note, however, that it will still
+ # override a run ID passed explicitly to `wandb.init()`.
+ if os.getenv("WANDB_RUN_ID"):
+ return False
+
+ run_group = os.getenv("TRAINING_JOB_NAME")
+ if not run_group:
+ return False
+
+ alphanumeric = string.ascii_lowercase + string.digits
+ random = "".join(secrets.choice(alphanumeric) for _ in range(6))
+
+ host = os.getenv("CURRENT_HOST", socket.gethostname())
+
+ run_settings.run_id = f"{run_group}-{random}-{host}"
+ run_settings.run_group = run_group
+ return True
+
+
+def set_global_settings(settings: wandb.Settings) -> None:
+ """Set global W&B settings based on the SageMaker environment."""
+ if env := parse_sm_secrets():
+ settings.update_from_env_vars(env)
+
+ # The SageMaker config may contain an API key, in which case it
+ # takes precedence over the value in the secrets. It's unclear
+ # whether this is by design, or by accident; we keep it for
+ # backward compatibility for now.
+ sm_config = config.parse_sm_config()
+ if api_key := sm_config.get("wandb_api_key"):
+ settings.api_key = api_key
+
+
+def parse_sm_secrets() -> dict[str, str]:
+ """We read our api_key from secrets.env in SageMaker."""
+ env_dict = dict()
+ # Set secret variables
+ if os.path.exists(sm_files.SM_SECRETS):
+ for line in open(sm_files.SM_SECRETS):
+ key, val = line.strip().split("=", 1)
+ env_dict[key] = val
+ return env_dict
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sb3/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sb3/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..29dd81a941cb1745cf82fecbcf12a857ce786f45
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sb3/__init__.py
@@ -0,0 +1,3 @@
+from .sb3 import WandbCallback
+
+__all__ = ["WandbCallback"]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sb3/sb3.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sb3/sb3.py
new file mode 100644
index 0000000000000000000000000000000000000000..2eec145d0fc052575ca6ba65d68283dcaa0ea69b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sb3/sb3.py
@@ -0,0 +1,147 @@
+"""W&B callback for sb3.
+
+Really simple callback to get logging for each tree
+
+Example usage:
+
+```python
+import gym
+from stable_baselines3 import PPO
+from stable_baselines3.common.monitor import Monitor
+from stable_baselines3.common.vec_env import DummyVecEnv, VecVideoRecorder
+import wandb
+from wandb.integration.sb3 import WandbCallback
+
+
+config = {
+ "policy_type": "MlpPolicy",
+ "total_timesteps": 25000,
+ "env_name": "CartPole-v1",
+}
+run = wandb.init(
+ project="sb3",
+ config=config,
+ sync_tensorboard=True, # auto-upload sb3's tensorboard metrics
+ monitor_gym=True, # auto-upload the videos of agents playing the game
+ save_code=True, # optional
+)
+
+
+def make_env():
+ env = gym.make(config["env_name"])
+ env = Monitor(env) # record stats such as returns
+ return env
+
+
+env = DummyVecEnv([make_env])
+env = VecVideoRecorder(
+ env, "videos", record_video_trigger=lambda x: x % 2000 == 0, video_length=200
+)
+model = PPO(config["policy_type"], env, verbose=1, tensorboard_log=f"runs")
+model.learn(
+ total_timesteps=config["total_timesteps"],
+ callback=WandbCallback(
+ model_save_path=f"models/{run.id}",
+ gradient_save_freq=100,
+ log="all",
+ ),
+)
+```
+"""
+
+import logging
+import os
+from typing import Literal, Optional
+
+from stable_baselines3.common.callbacks import BaseCallback # type: ignore
+
+import wandb
+from wandb.sdk.lib import telemetry as wb_telemetry
+
+logger = logging.getLogger(__name__)
+
+
+class WandbCallback(BaseCallback):
+ """Callback for logging experiments to Weights and Biases.
+
+ Log SB3 experiments to Weights and Biases
+ - Added model tracking and uploading
+ - Added complete hyperparameters recording
+ - Added gradient logging
+ - Note that `wandb.init(...)` must be called before the WandbCallback can be used.
+
+ Args:
+ verbose: The verbosity of sb3 output
+ model_save_path: Path to the folder where the model will be saved, The default value is `None` so the model is not logged
+ model_save_freq: Frequency to save the model
+ gradient_save_freq: Frequency to log gradient. The default value is 0 so the gradients are not logged
+ log: What to log. One of "gradients", "parameters", or "all".
+ """
+
+ def __init__(
+ self,
+ verbose: int = 0,
+ model_save_path: Optional[str] = None,
+ model_save_freq: int = 0,
+ gradient_save_freq: int = 0,
+ log: Optional[Literal["gradients", "parameters", "all"]] = "all",
+ ) -> None:
+ super().__init__(verbose)
+ if wandb.run is None:
+ raise wandb.Error("You must call wandb.init() before WandbCallback()")
+ with wb_telemetry.context() as tel:
+ tel.feature.sb3 = True
+ self.model_save_freq = model_save_freq
+ self.model_save_path = model_save_path
+ self.gradient_save_freq = gradient_save_freq
+ if log not in ["gradients", "parameters", "all", None]:
+ wandb.termwarn(
+ "`log` must be one of `None`, 'gradients', 'parameters', or 'all', "
+ "falling back to 'all'"
+ )
+ log = "all"
+ self.log = log
+ # Create folder if needed
+ if self.model_save_path is not None:
+ os.makedirs(self.model_save_path, exist_ok=True)
+ self.path = os.path.join(self.model_save_path, "model.zip")
+ else:
+ assert self.model_save_freq == 0, (
+ "to use the `model_save_freq` you have to set the `model_save_path` parameter"
+ )
+
+ def _init_callback(self) -> None:
+ d = {}
+ if "algo" not in d:
+ d["algo"] = type(self.model).__name__
+ for key in self.model.__dict__:
+ if key in wandb.config:
+ continue
+ if type(self.model.__dict__[key]) in [float, int, str]:
+ d[key] = self.model.__dict__[key]
+ else:
+ d[key] = str(self.model.__dict__[key])
+ if self.gradient_save_freq > 0:
+ wandb.watch(
+ self.model.policy,
+ log_freq=self.gradient_save_freq,
+ log=self.log,
+ )
+ wandb.config.setdefaults(d)
+
+ def _on_step(self) -> bool:
+ if self.model_save_freq > 0:
+ if self.model_save_path is not None:
+ if self.n_calls % self.model_save_freq == 0:
+ self.save_model()
+ return True
+
+ def _on_training_end(self) -> None:
+ if self.model_save_path is not None:
+ self.save_model()
+
+ def save_model(self) -> None:
+ self.model.save(self.path)
+ wandb.save(self.path, base_path=self.model_save_path)
+ if self.verbose > 1:
+ logger.info(f"Saving model checkpoint to {self.path}")
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb3cb14c923c289c8075c296066f840c3c4e0858
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/__init__.py
@@ -0,0 +1,37 @@
+"""Create informative charts for scikit-learn models and log them to W&B."""
+
+from .plot import (
+ plot_calibration_curve,
+ plot_class_proportions,
+ plot_classifier,
+ plot_clusterer,
+ plot_confusion_matrix,
+ plot_elbow_curve,
+ plot_feature_importances,
+ plot_learning_curve,
+ plot_outlier_candidates,
+ plot_precision_recall,
+ plot_regressor,
+ plot_residuals,
+ plot_roc,
+ plot_silhouette,
+ plot_summary_metrics,
+)
+
+__all__ = [
+ "plot_classifier",
+ "plot_clusterer",
+ "plot_regressor",
+ "plot_summary_metrics",
+ "plot_learning_curve",
+ "plot_feature_importances",
+ "plot_class_proportions",
+ "plot_calibration_curve",
+ "plot_roc",
+ "plot_precision_recall",
+ "plot_confusion_matrix",
+ "plot_elbow_curve",
+ "plot_silhouette",
+ "plot_residuals",
+ "plot_outlier_candidates",
+]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d22d629bbc7dced6da390f885a4d327049491ff
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/__init__.py
@@ -0,0 +1,32 @@
+"""Calculates and formats metrics and charts for introspecting sklearn models.
+
+The functions in these modules are designed to be called by functions from the
+plot submodule that have been exported into the namespace of the wandb.sklearn
+submodule, rather than being called directly.
+"""
+
+from .calibration_curves import calibration_curves
+from .class_proportions import class_proportions
+from .confusion_matrix import confusion_matrix
+from .decision_boundaries import decision_boundaries
+from .elbow_curve import elbow_curve
+from .feature_importances import feature_importances
+from .learning_curve import learning_curve
+from .outlier_candidates import outlier_candidates
+from .residuals import residuals
+from .silhouette import silhouette
+from .summary_metrics import summary_metrics
+
+__all__ = [
+ "calibration_curves",
+ "class_proportions",
+ "confusion_matrix",
+ "decision_boundaries",
+ "elbow_curve",
+ "feature_importances",
+ "learning_curve",
+ "outlier_candidates",
+ "residuals",
+ "silhouette",
+ "summary_metrics",
+]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/calibration_curves.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/calibration_curves.py
new file mode 100644
index 0000000000000000000000000000000000000000..b59aa25d7d8c984ca30529d497eb0e263570c365
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/calibration_curves.py
@@ -0,0 +1,125 @@
+from warnings import simplefilter
+
+import numpy as np
+import sklearn
+from sklearn import model_selection, naive_bayes
+from sklearn.calibration import CalibratedClassifierCV
+from sklearn.linear_model import LogisticRegression
+
+import wandb
+from wandb.integration.sklearn import utils
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def calibration_curves(clf, X, y, clf_name): # noqa: N803
+ # ComplementNB (introduced in 0.20.0) requires non-negative features
+ if int(sklearn.__version__.split(".")[1]) >= 20 and isinstance(
+ clf, naive_bayes.ComplementNB
+ ):
+ X = X - X.min() # noqa:N806
+
+ # Calibrated with isotonic calibration
+ isotonic = CalibratedClassifierCV(clf, cv=2, method="isotonic")
+
+ # Calibrated with sigmoid calibration
+ sigmoid = CalibratedClassifierCV(clf, cv=2, method="sigmoid")
+
+ # Logistic regression with no calibration as baseline
+ lr = LogisticRegression(C=1.0)
+
+ model_column = [] # color
+ frac_positives_column = [] # y axis
+ mean_pred_value_column = [] # x axis
+ hist_column = [] # barchart y
+ edge_column = [] # barchart x
+
+ # Add curve for perfectly calibrated model
+ # format: model, fraction_of_positives, mean_predicted_value
+ model_column.append("Perfectly calibrated")
+ frac_positives_column.append(0)
+ mean_pred_value_column.append(0)
+ hist_column.append(0)
+ edge_column.append(0)
+ model_column.append("Perfectly calibrated")
+ hist_column.append(0)
+ edge_column.append(0)
+ frac_positives_column.append(1)
+ mean_pred_value_column.append(1)
+
+ x_train, x_test, y_train, y_test = model_selection.train_test_split(
+ X, y, test_size=0.9, random_state=42
+ )
+
+ # Add curve for LogisticRegression baseline and other models
+
+ models = [lr, isotonic, sigmoid]
+ names = ["Logistic", f"{clf_name} Isotonic", f"{clf_name} Sigmoid"]
+
+ for model, name in zip(models, names):
+ model.fit(x_train, y_train)
+ if hasattr(model, "predict_proba"):
+ prob_pos = model.predict_proba(x_test)[:, 1]
+ else: # use decision function
+ prob_pos = model.decision_function(x_test)
+ prob_pos = (prob_pos - prob_pos.min()) / (prob_pos.max() - prob_pos.min())
+
+ hist, edges = np.histogram(prob_pos, bins=10, density=False)
+ frac_positives, mean_pred_value = sklearn.calibration.calibration_curve(
+ y_test, prob_pos, n_bins=10
+ )
+
+ # format: model, fraction_of_positives, mean_predicted_value
+ num_entries = len(frac_positives)
+ for i in range(num_entries):
+ hist_column.append(hist[i])
+ edge_column.append(edges[i])
+ model_column.append(name)
+ frac_positives_column.append(utils.round_3(frac_positives[i]))
+ mean_pred_value_column.append(utils.round_3(mean_pred_value[i]))
+ if utils.check_against_limit(
+ i,
+ "calibration_curve",
+ utils.chart_limit - 2,
+ ):
+ break
+
+ table = make_table(
+ model_column,
+ frac_positives_column,
+ mean_pred_value_column,
+ hist_column,
+ edge_column,
+ )
+ chart = wandb.visualize("wandb/calibration/v1", table)
+
+ return chart
+
+
+def make_table(
+ model_column,
+ frac_positives_column,
+ mean_pred_value_column,
+ hist_column,
+ edge_column,
+):
+ columns = [
+ "model",
+ "fraction_of_positives",
+ "mean_predicted_value",
+ "hist_dict",
+ "edge_dict",
+ ]
+
+ data = list(
+ zip(
+ model_column,
+ frac_positives_column,
+ mean_pred_value_column,
+ hist_column,
+ edge_column,
+ )
+ )
+
+ return wandb.Table(columns=columns, data=data)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/class_proportions.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/class_proportions.py
new file mode 100644
index 0000000000000000000000000000000000000000..183bf785a2fb62e2efe20fbdfde68f7a0fc45024
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/class_proportions.py
@@ -0,0 +1,68 @@
+from warnings import simplefilter
+
+import numpy as np
+from sklearn.utils.multiclass import unique_labels
+
+import wandb
+from wandb.integration.sklearn import utils
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def class_proportions(y_train, y_test, labels):
+ # Get the unique values from the dataset
+ targets = (y_train,) if y_test is None else (y_train, y_test)
+ class_ids = np.array(unique_labels(*targets))
+
+ # Compute the class counts
+ counts_train = np.array([(y_train == c).sum() for c in class_ids])
+ counts_test = np.array([(y_test == c).sum() for c in class_ids])
+
+ class_column, dataset_column, count_column = make_columns(
+ class_ids, counts_train, counts_test
+ )
+
+ if labels is not None and (
+ isinstance(class_column[0], int) or isinstance(class_column[0], np.integer)
+ ):
+ class_column = get_named_labels(labels, class_column)
+
+ table = make_table(class_column, dataset_column, count_column)
+ chart = wandb.visualize("wandb/class_proportions/v1", table)
+
+ return chart
+
+
+def make_table(class_column, dataset_column, count_column):
+ columns = ["class", "dataset", "count"]
+ data = list(zip(class_column, dataset_column, count_column))
+
+ return wandb.Table(data=data, columns=columns)
+
+
+def make_columns(class_ids, counts_train, counts_test):
+ class_column, dataset_column, count_column = [], [], []
+
+ for i in range(len(class_ids)):
+ # add class counts from training set
+ class_column.append(class_ids[i])
+ dataset_column.append("train")
+ count_column.append(counts_train[i])
+ # add class counts from test set
+ class_column.append(class_ids[i])
+ dataset_column.append("test")
+ count_column.append(counts_test[i])
+
+ if utils.check_against_limit(
+ i,
+ "class_proportions",
+ utils.chart_limit,
+ ):
+ break
+
+ return class_column, dataset_column, count_column
+
+
+def get_named_labels(labels, numeric_labels):
+ return np.array([labels[num_label] for num_label in numeric_labels])
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/confusion_matrix.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/confusion_matrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..777c84ada92237222e0a058c5facd7b761313b12
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/confusion_matrix.py
@@ -0,0 +1,93 @@
+import itertools
+from warnings import simplefilter
+
+import numpy as np
+from sklearn import metrics
+from sklearn.utils.multiclass import unique_labels
+
+import wandb
+
+from .. import utils
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def validate_labels(*args, **kwargs): # FIXME
+ raise AssertionError()
+
+
+def confusion_matrix(
+ y_true=None,
+ y_pred=None,
+ labels=None,
+ true_labels=None,
+ pred_labels=None,
+ normalize=False,
+):
+ """Compute the confusion matrix to evaluate the performance of a classification.
+
+ Called by plot_confusion_matrix to visualize roc curves. Please use the function
+ plot_confusion_matrix() if you wish to visualize your confusion matrix.
+ """
+ cm = metrics.confusion_matrix(y_true, y_pred)
+
+ if labels is None:
+ classes = unique_labels(y_true, y_pred)
+ else:
+ classes = np.asarray(labels)
+
+ if normalize:
+ cm = cm.astype("float") / cm.sum(axis=1)[:, np.newaxis]
+ cm = np.around(cm, decimals=2)
+ cm[np.isnan(cm)] = 0.0
+
+ if true_labels is None:
+ true_classes = classes
+ else:
+ validate_labels(classes, true_labels, "true_labels")
+
+ true_label_indexes = np.in1d(classes, true_labels)
+
+ true_classes = classes[true_label_indexes]
+ cm = cm[true_label_indexes]
+
+ if pred_labels is None:
+ pred_classes = classes
+ else:
+ validate_labels(classes, pred_labels, "pred_labels")
+
+ pred_label_indexes = np.in1d(classes, pred_labels)
+
+ pred_classes = classes[pred_label_indexes]
+ cm = cm[:, pred_label_indexes]
+
+ table = make_table(cm, pred_classes, true_classes, labels)
+ chart = wandb.visualize("wandb/confusion_matrix/v1", table)
+
+ return chart
+
+
+def make_table(cm, pred_classes, true_classes, labels):
+ data, count = [], 0
+ for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
+ if labels is not None and (
+ isinstance(pred_classes[i], int) or isinstance(pred_classes[0], np.integer)
+ ):
+ pred = labels[pred_classes[i]]
+ true = labels[true_classes[j]]
+ else:
+ pred = pred_classes[i]
+ true = true_classes[j]
+ data.append([pred, true, cm[i, j]])
+ count += 1
+ if utils.check_against_limit(
+ count,
+ "confusion_matrix",
+ utils.chart_limit,
+ ):
+ break
+
+ table = wandb.Table(columns=["Predicted", "Actual", "Count"], data=data)
+
+ return table
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/decision_boundaries.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/decision_boundaries.py
new file mode 100644
index 0000000000000000000000000000000000000000..a7a849b86b151270adf2437e4f2e72a03ce6c1a9
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/decision_boundaries.py
@@ -0,0 +1,40 @@
+from warnings import simplefilter
+
+import wandb
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def decision_boundaries(
+ decision_boundary_x,
+ decision_boundary_y,
+ decision_boundary_color,
+ train_x,
+ train_y,
+ train_color,
+ test_x,
+ test_y,
+ test_color,
+):
+ x_dict, y_dict, color_dict = [], [], []
+ for i in range(min(len(decision_boundary_x), 100)):
+ x_dict.append(decision_boundary_x[i])
+ y_dict.append(decision_boundary_y[i])
+ color_dict.append(decision_boundary_color)
+ for i in range(300):
+ x_dict.append(test_x[i])
+ y_dict.append(test_y[i])
+ color_dict.append(test_color[i])
+ for i in range(min(len(train_x), 600)):
+ x_dict.append(train_x[i])
+ y_dict.append(train_y[i])
+ color_dict.append(train_color[i])
+
+ return wandb.visualize(
+ "wandb/decision_boundaries/v1",
+ wandb.Table(
+ columns=["x", "y", "color"],
+ data=[[x_dict[i], y_dict[i], color_dict[i]] for i in range(len(x_dict))],
+ ),
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/elbow_curve.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/elbow_curve.py
new file mode 100644
index 0000000000000000000000000000000000000000..731102d75adabf238d44de00b8d79bca59f0a87a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/elbow_curve.py
@@ -0,0 +1,55 @@
+import time
+from warnings import simplefilter
+
+import numpy as np
+from joblib import Parallel, delayed
+from sklearn.base import clone
+
+import wandb
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def elbow_curve(clusterer, X, cluster_ranges, n_jobs, show_cluster_time): # noqa: N803
+ if cluster_ranges is None:
+ cluster_ranges = range(1, 10, 2)
+ else:
+ cluster_ranges = sorted(cluster_ranges)
+
+ clfs, times = _compute_results_parallel(n_jobs, clusterer, X, cluster_ranges)
+
+ clfs = np.absolute(clfs)
+
+ table = make_table(cluster_ranges, clfs, times)
+ chart = wandb.visualize("wandb/elbow/v1", table)
+
+ return chart
+
+
+def make_table(cluster_ranges, clfs, times):
+ columns = ["cluster_ranges", "errors", "clustering_time"]
+
+ data = list(zip(cluster_ranges, clfs, times))
+
+ table = wandb.Table(columns=columns, data=data)
+
+ return table
+
+
+def _compute_results_parallel(n_jobs, clusterer, x, cluster_ranges):
+ parallel_runner = Parallel(n_jobs=n_jobs)
+ _cluster_scorer = delayed(_clone_and_score_clusterer)
+ results = parallel_runner(_cluster_scorer(clusterer, x, i) for i in cluster_ranges)
+
+ clfs, times = zip(*results)
+
+ return clfs, times
+
+
+def _clone_and_score_clusterer(clusterer, x, n_clusters):
+ start = time.time()
+ clusterer = clone(clusterer)
+ clusterer.n_clusters = n_clusters
+
+ return clusterer.fit(x).score(x), time.time() - start
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/feature_importances.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/feature_importances.py
new file mode 100644
index 0000000000000000000000000000000000000000..fac0452b944fd31d3bf611df054f4f6c0dbc0895
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/feature_importances.py
@@ -0,0 +1,67 @@
+from warnings import simplefilter
+
+import numpy as np
+
+import wandb
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def feature_importances(model, feature_names):
+ attributes_to_check = ["feature_importances_", "feature_log_prob_", "coef_"]
+ found_attribute = check_for_attribute_on(model, attributes_to_check)
+ if found_attribute is None:
+ wandb.termwarn(
+ f"could not find any of attributes {', '.join(attributes_to_check)} on classifier. Cannot plot feature importances."
+ )
+ return
+ elif found_attribute == "feature_importances_":
+ importances = model.feature_importances_
+ elif found_attribute == "coef_": # ElasticNet-like models
+ importances = model.coef_
+ elif found_attribute == "feature_log_prob_":
+ # coef_ was deprecated in sklearn 0.24, replaced with
+ # feature_log_prob_
+ importances = model.feature_log_prob_
+
+ if len(importances.shape) > 1:
+ n_significant_dims = sum(i > 1 for i in importances.shape)
+ if n_significant_dims > 1:
+ nd = len(importances.shape)
+ wandb.termwarn(
+ f"{nd}-dimensional feature importances array passed to plot_feature_importances. "
+ f"{nd}-dimensional and higher feature importances arrays are not currently supported. "
+ f"These importances will not be plotted."
+ )
+ return
+ else:
+ importances = np.squeeze(importances)
+
+ indices = np.argsort(importances)[::-1]
+ importances = importances[indices]
+
+ if feature_names is None:
+ feature_names = indices
+ else:
+ feature_names = np.array(feature_names)[indices]
+
+ table = make_table(feature_names, importances)
+ chart = wandb.visualize("wandb/feature_importances/v1", table)
+
+ return chart
+
+
+def make_table(feature_names, importances):
+ table = wandb.Table(
+ columns=["feature_names", "importances"],
+ data=[[feature_names[i], importances[i]] for i in range(len(feature_names))],
+ )
+ return table
+
+
+def check_for_attribute_on(model, attributes_to_check):
+ for attr in attributes_to_check:
+ if hasattr(model, attr):
+ return attr
+ return None
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/learning_curve.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/learning_curve.py
new file mode 100644
index 0000000000000000000000000000000000000000..296c7d7780fec21e5f9e3a7a346301c3c38b7de8
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/learning_curve.py
@@ -0,0 +1,64 @@
+from warnings import simplefilter
+
+import numpy as np
+from sklearn import model_selection
+
+import wandb
+from wandb.integration.sklearn import utils
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def learning_curve(
+ model,
+ X, # noqa: N803
+ y,
+ cv=None,
+ shuffle=False,
+ random_state=None,
+ train_sizes=None,
+ n_jobs=1,
+ scoring=None,
+):
+ """Train model on datasets of varying size and generates plot of score vs size.
+
+ Called by plot_learning_curve to visualize learning curve. Please use the function
+ plot_learning_curve() if you wish to visualize your learning curves.
+ """
+ train_sizes, train_scores, test_scores = model_selection.learning_curve(
+ model,
+ X,
+ y,
+ cv=cv,
+ n_jobs=n_jobs,
+ train_sizes=train_sizes,
+ scoring=scoring,
+ shuffle=shuffle,
+ random_state=random_state,
+ )
+ train_scores_mean = np.mean(train_scores, axis=1)
+ test_scores_mean = np.mean(test_scores, axis=1)
+
+ table = make_table(train_scores_mean, test_scores_mean, train_sizes)
+ chart = wandb.visualize("wandb/learning_curve/v1", table)
+
+ return chart
+
+
+def make_table(train, test, train_sizes):
+ data = []
+ for i in range(len(train)):
+ if utils.check_against_limit(
+ i,
+ "learning_curve",
+ utils.chart_limit / 2,
+ ):
+ break
+ train_set = ["train", utils.round_2(train[i]), train_sizes[i]]
+ test_set = ["test", utils.round_2(test[i]), train_sizes[i]]
+ data.append(train_set)
+ data.append(test_set)
+
+ table = wandb.Table(columns=["dataset", "score", "train_size"], data=data)
+ return table
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/outlier_candidates.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/outlier_candidates.py
new file mode 100644
index 0000000000000000000000000000000000000000..5fb0a29f4e7c49939e2d34420c02f9d82d08570b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/outlier_candidates.py
@@ -0,0 +1,69 @@
+from warnings import simplefilter
+
+import numpy as np
+
+import wandb
+from wandb.integration.sklearn import utils
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def outlier_candidates(regressor, X, y): # noqa: N803
+ # Fit a linear model to X and y to compute MSE
+ regressor.fit(X, y)
+
+ # Leverage is computed as the diagonal of the projection matrix of X
+ leverage = (X * np.linalg.pinv(X).T).sum(1)
+
+ # Compute the rank and the degrees of freedom of the OLS model
+ rank = np.linalg.matrix_rank(X)
+ df = X.shape[0] - rank
+
+ # Compute the MSE from the residuals
+ residuals = y - regressor.predict(X)
+ mse = np.dot(residuals, residuals) / df
+
+ # Compute Cook's distance
+ residuals_studentized = residuals / np.sqrt(mse) / np.sqrt(1 - leverage)
+ distance_ = residuals_studentized**2 / X.shape[1]
+ distance_ *= leverage / (1 - leverage)
+
+ # Compute the influence threshold rule of thumb
+ influence_threshold_ = 4 / X.shape[0]
+ outlier_percentage_ = sum(distance_ >= influence_threshold_) / X.shape[0]
+ outlier_percentage_ *= 100.0
+
+ distance_dict, count = [], 0
+ for d in distance_:
+ distance_dict.append(d)
+ count += 1
+ if utils.check_against_limit(
+ count,
+ "outlier_candidates",
+ utils.chart_limit,
+ ):
+ break
+
+ table = make_table(distance_dict, outlier_percentage_, influence_threshold_)
+ chart = wandb.visualize("wandb/outliers/v1", table)
+
+ return chart
+
+
+def make_table(distance, outlier_percentage, influence_threshold):
+ columns = [
+ "distance",
+ "instance_indicies",
+ "outlier_percentage",
+ "influence_threshold",
+ ]
+
+ data = [
+ [distance[i], i, utils.round_3(outlier_percentage), influence_threshold]
+ for i in range(len(distance))
+ ]
+
+ table = wandb.Table(columns=columns, data=data)
+
+ return table
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/residuals.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/residuals.py
new file mode 100644
index 0000000000000000000000000000000000000000..b45df7b84fa5b3824f99425800bbf0039f7cacd8
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/residuals.py
@@ -0,0 +1,86 @@
+from warnings import simplefilter
+
+from sklearn import model_selection
+
+import wandb
+from wandb.integration.sklearn import utils
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def residuals(regressor, X, y): # noqa: N803
+ # Create the train and test splits
+ x_train, x_test, y_train, y_test = model_selection.train_test_split(
+ X, y, test_size=0.2
+ )
+
+ # Store labels and colors for the legend ordered by call
+ regressor.fit(x_train, y_train)
+ train_score_ = regressor.score(x_train, y_train)
+ test_score_ = regressor.score(x_test, y_test)
+
+ y_pred_train = regressor.predict(x_train)
+ residuals_train = y_pred_train - y_train
+
+ y_pred_test = regressor.predict(x_test)
+ residuals_test = y_pred_test - y_test
+
+ table = make_table(
+ y_pred_train,
+ residuals_train,
+ y_pred_test,
+ residuals_test,
+ train_score_,
+ test_score_,
+ )
+ chart = wandb.visualize("wandb/residuals_plot/v1", table)
+
+ return chart
+
+
+def make_table(
+ y_pred_train,
+ residuals_train,
+ y_pred_test,
+ residuals_test,
+ train_score_,
+ test_score_,
+):
+ y_pred_column, dataset_column, residuals_column = [], [], []
+
+ datapoints, max_datapoints_train = 0, 100
+ for pred, residual in zip(y_pred_train, residuals_train):
+ # add class counts from training set
+ y_pred_column.append(pred)
+ dataset_column.append("train")
+ residuals_column.append(residual)
+ datapoints += 1
+ if utils.check_against_limit(datapoints, "residuals", max_datapoints_train):
+ break
+
+ datapoints = 0
+ for pred, residual in zip(y_pred_test, residuals_test):
+ # add class counts from training set
+ y_pred_column.append(pred)
+ dataset_column.append("test")
+ residuals_column.append(residual)
+ datapoints += 1
+ if utils.check_against_limit(datapoints, "residuals", max_datapoints_train):
+ break
+
+ columns = ["dataset", "y_pred", "residuals", "train_score", "test_score"]
+ data = [
+ [
+ dataset_column[i],
+ y_pred_column[i],
+ residuals_column[i],
+ train_score_,
+ test_score_,
+ ]
+ for i in range(len(y_pred_column))
+ ]
+
+ table = wandb.Table(columns=columns, data=data)
+
+ return table
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/silhouette.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/silhouette.py
new file mode 100644
index 0000000000000000000000000000000000000000..a71ba88c8f03d99e6908e4f886ba5d0be4f4dd41
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/silhouette.py
@@ -0,0 +1,118 @@
+from warnings import simplefilter
+
+import numpy as np
+from sklearn.metrics import silhouette_samples, silhouette_score
+from sklearn.preprocessing import LabelEncoder
+
+import wandb
+from wandb.integration.sklearn import utils
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def silhouette(clusterer, X, cluster_labels, labels, metric, kmeans): # noqa: N803
+ # Run clusterer for n_clusters in range(len(cluster_ranges), get cluster labels
+ # TODO - keep/delete once we decide if we should train clusterers
+ # or ask for trained models
+ # clusterer.set_params(n_clusters=n_clusters, random_state=42)
+ # cluster_labels = clusterer.fit_predict(X)
+ cluster_labels = np.asarray(cluster_labels)
+ labels = np.asarray(labels)
+
+ le = LabelEncoder()
+ _ = le.fit_transform(cluster_labels)
+ n_clusters = len(np.unique(cluster_labels))
+
+ # The silhouette_score gives the average value for all the samples.
+ # This gives a perspective into the density and separation of the formed
+ # clusters
+ silhouette_avg = silhouette_score(X, cluster_labels, metric=metric)
+
+ # Compute the silhouette scores for each sample
+ sample_silhouette_values = silhouette_samples(X, cluster_labels, metric=metric)
+
+ x_sil, y_sil, color_sil = [], [], []
+
+ count, y_lower = 0, 10
+ for i in range(n_clusters):
+ # Aggregate the silhouette scores for samples belonging to
+ # cluster i, and sort them
+ ith_cluster_silhouette_values = sample_silhouette_values[cluster_labels == i]
+
+ ith_cluster_silhouette_values.sort()
+
+ size_cluster_i = ith_cluster_silhouette_values.shape[0]
+ y_upper = y_lower + size_cluster_i
+
+ y_values = np.arange(y_lower, y_upper)
+
+ for j in range(len(y_values)):
+ y_sil.append(y_values[j])
+ x_sil.append(ith_cluster_silhouette_values[j])
+ color_sil.append(i)
+ count += 1
+ if utils.check_against_limit(count, "silhouette", utils.chart_limit):
+ break
+
+ # Compute the new y_lower for next plot
+ y_lower = y_upper + 10 # 10 for the 0 samples
+
+ if kmeans:
+ centers = clusterer.cluster_centers_
+ centerx = centers[:, 0]
+ centery = centers[:, 1]
+
+ else:
+ centerx = [None] * len(color_sil)
+ centery = [None] * len(color_sil)
+
+ table = make_table(
+ X[:, 0],
+ X[:, 1],
+ cluster_labels,
+ centerx,
+ centery,
+ y_sil,
+ x_sil,
+ color_sil,
+ silhouette_avg,
+ )
+ chart = wandb.visualize("wandb/silhouette_/v1", table)
+
+ return chart
+
+
+def make_table(x, y, colors, centerx, centery, y_sil, x_sil, color_sil, silhouette_avg):
+ columns = [
+ "x",
+ "y",
+ "colors",
+ "centerx",
+ "centery",
+ "y_sil",
+ "x1",
+ "x2",
+ "color_sil",
+ "silhouette_avg",
+ ]
+
+ data = [
+ [
+ x[i],
+ y[i],
+ colors[i],
+ centerx[colors[i]],
+ centery[colors[i]],
+ y_sil[i],
+ 0,
+ x_sil[i],
+ color_sil[i],
+ silhouette_avg,
+ ]
+ for i in range(len(color_sil))
+ ]
+
+ table = wandb.Table(data=data, columns=columns)
+
+ return table
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/summary_metrics.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/summary_metrics.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4b6f25ead2fd3c94c302db7693ca3fd529812d9
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/calculate/summary_metrics.py
@@ -0,0 +1,62 @@
+from warnings import simplefilter
+
+import numpy as np
+import sklearn
+
+import wandb
+from wandb.integration.sklearn import utils
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def summary_metrics(model=None, X=None, y=None, X_test=None, y_test=None): # noqa: N803
+ """Calculate summary metrics for both regressors and classifiers.
+
+ Called by plot_summary_metrics to visualize metrics. Please use the function
+ plot_summary_metrics() if you wish to visualize your summary metrics.
+ """
+ y, y_test = np.asarray(y), np.asarray(y_test)
+ metrics = {}
+ model_name = model.__class__.__name__
+
+ y_pred = model.predict(X_test)
+
+ if sklearn.base.is_classifier(model):
+ accuracy_score = sklearn.metrics.accuracy_score(y_test, y_pred)
+ metrics["accuracy_score"] = accuracy_score
+
+ precision = sklearn.metrics.precision_score(y_test, y_pred, average="weighted")
+ metrics["precision"] = precision
+
+ recall = sklearn.metrics.recall_score(y_test, y_pred, average="weighted")
+ metrics["recall"] = recall
+
+ f1_score = sklearn.metrics.f1_score(y_test, y_pred, average="weighted")
+ metrics["f1_score"] = f1_score
+
+ elif sklearn.base.is_regressor(model):
+ mae = sklearn.metrics.mean_absolute_error(y_test, y_pred)
+ metrics["mae"] = mae
+
+ mse = sklearn.metrics.mean_squared_error(y_test, y_pred)
+ metrics["mse"] = mse
+
+ r2_score = sklearn.metrics.r2_score(y_test, y_pred)
+ metrics["r2_score"] = r2_score
+
+ metrics = {name: utils.round_2(metric) for name, metric in metrics.items()}
+
+ table = make_table(metrics, model_name)
+ chart = wandb.visualize("wandb/metrics/v1", table)
+
+ return chart
+
+
+def make_table(metrics, model_name):
+ columns = ["metric_name", "metric_value", "model_name"]
+ table_content = [[name, value, model_name] for name, value in metrics.items()]
+
+ table = wandb.Table(columns=columns, data=table_content)
+
+ return table
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/plot/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/plot/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..710e24c010e108bb4f25d361092a55182ad26917
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/plot/__init__.py
@@ -0,0 +1,35 @@
+"""Create and logs charts introspecting models built with scikit-learn to W&B."""
+
+from .classifier import calibration_curve as plot_calibration_curve
+from .classifier import class_proportions as plot_class_proportions
+from .classifier import classifier as plot_classifier
+from .classifier import confusion_matrix as plot_confusion_matrix
+from .classifier import feature_importances as plot_feature_importances
+from .classifier import precision_recall as plot_precision_recall
+from .classifier import roc as plot_roc
+from .clusterer import clusterer as plot_clusterer
+from .clusterer import elbow_curve as plot_elbow_curve
+from .clusterer import silhouette as plot_silhouette
+from .regressor import outlier_candidates as plot_outlier_candidates
+from .regressor import regressor as plot_regressor
+from .regressor import residuals as plot_residuals
+from .shared import learning_curve as plot_learning_curve
+from .shared import summary_metrics as plot_summary_metrics
+
+__all__ = [
+ "plot_classifier",
+ "plot_clusterer",
+ "plot_regressor",
+ "plot_summary_metrics",
+ "plot_learning_curve",
+ "plot_feature_importances",
+ "plot_class_proportions",
+ "plot_calibration_curve",
+ "plot_roc",
+ "plot_precision_recall",
+ "plot_confusion_matrix",
+ "plot_elbow_curve",
+ "plot_silhouette",
+ "plot_residuals",
+ "plot_outlier_candidates",
+]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/plot/classifier.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/plot/classifier.py
new file mode 100644
index 0000000000000000000000000000000000000000..e431c8090b565518315f7906c85314f7d4b0ad9b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/plot/classifier.py
@@ -0,0 +1,329 @@
+"""Define plots for classification models built with scikit-learn."""
+
+from warnings import simplefilter
+
+import numpy as np
+from sklearn import naive_bayes
+
+import wandb
+import wandb.plot
+from wandb.integration.sklearn import calculate, utils
+
+from . import shared
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def classifier(
+ model,
+ X_train, # noqa: N803
+ X_test, # noqa: N803
+ y_train,
+ y_test,
+ y_pred,
+ y_probas,
+ labels,
+ is_binary=False,
+ model_name="Classifier",
+ feature_names=None,
+ log_learning_curve=False,
+):
+ """Generate all sklearn classifier plots supported by W&B.
+
+ The following plots are generated:
+ feature importances, confusion matrix, summary metrics,
+ class proportions, calibration curve, roc curve, precision-recall curve.
+
+ Should only be called with a fitted classifier (otherwise an error is thrown).
+
+ Args:
+ model: (classifier) Takes in a fitted classifier.
+ X_train: (arr) Training set features.
+ y_train: (arr) Training set labels.
+ X_test: (arr) Test set features.
+ y_test: (arr) Test set labels.
+ y_pred: (arr) Test set predictions by the model passed.
+ y_probas: (arr) Test set predicted probabilities by the model passed.
+ labels: (list) Named labels for target variable (y). Makes plots easier to
+ read by replacing target values with corresponding index.
+ For example if `labels=['dog', 'cat', 'owl']` all 0s are
+ replaced by dog, 1s by cat.
+ is_binary: (bool) Is the model passed a binary classifier? Defaults to False
+ model_name: (str) Model name. Defaults to 'Classifier'
+ feature_names: (list) Names for features. Makes plots easier to read by
+ replacing feature indexes with corresponding names.
+ log_learning_curve: (bool) Whether or not to log the learning curve.
+ Defaults to False.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_classifier(
+ model,
+ X_train,
+ X_test,
+ y_train,
+ y_test,
+ y_pred,
+ y_probas,
+ ["cat", "dog"],
+ False,
+ "RandomForest",
+ ["barks", "drools", "plays_fetch", "breed"],
+ )
+ ```
+ """
+ wandb.termlog(f"\nPlotting {model_name}.")
+
+ if not isinstance(model, naive_bayes.MultinomialNB):
+ feature_importances(model, feature_names)
+ wandb.termlog("Logged feature importances.")
+
+ if log_learning_curve:
+ shared.learning_curve(model, X_train, y_train)
+ wandb.termlog("Logged learning curve.")
+
+ confusion_matrix(y_test, y_pred, labels)
+ wandb.termlog("Logged confusion matrix.")
+
+ shared.summary_metrics(model, X=X_train, y=y_train, X_test=X_test, y_test=y_test)
+ wandb.termlog("Logged summary metrics.")
+
+ class_proportions(y_train, y_test, labels)
+ wandb.termlog("Logged class proportions.")
+
+ if not isinstance(model, naive_bayes.MultinomialNB):
+ calibration_curve(model, X_train, y_train, model_name)
+ wandb.termlog("Logged calibration curve.")
+
+ roc(y_test, y_probas, labels)
+ wandb.termlog("Logged roc curve.")
+
+ precision_recall(y_test, y_probas, labels)
+ wandb.termlog("Logged precision-recall curve.")
+
+
+def roc(
+ y_true=None,
+ y_probas=None,
+ labels=None,
+ plot_micro=True,
+ plot_macro=True,
+ classes_to_plot=None,
+):
+ """Log the receiver-operating characteristic curve.
+
+ Args:
+ y_true: (arr) Test set labels.
+ y_probas: (arr) Test set predicted probabilities.
+ labels: (list) Named labels for target variable (y). Makes plots easier to
+ read by replacing target values with corresponding index.
+ For example if `labels=['dog', 'cat', 'owl']` all 0s are
+ replaced by dog, 1s by cat.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_roc(y_true, y_probas, labels)
+ ```
+ """
+ roc_chart = wandb.plot.roc_curve(y_true, y_probas, labels, classes_to_plot)
+ wandb.log({"roc": roc_chart})
+
+
+def confusion_matrix(
+ y_true=None,
+ y_pred=None,
+ labels=None,
+ true_labels=None,
+ pred_labels=None,
+ normalize=False,
+):
+ """Log a confusion matrix to W&B.
+
+ Confusion matrices depict the pattern of misclassifications by a model.
+
+ Args:
+ y_true: (arr) Test set labels.
+ y_probas: (arr) Test set predicted probabilities.
+ labels: (list) Named labels for target variable (y). Makes plots easier to
+ read by replacing target values with corresponding index.
+ For example if `labels=['dog', 'cat', 'owl']` all 0s are
+ replaced by dog, 1s by cat.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_confusion_matrix(y_true, y_probas, labels)
+ ```
+ """
+ y_true = np.asarray(y_true)
+ y_pred = np.asarray(y_pred)
+
+ not_missing = utils.test_missing(y_true=y_true, y_pred=y_pred)
+ correct_types = utils.test_types(y_true=y_true, y_pred=y_pred)
+
+ if not_missing and correct_types:
+ confusion_matrix_chart = calculate.confusion_matrix(
+ y_true,
+ y_pred,
+ labels,
+ true_labels,
+ pred_labels,
+ normalize,
+ )
+
+ wandb.log({"confusion_matrix": confusion_matrix_chart})
+
+
+def precision_recall(
+ y_true=None, y_probas=None, labels=None, plot_micro=True, classes_to_plot=None
+):
+ """Log a precision-recall curve to W&B.
+
+ Precision-recall curves depict the tradeoff between positive predictive value (precision)
+ and true positive rate (recall) as the threshold of a classifier is shifted.
+
+ Args:
+ y_true: (arr) Test set labels.
+ y_probas: (arr) Test set predicted probabilities.
+ labels: (list) Named labels for target variable (y). Makes plots easier to
+ read by replacing target values with corresponding index.
+ For example if `labels=['dog', 'cat', 'owl']` all 0s are
+ replaced by dog, 1s by cat.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_precision_recall(y_true, y_probas, labels)
+ ```
+ """
+ precision_recall_chart = wandb.plot.pr_curve(
+ y_true, y_probas, labels, classes_to_plot
+ )
+
+ wandb.log({"precision_recall": precision_recall_chart})
+
+
+def feature_importances(
+ model=None, feature_names=None, title="Feature Importance", max_num_features=50
+):
+ """Log a plot depicting the relative importance of each feature for a classifier's decisions.
+
+ Should only be called with a fitted classifier (otherwise an error is thrown).
+ Only works with classifiers that have a feature_importances_ attribute, like trees.
+
+ Args:
+ model: (clf) Takes in a fitted classifier.
+ feature_names: (list) Names for features. Makes plots easier to read by
+ replacing feature indexes with corresponding names.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_feature_importances(model, ["width", "height", "length"])
+ ```
+ """
+ not_missing = utils.test_missing(model=model)
+ correct_types = utils.test_types(model=model)
+ model_fitted = utils.test_fitted(model)
+
+ if not_missing and correct_types and model_fitted:
+ feature_importance_chart = calculate.feature_importances(model, feature_names)
+ wandb.log({"feature_importances": feature_importance_chart})
+
+
+def class_proportions(y_train=None, y_test=None, labels=None):
+ """Plot the distribution of target classes in training and test sets.
+
+ Useful for detecting imbalanced classes.
+
+ Args:
+ y_train: (arr) Training set labels.
+ y_test: (arr) Test set labels.
+ labels: (list) Named labels for target variable (y). Makes plots easier to
+ read by replacing target values with corresponding index.
+ For example if `labels=['dog', 'cat', 'owl']` all 0s are
+ replaced by dog, 1s by cat.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_class_proportions(y_train, y_test, ["dog", "cat", "owl"])
+ ```
+ """
+ not_missing = utils.test_missing(y_train=y_train, y_test=y_test)
+ correct_types = utils.test_types(y_train=y_train, y_test=y_test)
+ if not_missing and correct_types:
+ y_train, y_test = np.array(y_train), np.array(y_test)
+ class_proportions_chart = calculate.class_proportions(y_train, y_test, labels)
+
+ wandb.log({"class_proportions": class_proportions_chart})
+
+
+def calibration_curve(clf=None, X=None, y=None, clf_name="Classifier"): # noqa: N803
+ """Log a plot depicting how well-calibrated the predicted probabilities of a classifier are.
+
+ Also suggests how to calibrate an uncalibrated classifier. Compares estimated predicted
+ probabilities by a baseline logistic regression model, the model passed as
+ an argument, and by both its isotonic calibration and sigmoid calibrations.
+ The closer the calibration curves are to a diagonal the better.
+ A sine wave like curve represents an overfitted classifier, while a cosine
+ wave like curve represents an underfitted classifier.
+ By training isotonic and sigmoid calibrations of the model and comparing
+ their curves we can figure out whether the model is over or underfitting and
+ if so which calibration (sigmoid or isotonic) might help fix this.
+ For more details, see https://scikit-learn.org/stable/auto_examples/calibration/plot_calibration_curve.html.
+
+ Should only be called with a fitted classifier (otherwise an error is thrown).
+
+ Please note this function fits variations of the model on the training set when called.
+
+ Args:
+ clf: (clf) Takes in a fitted classifier.
+ X: (arr) Training set features.
+ y: (arr) Training set labels.
+ model_name: (str) Model name. Defaults to 'Classifier'
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_calibration_curve(clf, X, y, "RandomForestClassifier")
+ ```
+ """
+ not_missing = utils.test_missing(clf=clf, X=X, y=y)
+ correct_types = utils.test_types(clf=clf, X=X, y=y)
+ is_fitted = utils.test_fitted(clf)
+ if not_missing and correct_types and is_fitted:
+ y = np.asarray(y)
+ if y.dtype.char == "U" or not ((y == 0) | (y == 1)).all():
+ wandb.termwarn(
+ "This function only supports binary classification at the moment and therefore expects labels to be binary. Skipping calibration curve."
+ )
+ return
+
+ calibration_curve_chart = calculate.calibration_curves(clf, X, y, clf_name)
+
+ wandb.log({"calibration_curve": calibration_curve_chart})
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/plot/clusterer.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/plot/clusterer.py
new file mode 100644
index 0000000000000000000000000000000000000000..bced65ae105780961e434b78e6ef316297b5182e
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/plot/clusterer.py
@@ -0,0 +1,146 @@
+"""Define plots for clustering models built with scikit-learn."""
+
+from warnings import simplefilter
+
+import pandas as pd
+import sklearn
+
+import wandb
+from wandb.integration.sklearn import calculate, utils
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def clusterer(model, X_train, cluster_labels, labels=None, model_name="Clusterer"): # noqa: N803
+ """Generates all sklearn clusterer plots supported by W&B.
+
+ The following plots are generated:
+ elbow curve, silhouette plot.
+
+ Should only be called with a fitted clusterer (otherwise an error is thrown).
+
+ Args:
+ model: (clusterer) Takes in a fitted clusterer.
+ X_train: (arr) Training set features.
+ cluster_labels: (list) Names for cluster labels. Makes plots easier to read
+ by replacing cluster indexes with corresponding names.
+ labels: (list) Named labels for target variable (y). Makes plots easier to
+ read by replacing target values with corresponding index.
+ For example if `labels=['dog', 'cat', 'owl']` all 0s are
+ replaced by dog, 1s by cat.
+ model_name: (str) Model name. Defaults to 'Clusterer'
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_clusterer(kmeans, X, cluster_labels, labels, "KMeans")
+ ```
+ """
+ wandb.termlog(f"\nPlotting {model_name}.")
+ if isinstance(model, sklearn.cluster.KMeans):
+ elbow_curve(model, X_train)
+ wandb.termlog("Logged elbow curve.")
+
+ silhouette(model, X_train, cluster_labels, labels=labels, kmeans=True)
+
+ else:
+ silhouette(model, X_train, cluster_labels, kmeans=False)
+
+ wandb.termlog("Logged silhouette plot.")
+
+
+def elbow_curve(
+ clusterer=None,
+ X=None, # noqa: N803
+ cluster_ranges=None,
+ n_jobs=1,
+ show_cluster_time=True,
+):
+ """Measures and plots variance explained as a function of the number of clusters.
+
+ Useful in picking the optimal number of clusters.
+
+ Should only be called with a fitted clusterer (otherwise an error is thrown).
+
+ Please note this function fits the model on the training set when called.
+
+ Args:
+ model: (clusterer) Takes in a fitted clusterer.
+ X: (arr) Training set features.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_elbow_curve(model, X_train)
+ ```
+ """
+ if not hasattr(clusterer, "n_clusters"):
+ wandb.termlog(
+ "n_clusters attribute not in classifier. Cannot plot elbow method."
+ )
+ return
+
+ not_missing = utils.test_missing(clusterer=clusterer)
+ correct_types = utils.test_types
+ is_fitted = utils.test_fitted(clusterer)
+
+ if not_missing and correct_types and is_fitted:
+ elbow_curve_chart = calculate.elbow_curve(
+ clusterer, X, cluster_ranges, n_jobs, show_cluster_time
+ )
+
+ wandb.log({"elbow_curve": elbow_curve_chart})
+
+
+def silhouette(
+ clusterer=None,
+ X=None, # noqa: N803
+ cluster_labels=None,
+ labels=None,
+ metric="euclidean",
+ kmeans=True,
+):
+ """Measures & plots silhouette coefficients.
+
+ Silhouette coefficients near +1 indicate that the sample is far away from
+ the neighboring clusters. A value near 0 indicates that the sample is on or
+ very close to the decision boundary between two neighboring clusters and
+ negative values indicate that the samples might have been assigned to the wrong cluster.
+
+ Should only be called with a fitted clusterer (otherwise an error is thrown).
+
+ Please note this function fits the model on the training set when called.
+
+ Args:
+ model: (clusterer) Takes in a fitted clusterer.
+ X: (arr) Training set features.
+ cluster_labels: (list) Names for cluster labels. Makes plots easier to read
+ by replacing cluster indexes with corresponding names.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_silhouette(model, X_train, ["spam", "not spam"])
+ ```
+ """
+ not_missing = utils.test_missing(clusterer=clusterer)
+ correct_types = utils.test_types(clusterer=clusterer)
+ is_fitted = utils.test_fitted(clusterer)
+
+ if not_missing and correct_types and is_fitted:
+ if isinstance(X, (pd.DataFrame)):
+ X = X.values # noqa: N806
+ silhouette_chart = calculate.silhouette(
+ clusterer, X, cluster_labels, labels, metric, kmeans
+ )
+ wandb.log({"silhouette_plot": silhouette_chart})
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/plot/regressor.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/plot/regressor.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2840a06dabfd27cbe0d980af2988f6cc1ef0604
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/plot/regressor.py
@@ -0,0 +1,121 @@
+"""Define plots for regression models built with scikit-learn."""
+
+from warnings import simplefilter
+
+import numpy as np
+
+import wandb
+from wandb.integration.sklearn import calculate, utils
+
+from . import shared
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def regressor(model, X_train, X_test, y_train, y_test, model_name="Regressor"): # noqa: N803
+ """Generates all sklearn regressor plots supported by W&B.
+
+ The following plots are generated:
+ learning curve, summary metrics, residuals plot, outlier candidates.
+
+ Should only be called with a fitted regressor (otherwise an error is thrown).
+
+ Args:
+ model: (regressor) Takes in a fitted regressor.
+ X_train: (arr) Training set features.
+ y_train: (arr) Training set labels.
+ X_test: (arr) Test set features.
+ y_test: (arr) Test set labels.
+ model_name: (str) Model name. Defaults to 'Regressor'
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_regressor(reg, X_train, X_test, y_train, y_test, "Ridge")
+ ```
+ """
+ wandb.termlog(f"\nPlotting {model_name}.")
+
+ shared.summary_metrics(model, X_train, y_train, X_test, y_test)
+ wandb.termlog("Logged summary metrics.")
+
+ shared.learning_curve(model, X_train, y_train)
+ wandb.termlog("Logged learning curve.")
+
+ outlier_candidates(model, X_train, y_train)
+ wandb.termlog("Logged outlier candidates.")
+
+ residuals(model, X_train, y_train)
+ wandb.termlog("Logged residuals.")
+
+
+def outlier_candidates(regressor=None, X=None, y=None): # noqa: N803
+ """Measures a datapoint's influence on regression model via cook's distance.
+
+ Instances with high influences could potentially be outliers.
+
+ Should only be called with a fitted regressor (otherwise an error is thrown).
+
+ Please note this function fits the model on the training set when called.
+
+ Args:
+ model: (regressor) Takes in a fitted regressor.
+ X: (arr) Training set features.
+ y: (arr) Training set labels.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_outlier_candidates(model, X, y)
+ ```
+ """
+ is_missing = utils.test_missing(regressor=regressor, X=X, y=y)
+ correct_types = utils.test_types(regressor=regressor, X=X, y=y)
+ is_fitted = utils.test_fitted(regressor)
+
+ if is_missing and correct_types and is_fitted:
+ y = np.asarray(y)
+
+ outliers_chart = calculate.outlier_candidates(regressor, X, y)
+ wandb.log({"outlier_candidates": outliers_chart})
+
+
+def residuals(regressor=None, X=None, y=None): # noqa: N803
+ """Measures and plots the regressor's predicted value against the residual.
+
+ The marginal distribution of residuals is also calculated and plotted.
+
+ Should only be called with a fitted regressor (otherwise an error is thrown).
+
+ Please note this function fits variations of the model on the training set when called.
+
+ Args:
+ regressor: (regressor) Takes in a fitted regressor.
+ X: (arr) Training set features.
+ y: (arr) Training set labels.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_residuals(model, X, y)
+ ```
+ """
+ not_missing = utils.test_missing(regressor=regressor, X=X, y=y)
+ correct_types = utils.test_types(regressor=regressor, X=X, y=y)
+ is_fitted = utils.test_fitted(regressor)
+
+ if not_missing and correct_types and is_fitted:
+ y = np.asarray(y)
+
+ residuals_chart = calculate.residuals(regressor, X, y)
+ wandb.log({"residuals": residuals_chart})
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/plot/shared.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/plot/shared.py
new file mode 100644
index 0000000000000000000000000000000000000000..871dbd742c960d681803f240fbccddff02000733
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/plot/shared.py
@@ -0,0 +1,91 @@
+"""Define plots used by multiple sklearn model classes."""
+
+from warnings import simplefilter
+
+import numpy as np
+
+import wandb
+from wandb.integration.sklearn import calculate, utils
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def summary_metrics(model=None, X=None, y=None, X_test=None, y_test=None): # noqa: N803
+ """Logs a chart depicting summary metrics for a model.
+
+ Should only be called with a fitted model (otherwise an error is thrown).
+
+ Args:
+ model: (clf or reg) Takes in a fitted regressor or classifier.
+ X: (arr) Training set features.
+ y: (arr) Training set labels.
+ X_test: (arr) Test set features.
+ y_test: (arr) Test set labels.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_summary_metrics(model, X_train, y_train, X_test, y_test)
+ ```
+ """
+ not_missing = utils.test_missing(
+ model=model, X=X, y=y, X_test=X_test, y_test=y_test
+ )
+ correct_types = utils.test_types(
+ model=model, X=X, y=y, X_test=X_test, y_test=y_test
+ )
+ model_fitted = utils.test_fitted(model)
+
+ if not_missing and correct_types and model_fitted:
+ metrics_chart = calculate.summary_metrics(model, X, y, X_test, y_test)
+ wandb.log({"summary_metrics": metrics_chart})
+
+
+def learning_curve(
+ model=None,
+ X=None, # noqa: N803
+ y=None,
+ cv=None,
+ shuffle=False,
+ random_state=None,
+ train_sizes=None,
+ n_jobs=1,
+ scoring=None,
+):
+ """Logs a plot depicting model performance against dataset size.
+
+ Please note this function fits the model to datasets of varying sizes when called.
+
+ Args:
+ model: (clf or reg) Takes in a fitted regressor or classifier.
+ X: (arr) Dataset features.
+ y: (arr) Dataset labels.
+
+ For details on the other keyword arguments, see the documentation for
+ `sklearn.model_selection.learning_curve`.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_learning_curve(model, X, y)
+ ```
+ """
+ not_missing = utils.test_missing(model=model, X=X, y=y)
+ correct_types = utils.test_types(model=model, X=X, y=y)
+ if not_missing and correct_types:
+ if train_sizes is None:
+ train_sizes = np.linspace(0.1, 1.0, 5)
+ y = np.asarray(y)
+
+ learning_curve_chart = calculate.learning_curve(
+ model, X, y, cv, shuffle, random_state, train_sizes, n_jobs, scoring
+ )
+
+ wandb.log({"learning_curve": learning_curve_chart})
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/utils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b2ef628bbb4165e15d33cd26feb144bd2e40d11
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/sklearn/utils.py
@@ -0,0 +1,184 @@
+"""Shared utilities for the modules in wandb.sklearn."""
+
+from collections.abc import Iterable, Sequence
+
+import numpy as np
+import pandas as pd
+import scipy
+import sklearn
+
+import wandb
+
+chart_limit = 1000
+
+
+def check_against_limit(count, chart, limit=None):
+ if limit is None:
+ limit = chart_limit
+ if count > limit:
+ warn_chart_limit(limit, chart)
+ return True
+ else:
+ return False
+
+
+def warn_chart_limit(limit, chart):
+ warning = f"using only the first {limit} datapoints to create chart {chart}"
+ wandb.termwarn(warning)
+
+
+def encode_labels(df):
+ le = sklearn.preprocessing.LabelEncoder()
+ # apply le on categorical feature columns
+ categorical_cols = df.select_dtypes(
+ exclude=["int", "float", "float64", "float32", "int32", "int64"]
+ ).columns
+ df[categorical_cols] = df[categorical_cols].apply(lambda col: le.fit_transform(col))
+
+
+def test_types(**kwargs):
+ test_passed = True
+ for k, v in kwargs.items():
+ # check for incorrect types
+ if (
+ (k == "X")
+ or (k == "X_test")
+ or (k == "y")
+ or (k == "y_test")
+ or (k == "y_true")
+ or (k == "y_probas")
+ ):
+ # FIXME: do this individually
+ if not isinstance(
+ v,
+ (
+ Sequence,
+ Iterable,
+ np.ndarray,
+ np.generic,
+ pd.DataFrame,
+ pd.Series,
+ list,
+ ),
+ ):
+ wandb.termerror(f"{k} is not an array. Please try again.")
+ test_passed = False
+ # check for classifier types
+ if k == "model":
+ if (not sklearn.base.is_classifier(v)) and (
+ not sklearn.base.is_regressor(v)
+ ):
+ wandb.termerror(
+ f"{k} is not a classifier or regressor. Please try again."
+ )
+ test_passed = False
+ elif k == "clf" or k == "binary_clf":
+ if not (sklearn.base.is_classifier(v)):
+ wandb.termerror(f"{k} is not a classifier. Please try again.")
+ test_passed = False
+ elif k == "regressor":
+ if not sklearn.base.is_regressor(v):
+ wandb.termerror(f"{k} is not a regressor. Please try again.")
+ test_passed = False
+ elif k == "clusterer":
+ if not (getattr(v, "_estimator_type", None) == "clusterer"):
+ wandb.termerror(f"{k} is not a clusterer. Please try again.")
+ test_passed = False
+ return test_passed
+
+
+def test_fitted(model):
+ try:
+ model.predict(np.zeros((7, 3)))
+ except sklearn.exceptions.NotFittedError:
+ wandb.termerror("Please fit the model before passing it in.")
+ return False
+ except AttributeError:
+ # Some clustering models (LDA, PCA, Agglomerative) don't implement ``predict``
+ try:
+ sklearn.utils.validation.check_is_fitted(
+ model,
+ [
+ "coef_",
+ "estimator_",
+ "labels_",
+ "n_clusters_",
+ "children_",
+ "components_",
+ "n_components_",
+ "n_iter_",
+ "n_batch_iter_",
+ "explained_variance_",
+ "singular_values_",
+ "mean_",
+ ],
+ all_or_any=any,
+ )
+ except sklearn.exceptions.NotFittedError:
+ wandb.termerror("Please fit the model before passing it in.")
+ return False
+ else:
+ return True
+ except Exception:
+ # Assume it's fitted, since ``NotFittedError`` wasn't raised
+ return True
+
+
+# Test Asummptions for plotting parameters and datasets
+def test_missing(**kwargs):
+ test_passed = True
+ for k, v in kwargs.items():
+ # Missing/empty params/datapoint arrays
+ if v is None:
+ wandb.termerror(f"{k} is None. Please try again.")
+ test_passed = False
+ if (k == "X") or (k == "X_test"):
+ if isinstance(v, scipy.sparse.csr.csr_matrix):
+ v = v.toarray()
+ elif isinstance(v, (pd.DataFrame, pd.Series)):
+ v = v.to_numpy()
+ elif isinstance(v, list):
+ v = np.asarray(v)
+
+ # Warn the user about missing values
+ missing = 0
+ missing = np.count_nonzero(pd.isnull(v))
+ if missing > 0:
+ wandb.termwarn(f"{k} contains {missing} missing values. ")
+ test_passed = False
+ # Ensure the dataset contains only integers
+ non_nums = 0
+ if v.ndim == 1:
+ non_nums = sum(
+ 1
+ for val in v
+ if (
+ not isinstance(val, (int, float, complex))
+ and not isinstance(val, np.number)
+ )
+ )
+ else:
+ non_nums = sum(
+ 1
+ for sl in v
+ for val in sl
+ if (
+ not isinstance(val, (int, float, complex))
+ and not isinstance(val, np.number)
+ )
+ )
+ if non_nums > 0:
+ wandb.termerror(
+ f"{k} contains values that are not numbers. Please vectorize, label encode or one hot encode {k} "
+ "and call the plotting function again."
+ )
+ test_passed = False
+ return test_passed
+
+
+def round_3(n):
+ return round(n, 3)
+
+
+def round_2(n):
+ return round(n, 2)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/tensorboard/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/tensorboard/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..80f60ef258a10fb2e7ad2f81594084ccd6098f6c
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/tensorboard/__init__.py
@@ -0,0 +1,10 @@
+"""wandb integration tensorboard module."""
+
+from .log import _log, log, reset_state, tf_summary_to_dict
+from .monkeypatch import patch, unpatch
+
+__all__ = [
+ "patch",
+ "unpatch",
+ "log",
+]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/tensorboard/log.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/tensorboard/log.py
new file mode 100644
index 0000000000000000000000000000000000000000..5062a9b0d14109aae1901e751e7864d701d2b7da
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/tensorboard/log.py
@@ -0,0 +1,351 @@
+import io
+import re
+import time
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
+
+import wandb
+import wandb.util
+from wandb.sdk.lib import telemetry
+
+if TYPE_CHECKING:
+ import numpy as np
+
+ from wandb.sdk.internal.tb_watcher import TBHistory
+
+# We have at least the default namestep and a global step to track
+# TODO: reset this structure on wandb.finish
+STEPS: Dict[str, Dict[str, Any]] = {
+ "": {"step": 0},
+ "global": {"step": 0, "last_log": None},
+}
+# TODO(cling): Set these when tensorboard behavior is configured.
+# We support rate limited logging by setting this to number of seconds,
+# can be a floating point.
+RATE_LIMIT_SECONDS: Optional[Union[float, int]] = None
+IGNORE_KINDS = ["graphs"]
+tensor_util = wandb.util.get_module("tensorboard.util.tensor_util")
+
+
+# prefer tensorboard, fallback to protobuf in tensorflow when tboard isn't available
+pb = wandb.util.get_module(
+ "tensorboard.compat.proto.summary_pb2"
+) or wandb.util.get_module("tensorflow.core.framework.summary_pb2")
+
+Summary = pb.Summary if pb else None
+
+
+def make_ndarray(tensor: Any) -> Optional["np.ndarray"]:
+ if tensor_util:
+ res = tensor_util.make_ndarray(tensor)
+ # Tensorboard can log generic objects, and we don't want to save them
+ if res.dtype == "object":
+ return None
+ else:
+ return res # type: ignore
+ else:
+ wandb.termwarn(
+ "Can't convert tensor summary, upgrade tensorboard with `pip"
+ " install tensorboard --upgrade`"
+ )
+ return None
+
+
+def namespaced_tag(tag: str, namespace: str = "") -> str:
+ if not namespace:
+ return tag
+ else:
+ return namespace + "/" + tag
+
+
+def history_image_key(key: str, namespace: str = "") -> str:
+ """Convert invalid filesystem characters to _ for use in History keys.
+
+ Unfortunately this means currently certain image keys will collide silently. We
+ implement this mapping up here in the TensorFlow stuff rather than in the History
+ stuff so that we don't have to store a mapping anywhere from the original keys to
+ the safe ones.
+ """
+ return namespaced_tag(re.sub(r"[/\\]", "_", key), namespace)
+
+
+def tf_summary_to_dict( # noqa: C901
+ tf_summary_str_or_pb: Any, namespace: str = ""
+) -> Optional[Dict[str, Any]]:
+ """Convert a Tensorboard Summary to a dictionary.
+
+ Accepts a tensorflow.summary.Summary, one encoded as a string,
+ or a list of such encoded as strings.
+ """
+ values = {}
+ if hasattr(tf_summary_str_or_pb, "summary"):
+ summary_pb = tf_summary_str_or_pb.summary
+ values[namespaced_tag("global_step", namespace)] = tf_summary_str_or_pb.step
+ values["_timestamp"] = tf_summary_str_or_pb.wall_time
+ elif isinstance(tf_summary_str_or_pb, (str, bytes, bytearray)):
+ summary_pb = Summary()
+ summary_pb.ParseFromString(tf_summary_str_or_pb)
+ elif hasattr(tf_summary_str_or_pb, "__iter__"):
+ summary_pb = [Summary() for _ in range(len(tf_summary_str_or_pb))]
+ for i, summary in enumerate(tf_summary_str_or_pb):
+ summary_pb[i].ParseFromString(summary)
+ if i > 0:
+ summary_pb[0].MergeFrom(summary_pb[i])
+ summary_pb = summary_pb[0]
+ else:
+ summary_pb = tf_summary_str_or_pb
+
+ if not hasattr(summary_pb, "value") or len(summary_pb.value) == 0:
+ # Ignore these, caller is responsible for handling None
+ return None
+
+ def encode_images(_img_strs: List[bytes], _value: Any) -> None:
+ try:
+ from PIL import Image
+ except ImportError:
+ wandb.termwarn(
+ "Install pillow if you are logging images with Tensorboard. "
+ "To install, run `pip install pillow`.",
+ repeat=False,
+ )
+ return None
+
+ if len(_img_strs) == 0:
+ return None
+
+ images: List[Union[wandb.Video, wandb.Image]] = []
+ for _img_str in _img_strs:
+ # Supports gifs from TensorboardX
+ if _img_str.startswith(b"GIF"):
+ images.append(wandb.Video(io.BytesIO(_img_str), format="gif"))
+ else:
+ images.append(wandb.Image(Image.open(io.BytesIO(_img_str))))
+ tag_idx = _value.tag.rsplit("/", 1)
+ if len(tag_idx) > 1 and tag_idx[1].isdigit():
+ tag, idx = tag_idx
+ values.setdefault(history_image_key(tag, namespace), []).extend(images)
+ else:
+ values[history_image_key(_value.tag, namespace)] = images
+
+ return None
+
+ for value in summary_pb.value:
+ kind = value.WhichOneof("value")
+ if kind in IGNORE_KINDS:
+ continue
+ if kind == "simple_value":
+ values[namespaced_tag(value.tag, namespace)] = value.simple_value
+ elif kind == "tensor":
+ plugin_name = value.metadata.plugin_data.plugin_name
+ if plugin_name == "scalars" or plugin_name == "":
+ values[namespaced_tag(value.tag, namespace)] = make_ndarray(
+ value.tensor
+ )
+ elif plugin_name == "images":
+ img_strs = value.tensor.string_val[2:] # First two items are dims.
+ encode_images(img_strs, value)
+ elif plugin_name == "histograms":
+ # https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/histogram/summary_v2.py#L15-L26
+ ndarray = make_ndarray(value.tensor)
+ if ndarray is None:
+ continue
+ shape = ndarray.shape
+ counts = []
+ bins = []
+ if shape[0] > 1:
+ bins.append(ndarray[0][0]) # Add the left most edge
+ for v in ndarray:
+ counts.append(v[2])
+ bins.append(v[1]) # Add the right most edges
+ elif shape[0] == 1:
+ counts = [ndarray[0][2]]
+ bins = ndarray[0][:2]
+ if len(counts) > 0:
+ try:
+ # TODO: we should just re-bin if there are too many buckets
+ values[namespaced_tag(value.tag, namespace)] = wandb.Histogram(
+ np_histogram=(counts, bins) # type: ignore
+ )
+ except ValueError:
+ wandb.termwarn(
+ f'Not logging key "{namespaced_tag(value.tag, namespace)}". '
+ f"Histograms must have fewer than {wandb.Histogram.MAX_LENGTH} bins",
+ repeat=False,
+ )
+ elif plugin_name == "pr_curves":
+ pr_curve_data = make_ndarray(value.tensor)
+ if pr_curve_data is None:
+ continue
+ precision = pr_curve_data[-2, :].tolist()
+ recall = pr_curve_data[-1, :].tolist()
+ # TODO: (kdg) implement spec for showing additional info in tool tips
+ # true_pos = pr_curve_data[1,:]
+ # false_pos = pr_curve_data[2,:]
+ # true_neg = pr_curve_data[1,:]
+ # false_neg = pr_curve_data[1,:]
+ # threshold = [1.0 / n for n in range(len(true_pos), 0, -1)]
+ # min of each in case tensorboard ever changes their pr_curve
+ # to allow for different length outputs
+ data = []
+ for i in range(min(len(precision), len(recall))):
+ # drop additional threshold values if they exist
+ if precision[i] != 0 or recall[i] != 0:
+ data.append((recall[i], precision[i]))
+ # sort data so custom chart looks the same as tb generated pr curve
+ # ascending recall, descending precision for the same recall values
+ data = sorted(data, key=lambda x: (x[0], -x[1]))
+ data_table = wandb.Table(data=data, columns=["recall", "precision"])
+ name = namespaced_tag(value.tag, namespace)
+
+ values[name] = wandb.plot_table(
+ "wandb/line/v0",
+ data_table,
+ {"x": "recall", "y": "precision"},
+ {"title": f"{name} Precision v. Recall"},
+ )
+ elif kind == "image":
+ img_str = value.image.encoded_image_string
+ encode_images([img_str], value)
+ # Coming soon...
+ # elif kind == "audio":
+ # audio = wandb.Audio(
+ # six.BytesIO(value.audio.encoded_audio_string),
+ # sample_rate=value.audio.sample_rate,
+ # content_type=value.audio.content_type,
+ # )
+ elif kind == "histo":
+ tag = namespaced_tag(value.tag, namespace)
+ if len(value.histo.bucket_limit) >= 3:
+ first = (
+ value.histo.bucket_limit[0]
+ + value.histo.bucket_limit[0]
+ - value.histo.bucket_limit[1]
+ )
+ last = (
+ value.histo.bucket_limit[-2]
+ + value.histo.bucket_limit[-2]
+ - value.histo.bucket_limit[-3]
+ )
+ np_histogram = (
+ list(value.histo.bucket),
+ [first] + value.histo.bucket_limit[:-1] + [last],
+ )
+ try:
+ # TODO: we should just re-bin if there are too many buckets
+ values[tag] = wandb.Histogram(np_histogram=np_histogram) # type: ignore
+ except ValueError:
+ wandb.termwarn(
+ f"Not logging key {tag!r}. "
+ f"Histograms must have fewer than {wandb.Histogram.MAX_LENGTH} bins",
+ repeat=False,
+ )
+ else:
+ # TODO: is there a case where we can render this?
+ wandb.termwarn(
+ f"Not logging key {tag!r}. Found a histogram with only 2 bins.",
+ repeat=False,
+ )
+ # TODO(jhr): figure out how to share this between userspace and internal process or dont
+ # elif value.tag == "_hparams_/session_start_info":
+ # if wandb.util.get_module("tensorboard.plugins.hparams"):
+ # from tensorboard.plugins.hparams import plugin_data_pb2
+ #
+ # plugin_data = plugin_data_pb2.HParamsPluginData() #
+ # plugin_data.ParseFromString(value.metadata.plugin_data.content)
+ # for key, param in six.iteritems(plugin_data.session_start_info.hparams):
+ # if not wandb.run.config.get(key):
+ # wandb.run.config[key] = (
+ # param.number_value or param.string_value or param.bool_value
+ # )
+ # else:
+ # wandb.termerror(
+ # "Received hparams tf.summary, but could not import "
+ # "the hparams plugin from tensorboard"
+ # )
+ return values
+
+
+def reset_state() -> None:
+ """Internal method for resetting state, called by wandb.finish()."""
+ global STEPS
+ STEPS = {"": {"step": 0}, "global": {"step": 0, "last_log": None}}
+
+
+def _log(
+ tf_summary_str_or_pb: Any,
+ history: Optional["TBHistory"] = None,
+ step: int = 0,
+ namespace: str = "",
+ **kwargs: Any,
+) -> None:
+ """Logs a tfsummary to wandb.
+
+ Can accept a tf summary string or parsed event. Will use wandb.run.history unless a
+ history object is passed. Can optionally namespace events. Results are committed
+ when step increases for this namespace.
+
+ NOTE: This assumes that events being passed in are in chronological order
+ """
+ global STEPS
+ global RATE_LIMIT_SECONDS
+ # To handle multiple global_steps, we keep track of them here instead
+ # of the global log
+ last_step = STEPS.get(namespace, {"step": 0})
+
+ # Commit our existing data if this namespace increased its step
+ commit = False
+ if last_step["step"] < step:
+ commit = True
+
+ log_dict = tf_summary_to_dict(tf_summary_str_or_pb, namespace)
+ if log_dict is None:
+ # not an event, just return
+ return
+
+ # Pass timestamp to history for loading historic data
+ timestamp = log_dict.get("_timestamp", time.time())
+ # Store our initial timestamp
+ if STEPS["global"]["last_log"] is None:
+ STEPS["global"]["last_log"] = timestamp
+ # Rollup events that share the same step across namespaces
+ if commit and step == STEPS["global"]["step"]:
+ commit = False
+ # Always add the biggest global_step key for non-default namespaces
+ if step > STEPS["global"]["step"]:
+ STEPS["global"]["step"] = step
+ if namespace != "":
+ log_dict["global_step"] = STEPS["global"]["step"]
+
+ # Keep internal step counter
+ STEPS[namespace] = {"step": step}
+
+ if commit:
+ # Only commit our data if we're below the rate limit or don't have one
+ if (
+ RATE_LIMIT_SECONDS is None
+ or timestamp - STEPS["global"]["last_log"] >= RATE_LIMIT_SECONDS
+ ):
+ if history is None:
+ if wandb.run is not None:
+ wandb.run._log({})
+ else:
+ history.add({})
+
+ STEPS["global"]["last_log"] = timestamp
+
+ if history is None:
+ if wandb.run is not None:
+ wandb.run._log(log_dict, commit=False)
+ else:
+ history._row_update(log_dict)
+
+
+def log(tf_summary_str_or_pb: Any, step: int = 0, namespace: str = "") -> None:
+ if wandb.run is None:
+ raise wandb.Error(
+ "You must call `wandb.init()` before calling `wandb.tensorflow.log`"
+ )
+
+ with telemetry.context() as tel:
+ tel.feature.tensorboard_log = True
+
+ _log(tf_summary_str_or_pb, namespace=namespace, step=step)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/tensorboard/monkeypatch.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/tensorboard/monkeypatch.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0db49aaf79bad018642eea9e1d555f65827ba6e
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/tensorboard/monkeypatch.py
@@ -0,0 +1,186 @@
+"""monkeypatch: patch code to add tensorboard hooks."""
+
+import os
+import re
+import socket
+from typing import Any, Optional
+
+import wandb
+import wandb.util
+
+TENSORBOARD_C_MODULE = "tensorflow.python.ops.gen_summary_ops"
+TENSORBOARD_X_MODULE = "tensorboardX.writer"
+TENSORFLOW_PY_MODULE = "tensorflow.python.summary.writer.writer"
+TENSORBOARD_WRITER_MODULE = "tensorboard.summary.writer.event_file_writer"
+TENSORBOARD_PYTORCH_MODULE = "torch.utils.tensorboard.writer"
+
+
+def unpatch() -> None:
+ for module, method in wandb.patched["tensorboard"]:
+ writer = wandb.util.get_module(module, lazy=False)
+ setattr(writer, method, getattr(writer, f"orig_{method}"))
+ wandb.patched["tensorboard"] = []
+
+
+def patch(
+ save: bool = True,
+ tensorboard_x: Optional[bool] = None,
+ pytorch: Optional[bool] = None,
+ root_logdir: str = "",
+) -> None:
+ if len(wandb.patched["tensorboard"]) > 0:
+ raise ValueError(
+ "Tensorboard already patched. Call `wandb.tensorboard.unpatch()` first; "
+ "remove `sync_tensorboard=True` from `wandb.init`; "
+ "or only call `wandb.tensorboard.patch` once."
+ )
+
+ # TODO: Some older versions of tensorflow don't require tensorboard to be present.
+ # we may want to lift this requirement, but it's safer to have it for now
+ wandb.util.get_module(
+ "tensorboard", required="Please install tensorboard package", lazy=False
+ )
+ c_writer = wandb.util.get_module(TENSORBOARD_C_MODULE, lazy=False)
+ py_writer = wandb.util.get_module(TENSORFLOW_PY_MODULE, lazy=False)
+ tb_writer = wandb.util.get_module(TENSORBOARD_WRITER_MODULE, lazy=False)
+ pt_writer = wandb.util.get_module(TENSORBOARD_PYTORCH_MODULE, lazy=False)
+ tbx_writer = wandb.util.get_module(TENSORBOARD_X_MODULE, lazy=False)
+
+ if not pytorch and not tensorboard_x and c_writer:
+ _patch_tensorflow2(
+ writer=c_writer,
+ module=TENSORBOARD_C_MODULE,
+ save=save,
+ root_logdir=root_logdir,
+ )
+ # This is for tensorflow <= 1.15 (tf.compat.v1.summary.FileWriter)
+ if py_writer:
+ _patch_file_writer(
+ writer=py_writer,
+ module=TENSORFLOW_PY_MODULE,
+ save=save,
+ root_logdir=root_logdir,
+ )
+ if tb_writer:
+ _patch_file_writer(
+ writer=tb_writer,
+ module=TENSORBOARD_WRITER_MODULE,
+ save=save,
+ root_logdir=root_logdir,
+ )
+ if pt_writer:
+ _patch_file_writer(
+ writer=pt_writer,
+ module=TENSORBOARD_PYTORCH_MODULE,
+ save=save,
+ root_logdir=root_logdir,
+ )
+ if tbx_writer:
+ _patch_file_writer(
+ writer=tbx_writer,
+ module=TENSORBOARD_X_MODULE,
+ save=save,
+ root_logdir=root_logdir,
+ )
+ if not c_writer and not tb_writer and not tb_writer:
+ wandb.termerror("Unsupported tensorboard configuration")
+
+
+def _patch_tensorflow2(
+ writer: Any,
+ module: Any,
+ save: bool = True,
+ root_logdir: str = "",
+) -> None:
+ # This configures TensorFlow 2 style Tensorboard logging
+ old_csfw_func = writer.create_summary_file_writer
+ logdir_hist = []
+
+ def new_csfw_func(*args: Any, **kwargs: Any) -> Any:
+ logdir = (
+ kwargs["logdir"].numpy().decode("utf8")
+ if hasattr(kwargs["logdir"], "numpy")
+ else kwargs["logdir"]
+ )
+ logdir_hist.append(logdir)
+ root_logdir_arg = root_logdir
+
+ if len(set(logdir_hist)) > 1 and root_logdir == "":
+ wandb.termwarn(
+ "When using several event log directories, "
+ 'please call `wandb.tensorboard.patch(root_logdir="...")` before `wandb.init`'
+ )
+ # if the logdir contains the hostname, the writer was not given a logdir.
+ # In this case, the generated logdir
+ # is generated and ends with the hostname, update the root_logdir to match.
+ hostname = socket.gethostname()
+ search = re.search(rf"-\d+_{hostname}", logdir)
+ if search:
+ root_logdir_arg = logdir[: search.span()[1]]
+ elif root_logdir is not None and not os.path.abspath(logdir).startswith(
+ os.path.abspath(root_logdir)
+ ):
+ wandb.termwarn(
+ "Found log directory outside of given root_logdir, "
+ f"dropping given root_logdir for event file in {logdir}"
+ )
+ root_logdir_arg = ""
+
+ _notify_tensorboard_logdir(logdir, save=save, root_logdir=root_logdir_arg)
+ return old_csfw_func(*args, **kwargs)
+
+ writer.orig_create_summary_file_writer = old_csfw_func
+ writer.create_summary_file_writer = new_csfw_func
+ wandb.patched["tensorboard"].append([module, "create_summary_file_writer"])
+
+
+def _patch_file_writer(
+ writer: Any,
+ module: Any,
+ save: bool = True,
+ root_logdir: str = "",
+) -> None:
+ # This configures non-TensorFlow Tensorboard logging, or tensorflow <= 1.15
+ logdir_hist = []
+
+ class TBXEventFileWriter(writer.EventFileWriter):
+ def __init__(self, logdir: str, *args: Any, **kwargs: Any) -> None:
+ logdir_hist.append(logdir)
+ root_logdir_arg = root_logdir
+ if len(set(logdir_hist)) > 1 and root_logdir == "":
+ wandb.termwarn(
+ "When using several event log directories, "
+ 'please call `wandb.tensorboard.patch(root_logdir="...")` before `wandb.init`'
+ )
+
+ # if the logdir contains the hostname, the writer was not given a logdir.
+ # In this case, the logdir is generated and ends with the hostname,
+ # update the root_logdir to match.
+ hostname = socket.gethostname()
+ search = re.search(rf"-\d+_{hostname}", logdir)
+ if search:
+ root_logdir_arg = logdir[: search.span()[1]]
+
+ elif root_logdir is not None and not os.path.abspath(logdir).startswith(
+ os.path.abspath(root_logdir)
+ ):
+ wandb.termwarn(
+ "Found log directory outside of given root_logdir, "
+ f"dropping given root_logdir for event file in {logdir}"
+ )
+ root_logdir_arg = ""
+
+ _notify_tensorboard_logdir(logdir, save=save, root_logdir=root_logdir_arg)
+
+ super().__init__(logdir, *args, **kwargs)
+
+ writer.orig_EventFileWriter = writer.EventFileWriter
+ writer.EventFileWriter = TBXEventFileWriter
+ wandb.patched["tensorboard"].append([module, "EventFileWriter"])
+
+
+def _notify_tensorboard_logdir(
+ logdir: str, save: bool = True, root_logdir: str = ""
+) -> None:
+ if wandb.run is not None:
+ wandb.run._tensorboard_callback(logdir, save=save, root_logdir=root_logdir)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/tensorflow/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/tensorflow/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5a5838c7d3eb5e5ea9e50b420bf42a605084dc6
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/tensorflow/__init__.py
@@ -0,0 +1,5 @@
+"""api."""
+
+from wandb.integration.tensorboard import log
+
+from .estimator_hook import WandbHook
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/tensorflow/estimator_hook.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/tensorflow/estimator_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..88d58abe3c6ee81759ce01a8e7254e1e324034de
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/tensorflow/estimator_hook.py
@@ -0,0 +1,54 @@
+import tensorflow as tf
+
+import wandb
+from wandb.sdk.lib import telemetry
+
+if hasattr(tf.estimator, "SessionRunHook"):
+ # In tf 1.14 and beyond, SessionRunHook is in the estimator package.
+ SessionRunHook = tf.estimator.SessionRunHook
+ SessionRunArgs = tf.estimator.SessionRunArgs
+else:
+ # In older versions it's in train.
+ SessionRunHook = tf.train.SessionRunHook
+ SessionRunArgs = tf.train.SessionRunArgs
+
+if hasattr(tf.train, "get_global_step"):
+ get_global_step = tf.train.get_global_step
+else:
+ get_global_step = tf.compat.v1.train.get_global_step
+
+if hasattr(tf.summary, "merge_all"):
+ merge_all_summaries = tf.summary.merge_all
+else:
+ merge_all_summaries = tf.compat.v1.summary.merge_all
+
+
+class WandbHook(SessionRunHook):
+ def __init__(self, summary_op=None, steps_per_log=1000, history=None):
+ self._summary_op = summary_op
+ self._steps_per_log = steps_per_log
+ self._history = history
+
+ with telemetry.context() as tel:
+ tel.feature.estimator_hook = True
+
+ def begin(self):
+ if wandb.run is None:
+ raise wandb.Error("You must call `wandb.init()` before calling `WandbHook`")
+ if self._summary_op is None:
+ self._summary_op = merge_all_summaries()
+ self._step = -1
+
+ def before_run(self, run_context):
+ return SessionRunArgs(
+ {"summary": self._summary_op, "global_step": get_global_step()}
+ )
+
+ def after_run(self, run_context, run_values):
+ step = run_values.results["global_step"]
+ if step % self._steps_per_log == 0:
+ wandb.tensorboard._log(
+ run_values.results["summary"],
+ history=self._history,
+ step=step,
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/torch/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/torch/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/torch/wandb_torch.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/torch/wandb_torch.py
new file mode 100644
index 0000000000000000000000000000000000000000..28d5971f8fd640ef6315aa22cb795163bc9d0724
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/torch/wandb_torch.py
@@ -0,0 +1,554 @@
+"""PyTorch-specific functionality."""
+
+import itertools
+from functools import reduce
+from operator import mul
+from typing import TYPE_CHECKING, List
+
+import wandb
+from wandb import util
+from wandb.data_types import Node
+
+torch = None
+
+if TYPE_CHECKING:
+ from torch import Tensor
+ from torch.nn import Module
+
+
+def nested_shape(array_or_tuple, seen=None):
+ """Figure out the shape of tensors possibly embedded in tuples.
+
+ for example:
+ - [0,0] returns (2)
+ - ([0,0], [0,0]) returns (2,2)
+ - (([0,0], [0,0]),[0,0]) returns ((2,2),2).
+ """
+ if seen is None:
+ seen = set()
+ if hasattr(array_or_tuple, "size"):
+ # pytorch tensors use V.size() to get size of tensor
+ return list(array_or_tuple.size())
+ elif hasattr(array_or_tuple, "get_shape"):
+ # tensorflow uses V.get_shape() to get size of tensor
+ return array_or_tuple.get_shape().as_list()
+ elif hasattr(array_or_tuple, "shape"):
+ return array_or_tuple.shape
+
+ seen.add(id(array_or_tuple))
+ try:
+ # treat object as iterable
+ return [
+ nested_shape(item, seen) if id(item) not in seen else 0
+ for item in list(array_or_tuple)
+ ]
+ except TypeError:
+ # object is not actually iterable
+ # LB: Maybe we should throw an error?
+ return []
+
+
+LOG_TRACK_COUNT, LOG_TRACK_THRESHOLD = range(2)
+
+
+def log_track_init(log_freq: int) -> List[int]:
+ """Create tracking structure used by log_track_update."""
+ log_track = [0, 0]
+ log_track[LOG_TRACK_THRESHOLD] = log_freq
+ return log_track
+
+
+def log_track_update(log_track: int) -> bool:
+ """Count (log_track[0]) up to threshold (log_track[1]), reset count (log_track[0]) and return true when reached."""
+ log_track[LOG_TRACK_COUNT] += 1
+ if log_track[LOG_TRACK_COUNT] < log_track[LOG_TRACK_THRESHOLD]:
+ return False
+ log_track[LOG_TRACK_COUNT] = 0
+ return True
+
+
+class TorchHistory:
+ """History methods specific to PyTorch."""
+
+ def __init__(self):
+ global torch
+ torch = wandb.util.get_module("torch", "Could not import torch")
+ self._hook_handles = {}
+ self._num_bins = 64
+ self._is_cuda_histc_supported = None
+ self.hook_torch = TorchGraph.hook_torch
+
+ def add_log_parameters_hook(
+ self,
+ module: "Module",
+ name: str = "",
+ prefix: str = "",
+ log_freq: int = 0,
+ ) -> None:
+ """This instruments hooks into the pytorch module.
+
+ log parameters after a forward pass
+ log_freq - log gradients/parameters every N batches.
+ """
+ # if name is not None:
+ prefix = prefix + name
+
+ if not hasattr(module, "_wandb_hook_names"):
+ module._wandb_hook_names = []
+
+ def parameter_log_hook(module, input_, output, log_track):
+ if not log_track_update(log_track):
+ return
+ for name, parameter in module.named_parameters():
+ # for pytorch 0.3 Variables
+ if isinstance(parameter, torch.autograd.Variable):
+ data = parameter.data
+ else:
+ data = parameter
+ self.log_tensor_stats(data.cpu(), "parameters/" + prefix + name)
+
+ log_track_params = log_track_init(log_freq)
+ try:
+ hook = module.register_forward_hook(
+ lambda mod, inp, outp: parameter_log_hook(
+ mod, inp, outp, log_track_params
+ )
+ )
+ self._hook_handles["parameters/" + prefix] = hook
+ module._wandb_hook_names.append("parameters/" + prefix)
+ except RuntimeError as e:
+ wandb.termwarn(
+ f"Trying to register forward_hook failed ({e}) - skipping parameter tracking."
+ )
+
+ def add_log_gradients_hook(
+ self,
+ module: "Module",
+ name: str = "",
+ prefix: str = "",
+ log_freq: int = 0,
+ ) -> None:
+ """This instruments hooks into the PyTorch module slog gradients after a backward pass.
+
+ Args:
+ module: torch.nn.Module - the module to instrument
+ name: str - the name of the module
+ prefix: str - the prefix to add to the name
+ log_freq: log gradients/parameters every N batches
+ """
+ # if name is not None:
+ prefix = prefix + name
+
+ if not hasattr(module, "_wandb_hook_names"):
+ module._wandb_hook_names = []
+
+ for name, parameter in module.named_parameters():
+ if parameter.requires_grad:
+ log_track_grad = log_track_init(log_freq)
+ module._wandb_hook_names.append("gradients/" + prefix + name)
+ self._hook_variable_gradient_stats(
+ parameter, "gradients/" + prefix + name, log_track_grad
+ )
+
+ def log_tensor_stats(self, tensor, name): # noqa: C901
+ """Add distribution statistics on a tensor's elements to the current History entry."""
+ # TODO Handle the case of duplicate names.
+ if isinstance(tensor, (tuple, list)):
+ while isinstance(tensor, (tuple, list)) and isinstance(
+ tensor[0], (tuple, list)
+ ):
+ tensor = [item for sublist in tensor for item in sublist]
+ tensor = torch.cat([t.detach().clone().reshape(-1) for t in tensor])
+
+ tensor = tensor.detach().clone()
+ # checking for inheritance from _TensorBase didn't work for some reason
+ if not hasattr(tensor, "shape"):
+ cls = type(tensor)
+ raise TypeError(f"Expected Tensor, not {cls.__module__}.{cls.__name__}")
+
+ # Sparse tensors have a bunch of implicit zeros. In order to histo them correctly,
+ # we have to count them up and add them to the histo ourselves.
+ sparse_zeros = None
+ if tensor.is_sparse:
+ # Have to call this on a sparse tensor before most other ops.
+ tensor = tensor.cpu().coalesce()
+
+ backing_values = tensor._values()
+ sparse_zeros = tensor.numel() - backing_values.numel()
+ tensor = backing_values
+
+ flat = tensor.reshape(-1)
+
+ if flat.is_cuda:
+ if self._is_cuda_histc_supported is None:
+ try:
+ flat.histc(bins=self._num_bins)
+ except RuntimeError:
+ self._is_cuda_histc_supported = False
+ else:
+ self._is_cuda_histc_supported = True
+
+ # As of torch 1.0.1.post2+nightly, float16 cuda summary ops are not supported (convert to float32)
+ if not self._is_cuda_histc_supported:
+ flat = flat.cpu()
+ elif not isinstance(
+ flat, (torch.cuda.FloatTensor, torch.cuda.DoubleTensor)
+ ):
+ flat = flat.type(torch.cuda.FloatTensor)
+
+ # Since we use histc, we need to make sure that torch supports the operation on CPU,
+ # otherwise we'll get a runtime error. Hence, we need to upcast to float32.
+ if not flat.is_cuda and not isinstance(
+ flat, (torch.FloatTensor, torch.DoubleTensor)
+ ):
+ flat = flat.type(torch.FloatTensor)
+
+ # Skip logging if all values are nan or inf or the tensor is empty.
+ if self._no_finite_values(flat):
+ return
+
+ # Remove nans and infs if present. There's no good way to represent that in histograms.
+ flat = self._remove_infs_nans(flat)
+
+ tmin = flat.min().item()
+ tmax = flat.max().item()
+ if sparse_zeros:
+ # If we've got zeros to add in, make sure zero is in the hist range.
+ tmin = 0 if tmin > 0 else tmin
+ tmax = 0 if tmax < 0 else tmax
+ # Anecdotally, this can somehow happen sometimes. Maybe a precision error
+ # in min()/max() above. Swap here to prevent a runtime error.
+ # If all values are equal, just return a single bin.
+ if tmin > tmax:
+ tmin, tmax = tmax, tmin
+ if tmin == tmax:
+ tensor = torch.Tensor([flat.numel()])
+ tensor = tensor.cpu().clone().detach()
+ bins = torch.Tensor([tmin, tmax])
+ else:
+ tensor = flat.histc(bins=self._num_bins, min=tmin, max=tmax)
+ tensor = tensor.cpu().detach().clone()
+ bins = torch.linspace(tmin, tmax, steps=self._num_bins + 1)
+
+ # Add back zeroes from a sparse tensor.
+ if sparse_zeros:
+ bins_np = bins.numpy()
+ tensor_np = tensor.numpy()
+ bin_idx = 0
+ num_buckets = len(bins_np) - 1
+ for i in range(num_buckets):
+ start = bins_np[i]
+ end = bins_np[i + 1]
+ # There are 3 cases to consider here, all of which mean we've found the right bucket
+ # 1. The bucket range contains zero.
+ # 2. The bucket range lower bound *is* zero.
+ # 3. This is the last bucket and the bucket range upper bound is zero.
+ if (start <= 0 and end > 0) or (i == num_buckets - 1 and end == 0):
+ bin_idx = i
+ break
+
+ tensor_np[bin_idx] += sparse_zeros
+ tensor = torch.Tensor(tensor_np)
+ bins = torch.Tensor(bins_np)
+
+ wandb.run._log(
+ {name: wandb.Histogram(np_histogram=(tensor.tolist(), bins.tolist()))},
+ commit=False,
+ )
+
+ def _hook_variable_gradient_stats(self, var, name, log_track):
+ """Logs a Variable's gradient's distribution statistics next time backward() is called on it."""
+ if not isinstance(var, torch.autograd.Variable):
+ cls = type(var)
+ raise TypeError(
+ f"Expected torch.Variable, not {cls.__module__}.{cls.__name__}"
+ )
+
+ handle = self._hook_handles.get(name)
+ if handle is not None and self._torch_hook_handle_is_valid(handle):
+ raise ValueError(f'A hook has already been set under name "{name}"')
+
+ def _callback(grad, log_track):
+ if not log_track_update(log_track):
+ return
+ self.log_tensor_stats(grad.data, name)
+
+ handle = var.register_hook(lambda grad: _callback(grad, log_track))
+ self._hook_handles[name] = handle
+ return handle
+
+ def unhook_all(self):
+ for handle in self._hook_handles.values():
+ handle.remove()
+ self._hook_handles = {}
+
+ def unhook(self, name):
+ handle = self._hook_handles.pop(name)
+ handle.remove()
+
+ def _torch_hook_handle_is_valid(self, handle):
+ d = handle.hooks_dict_ref()
+ if d is None:
+ return False
+ else:
+ return handle.id in d
+
+ def _no_finite_values(self, tensor: "Tensor") -> bool:
+ return tensor.shape == torch.Size([0]) or (~torch.isfinite(tensor)).all().item()
+
+ def _remove_infs_nans(self, tensor: "Tensor") -> "Tensor":
+ if not torch.isfinite(tensor).all():
+ tensor = tensor[torch.isfinite(tensor)]
+
+ return tensor
+
+
+class TorchGraph(wandb.data_types.Graph):
+ def __init__(self):
+ super().__init__("torch")
+ self._graph_hooks = set()
+
+ @classmethod
+ def hook_torch(cls, model, criterion=None, graph_idx=0):
+ wandb.termlog("logging graph, to disable use `wandb.watch(log_graph=False)`")
+ graph = TorchGraph()
+ graph.hook_torch_modules(model, criterion, graph_idx=graph_idx)
+ return graph
+
+ def create_forward_hook(self, name, graph_idx):
+ graph = self
+
+ def after_forward_hook(module, input, output):
+ if id(module) not in self._graph_hooks:
+ # hook already processed -> noop
+ return
+ if not isinstance(output, tuple):
+ output = (output,)
+ parameters = [
+ (pname, list(param.size()))
+ for pname, param in module.named_parameters()
+ ]
+
+ node = Node(
+ id=id(module),
+ name=name,
+ class_name=str(module),
+ output_shape=nested_shape(output),
+ parameters=parameters,
+ num_parameters=[reduce(mul, size, 1) for (pname, size) in parameters],
+ )
+ graph.nodes_by_id[id(module)] = node
+ for param in module.parameters():
+ graph.nodes_by_id[id(param)] = node
+ graph.add_node(node)
+ if not graph.criterion_passed:
+ if hasattr(output[0], "grad_fn"):
+ graph.criterion = output[0].grad_fn
+ elif (
+ isinstance(output[0], list)
+ and output[0]
+ and hasattr(output[0][0], "grad_fn")
+ ):
+ graph.criterion = output[0][0].grad_fn
+
+ # hook has been processed
+ self._graph_hooks -= {id(module)}
+
+ if not self._graph_hooks:
+ # we went through the entire graph
+ wandb.run.summary[f"graph_{graph_idx}"] = self
+
+ return after_forward_hook
+
+ def hook_torch_modules(
+ self, module, criterion=None, prefix=None, graph_idx=0, parent=None
+ ):
+ torch = util.get_module("torch", "Could not import torch")
+ layers = 0
+ graph = self
+ if hasattr(module, "_wandb_watch_called") and module._wandb_watch_called:
+ raise ValueError(
+ "You can only call `wandb.watch` once per model. Pass a new instance of the model if you need to call wandb.watch again in your code."
+ )
+ module._wandb_watch_called = True
+ if criterion:
+ graph.criterion = criterion
+ graph.criterion_passed = True
+
+ for name, sub_module in module.named_children():
+ name = name or str(layers)
+ if prefix:
+ name = prefix + "." + name
+ layers += 1
+ if not isinstance(sub_module, torch.nn.Module):
+ # TODO: Why does this happen?
+ break
+
+ # Trying to support torch >0.3 making this code complicated
+ # We want a list of types that we should recurse into
+ # Torch 0.3 uses containers
+ # 0.4 has ModuleList
+ # 0.4.1 has ModuleDict
+ module_types = [
+ getattr(torch.nn, module_classname)
+ for module_classname in (
+ "Container",
+ "Sequential",
+ "ModuleList",
+ "ModuleDict",
+ )
+ if hasattr(torch.nn, module_classname)
+ ]
+ if parent is None:
+ parent = module
+
+ if isinstance(sub_module, tuple(module_types)):
+ self.hook_torch_modules(sub_module, prefix=name, parent=parent)
+ else:
+ self._graph_hooks |= {id(sub_module)}
+ try:
+ graph_hook = sub_module.register_forward_hook(
+ self.create_forward_hook(name, graph_idx)
+ )
+ wandb.run._torch._hook_handles[
+ "topology/" + str(id(graph_hook))
+ ] = graph_hook
+ if not hasattr(parent, "_wandb_hook_names"):
+ # should never happen but let's be extra safe
+ parent._wandb_hook_names = []
+ parent._wandb_hook_names.append("topology/" + str(id(graph_hook)))
+ except RuntimeError as e:
+ wandb.termwarn(
+ f"Trying to register forward_hook failed ({e}) - skipping graph tracking.",
+ repeat=False,
+ )
+
+ @classmethod
+ def from_torch_layers(cls, module_graph, variable):
+ """Recover something like neural net layers from PyTorch Module's and the compute graph from a Variable.
+
+ Example output for a multi-layer RNN. We confusingly assign shared embedding values
+ to the encoder, but ordered next to the decoder.
+
+ rnns.0.linear.module.weight_raw rnns.0
+ rnns.0.linear.module.bias rnns.0
+ rnns.1.linear.module.weight_raw rnns.1
+ rnns.1.linear.module.bias rnns.1
+ rnns.2.linear.module.weight_raw rnns.2
+ rnns.2.linear.module.bias rnns.2
+ rnns.3.linear.module.weight_raw rnns.3
+ rnns.3.linear.module.bias rnns.3
+ decoder.weight encoder
+ decoder.bias decoder
+ """
+ # TODO: We're currently not using this, but I left it here in case we want to resurrect! - CVP
+ torch = util.get_module("torch", "Could not import torch")
+
+ module_nodes_by_hash = {id(n): n for n in module_graph.nodes}
+ module_parameter_nodes = [
+ n for n in module_graph.nodes if isinstance(n.obj, torch.nn.Parameter)
+ ]
+
+ names_by_pid = {id(n.obj): n.name for n in module_parameter_nodes}
+
+ reachable_param_nodes = module_graph[0].reachable_descendents()
+ reachable_params = {}
+ module_reachable_params = {}
+ names = {}
+ for pid, reachable_nodes in reachable_param_nodes.items():
+ node = module_nodes_by_hash[pid]
+ if not isinstance(node.obj, torch.nn.Module):
+ continue
+ module = node.obj
+ reachable_params = {} # by object id
+ module_reachable_params[id(module)] = reachable_params
+ names[node.name] = set()
+ for reachable_hash in reachable_nodes:
+ reachable = module_nodes_by_hash[reachable_hash]
+ if isinstance(reachable.obj, torch.nn.Parameter):
+ param = reachable.obj
+ reachable_params[id(param)] = param
+ names[node.name].add(names_by_pid[id(param)])
+
+ # we look for correspondences between sets of parameters used in subtrees of the
+ # computation graph and sets of parameters contained in subtrees of the module
+ # graph
+ node_depths = {id(n): d for n, d in module_graph[0].descendent_bfs()}
+ parameter_module_names = {}
+ parameter_modules = {}
+ for param_node in (
+ n for n in module_graph.nodes if isinstance(n.obj, torch.nn.Parameter)
+ ):
+ pid = id(param_node.obj)
+ best_node = None
+ best_depth = None
+ best_reachable_params = None
+ for node in module_graph.nodes:
+ if not isinstance(node.obj, torch.nn.Module):
+ continue
+ module = node.obj
+ reachable_params = module_reachable_params[id(module)]
+ if pid in reachable_params:
+ depth = node_depths[id(node)]
+ if best_node is None or (len(reachable_params), depth) <= (
+ len(best_reachable_params),
+ best_depth,
+ ):
+ best_node = node
+ best_depth = depth
+ best_reachable_params = reachable_params
+
+ parameter_modules[pid] = best_node
+ parameter_module_names[param_node.name] = best_node.name
+
+ # contains all parameters but only a minimal set of modules necessary
+ # to contain them (and which ideally correspond to conceptual layers)
+ reduced_module_graph = cls()
+ rmg_ids = itertools.count()
+ rmg_root = Node(id=next(rmg_ids), node=module_graph[0])
+ reduced_module_graph.add_node(rmg_root)
+ reduced_module_graph.root = rmg_root
+ rmg_nodes_by_pid = {}
+
+ module_nodes_by_pid = {id(n.obj): n for n in module_graph.nodes}
+
+ compute_graph, compute_node_vars = cls.from_torch_compute_graph(variable)
+ for node, _ in reversed(list(compute_graph[0].ancestor_bfs())):
+ param = compute_node_vars.get(node.id)
+ pid = id(param)
+ if not isinstance(param, torch.nn.Parameter):
+ continue
+ if pid not in module_nodes_by_pid:
+ # not all Parameters that occur in the compute graph come from the Module graph
+ continue
+
+ # add the nodes in the order we want to display them on the frontend
+ mid = id(parameter_modules[pid].obj)
+ if mid in rmg_nodes_by_pid:
+ rmg_module = rmg_nodes_by_pid[mid]
+ else:
+ rmg_module = rmg_nodes_by_pid[mid] = Node(
+ id=next(rmg_ids), node=module_nodes_by_pid[mid]
+ )
+ reduced_module_graph.add_node(rmg_module)
+ reduced_module_graph.add_edge(rmg_root, rmg_module)
+
+ rmg_param = Node(id=next(rmg_ids), node=module_nodes_by_pid[pid])
+ rmg_nodes_by_pid[pid] = rmg_param
+ reduced_module_graph.add_node(rmg_param)
+
+ reduced_module_graph.add_edge(rmg_module, rmg_param)
+ return reduced_module_graph
+
+ @classmethod
+ def node_from_module(cls, nid, module):
+ numpy = util.get_module("numpy", "Could not import numpy")
+
+ node = wandb.Node()
+ node.id = nid
+ node.child_parameters = 0
+ for parameter in module.parameters():
+ node.child_parameters += numpy.prod(parameter.size())
+ node.class_name = type(module).__name__
+
+ return node
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/ultralytics/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/ultralytics/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c25ae320c8c946a25150b870770710f58a8bf713
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/ultralytics/__init__.py
@@ -0,0 +1,11 @@
+"""Tools for integrating with [`ultralytics`](https://docs.ultralytics.com/).
+
+Ultralytics is a computer vision framework for training and deploying YOLOv8 models.
+"""
+
+from wandb.integration.ultralytics.callback import (
+ WandBUltralyticsCallback,
+ add_wandb_callback,
+)
+
+__all__ = ("WandBUltralyticsCallback", "add_wandb_callback")
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/ultralytics/bbox_utils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/ultralytics/bbox_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f87bd167bfb45cb4f9a996df301985fa46a0dc9
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/ultralytics/bbox_utils.py
@@ -0,0 +1,215 @@
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import torch
+from tqdm.auto import tqdm
+from ultralytics.engine.results import Results
+from ultralytics.models.yolo.detect import DetectionPredictor
+from ultralytics.utils import ops
+
+import wandb
+
+
+def scale_bounding_box_to_original_image_shape(
+ box: torch.Tensor,
+ resized_image_shape: Tuple,
+ original_image_shape: Tuple,
+ ratio_pad: bool,
+) -> List[int]:
+ """YOLOv8 resizes images during training and the label values are normalized based on this resized shape.
+
+ This function rescales the bounding box labels to the original
+ image shape.
+
+ Reference: https://github.com/ultralytics/ultralytics/blob/main/ultralytics/yolo/utils/callbacks/comet.py#L105
+ """
+ resized_image_height, resized_image_width = resized_image_shape
+ # Convert normalized xywh format predictions to xyxy in resized scale format
+ box = ops.xywhn2xyxy(box, h=resized_image_height, w=resized_image_width)
+ # Scale box predictions from resized image scale back to original image scale
+ box = ops.scale_boxes(resized_image_shape, box, original_image_shape, ratio_pad)
+ # # Convert bounding box format from xyxy to xywh for Comet logging
+ box = ops.xyxy2xywh(box)
+ return box.tolist()
+
+
+def get_ground_truth_bbox_annotations(
+ img_idx: int, image_path: str, batch: Dict, class_name_map: Dict = None
+) -> List[Dict[str, Any]]:
+ """Get ground truth bounding box annotation data in the form required for `wandb.Image` overlay system."""
+ indices = batch["batch_idx"] == img_idx
+ bboxes = batch["bboxes"][indices]
+ if len(batch["cls"][indices]):
+ cls_labels = batch["cls"][indices].squeeze(1).tolist()
+ else:
+ cls_labels = []
+
+ class_name_map_reverse = {v: k for k, v in class_name_map.items()}
+
+ if len(bboxes) == 0:
+ wandb.termwarn(
+ f"Image: {image_path} has no bounding boxes labels", repeat=False
+ )
+ return None
+
+ if len(batch["cls"][indices]):
+ cls_labels = batch["cls"][indices].squeeze(1).tolist()
+ else:
+ cls_labels = []
+
+ if class_name_map:
+ cls_labels = [str(class_name_map[label]) for label in cls_labels]
+
+ original_image_shape = batch["ori_shape"][img_idx]
+ resized_image_shape = batch["resized_shape"][img_idx]
+ ratio_pad = batch["ratio_pad"][img_idx]
+
+ data = []
+ for box, label in zip(bboxes, cls_labels):
+ box = scale_bounding_box_to_original_image_shape(
+ box, resized_image_shape, original_image_shape, ratio_pad
+ )
+ data.append(
+ {
+ "position": {
+ "middle": [int(box[0]), int(box[1])],
+ "width": int(box[2]),
+ "height": int(box[3]),
+ },
+ "domain": "pixel",
+ "class_id": class_name_map_reverse[label],
+ "box_caption": label,
+ }
+ )
+
+ return data
+
+
+def get_mean_confidence_map(
+ classes: List, confidence: List, class_id_to_label: Dict
+) -> Dict[str, float]:
+ """Get Mean-confidence map from the predictions to be logged into a `wandb.Table`."""
+ confidence_map = {v: [] for _, v in class_id_to_label.items()}
+ for class_idx, confidence_value in zip(classes, confidence):
+ confidence_map[class_id_to_label[class_idx]].append(confidence_value)
+ updated_confidence_map = {}
+ for label, confidence_list in confidence_map.items():
+ if len(confidence_list) > 0:
+ updated_confidence_map[label] = sum(confidence_list) / len(confidence_list)
+ else:
+ updated_confidence_map[label] = 0
+ return updated_confidence_map
+
+
+def get_boxes(result: Results) -> Tuple[Dict, Dict]:
+ """Convert an ultralytics prediction result into metadata for the `wandb.Image` overlay system."""
+ boxes = result.boxes.xywh.long().numpy()
+ classes = result.boxes.cls.long().numpy()
+ confidence = result.boxes.conf.numpy()
+ class_id_to_label = {int(k): str(v) for k, v in result.names.items()}
+ mean_confidence_map = get_mean_confidence_map(
+ classes, confidence, class_id_to_label
+ )
+ box_data = []
+ for idx in range(len(boxes)):
+ box_data.append(
+ {
+ "position": {
+ "middle": [int(boxes[idx][0]), int(boxes[idx][1])],
+ "width": int(boxes[idx][2]),
+ "height": int(boxes[idx][3]),
+ },
+ "domain": "pixel",
+ "class_id": int(classes[idx]),
+ "box_caption": class_id_to_label[int(classes[idx])],
+ "scores": {"confidence": float(confidence[idx])},
+ }
+ )
+ boxes = {
+ "predictions": {
+ "box_data": box_data,
+ "class_labels": class_id_to_label,
+ },
+ }
+ return boxes, mean_confidence_map
+
+
+def plot_bbox_predictions(
+ result: Results, model_name: str, table: Optional[wandb.Table] = None
+) -> Union[wandb.Table, Tuple[wandb.Image, Dict, Dict]]:
+ """Plot the images with the W&B overlay system.
+
+ The `wandb.Image` is either added to a `wandb.Table` or returned.
+ """
+ result = result.to("cpu")
+ boxes, mean_confidence_map = get_boxes(result)
+ image = wandb.Image(result.orig_img[:, :, ::-1], boxes=boxes)
+ if table is not None:
+ table.add_data(
+ model_name,
+ image,
+ len(boxes["predictions"]["box_data"]),
+ mean_confidence_map,
+ result.speed,
+ )
+ return table
+ return image, boxes["predictions"], mean_confidence_map
+
+
+def plot_detection_validation_results(
+ dataloader: Any,
+ class_label_map: Dict,
+ model_name: str,
+ predictor: DetectionPredictor,
+ table: wandb.Table,
+ max_validation_batches: int,
+ epoch: Optional[int] = None,
+) -> wandb.Table:
+ """Plot validation results in a table."""
+ data_idx = 0
+ num_dataloader_batches = len(dataloader.dataset) // dataloader.batch_size
+ max_validation_batches = min(max_validation_batches, num_dataloader_batches)
+ for batch_idx, batch in enumerate(dataloader):
+ prediction_results = predictor(batch["im_file"])
+ progress_bar_result_iterable = tqdm(
+ enumerate(prediction_results),
+ total=len(prediction_results),
+ desc=f"Generating Visualizations for batch-{batch_idx + 1}/{max_validation_batches}",
+ )
+ for img_idx, prediction_result in progress_bar_result_iterable:
+ prediction_result = prediction_result.to("cpu")
+ _, prediction_box_data, mean_confidence_map = plot_bbox_predictions(
+ prediction_result, model_name
+ )
+ try:
+ ground_truth_data = get_ground_truth_bbox_annotations(
+ img_idx, batch["im_file"][img_idx], batch, class_label_map
+ )
+ wandb_image = wandb.Image(
+ batch["im_file"][img_idx],
+ boxes={
+ "ground-truth": {
+ "box_data": ground_truth_data,
+ "class_labels": class_label_map,
+ },
+ "predictions": {
+ "box_data": prediction_box_data["box_data"],
+ "class_labels": class_label_map,
+ },
+ },
+ )
+ table_rows = [
+ data_idx,
+ batch_idx,
+ wandb_image,
+ mean_confidence_map,
+ prediction_result.speed,
+ ]
+ table_rows = [epoch] + table_rows if epoch is not None else table_rows
+ table_rows = [model_name] + table_rows
+ table.add_data(*table_rows)
+ data_idx += 1
+ except TypeError:
+ pass
+ if batch_idx + 1 == max_validation_batches:
+ break
+ return table
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/ultralytics/callback.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/ultralytics/callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..c47605a9579dafece3ef364bd3916f4cfd3c96f9
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/ultralytics/callback.py
@@ -0,0 +1,528 @@
+import copy
+from datetime import datetime
+from typing import Callable, Dict, Optional, Union
+
+from packaging import version
+
+try:
+ import dill as pickle
+except ImportError:
+ import pickle
+
+import wandb
+from wandb.sdk.lib import telemetry
+
+try:
+ import torch
+ import ultralytics
+ from tqdm.auto import tqdm
+
+ if version.parse(ultralytics.__version__) > version.parse("8.0.238"):
+ wandb.termwarn(
+ """This integration is tested and supported for ultralytics v8.0.238 and below.
+ Please report any issues to https://github.com/wandb/wandb/issues with the tag `yolov8`.""",
+ repeat=False,
+ )
+
+ from ultralytics.models import YOLO
+ from ultralytics.models.sam.predict import Predictor as SAMPredictor
+ from ultralytics.models.yolo.classify import (
+ ClassificationPredictor,
+ ClassificationTrainer,
+ ClassificationValidator,
+ )
+ from ultralytics.models.yolo.detect import (
+ DetectionPredictor,
+ DetectionTrainer,
+ DetectionValidator,
+ )
+ from ultralytics.models.yolo.pose import PosePredictor, PoseTrainer, PoseValidator
+ from ultralytics.models.yolo.segment import (
+ SegmentationPredictor,
+ SegmentationTrainer,
+ SegmentationValidator,
+ )
+ from ultralytics.utils.torch_utils import de_parallel
+
+ try:
+ from ultralytics.yolo.utils import RANK, __version__
+ except ModuleNotFoundError:
+ from ultralytics.utils import RANK, __version__
+
+ from wandb.integration.ultralytics.bbox_utils import (
+ plot_bbox_predictions,
+ plot_detection_validation_results,
+ )
+ from wandb.integration.ultralytics.classification_utils import (
+ plot_classification_predictions,
+ plot_classification_validation_results,
+ )
+ from wandb.integration.ultralytics.mask_utils import (
+ plot_mask_predictions,
+ plot_sam_predictions,
+ plot_segmentation_validation_results,
+ )
+ from wandb.integration.ultralytics.pose_utils import (
+ plot_pose_predictions,
+ plot_pose_validation_results,
+ )
+except Exception as e:
+ wandb.Error(e)
+
+
+TRAINER_TYPE = Union[
+ ClassificationTrainer, DetectionTrainer, SegmentationTrainer, PoseTrainer
+]
+VALIDATOR_TYPE = Union[
+ ClassificationValidator, DetectionValidator, SegmentationValidator, PoseValidator
+]
+PREDICTOR_TYPE = Union[
+ ClassificationPredictor,
+ DetectionPredictor,
+ SegmentationPredictor,
+ PosePredictor,
+ SAMPredictor,
+]
+
+
+class WandBUltralyticsCallback:
+ """Stateful callback for logging to W&B.
+
+ In particular, it will log model checkpoints, predictions, and
+ ground-truth annotations with interactive overlays for bounding boxes
+ to Weights & Biases Tables during training, validation and prediction
+ for a `ultratytics` workflow.
+
+ Example:
+ ```python
+ from ultralytics.yolo.engine.model import YOLO
+ from wandb.yolov8 import add_wandb_callback
+
+ # initialize YOLO model
+ model = YOLO("yolov8n.pt")
+
+ # add wandb callback
+ add_wandb_callback(
+ model, max_validation_batches=2, enable_model_checkpointing=True
+ )
+
+ # train
+ model.train(data="coco128.yaml", epochs=5, imgsz=640)
+
+ # validate
+ model.val()
+
+ # perform inference
+ model(["img1.jpeg", "img2.jpeg"])
+ ```
+
+ Args:
+ model: (ultralytics.yolo.engine.model.YOLO) YOLO Model of type
+ `ultralytics.yolo.engine.model.YOLO`.
+ epoch_logging_interval: (int) interval to log the prediction visualizations
+ during training.
+ max_validation_batches: (int) maximum number of validation batches to log to
+ a table per epoch.
+ enable_model_checkpointing: (bool) enable logging model checkpoints as
+ artifacts at the end of eveny epoch if set to `True`.
+ visualize_skeleton: (bool) visualize pose skeleton by drawing lines connecting
+ keypoints for human pose.
+ """
+
+ def __init__(
+ self,
+ model: YOLO,
+ epoch_logging_interval: int = 1,
+ max_validation_batches: int = 1,
+ enable_model_checkpointing: bool = False,
+ visualize_skeleton: bool = False,
+ ) -> None:
+ self.epoch_logging_interval = epoch_logging_interval
+ self.max_validation_batches = max_validation_batches
+ self.enable_model_checkpointing = enable_model_checkpointing
+ self.visualize_skeleton = visualize_skeleton
+ self.task = model.task
+ self.task_map = model.task_map
+ self.model_name = (
+ model.overrides["model"].split(".")[0]
+ if "model" in model.overrides
+ else None
+ )
+ self._make_tables()
+ self._make_predictor(model)
+ self.supported_tasks = ["detect", "segment", "pose", "classify"]
+ self.prompts = None
+ self.run_id = None
+ self.train_epoch = None
+
+ def _make_tables(self):
+ if self.task in ["detect", "segment"]:
+ validation_columns = [
+ "Data-Index",
+ "Batch-Index",
+ "Image",
+ "Mean-Confidence",
+ "Speed",
+ ]
+ train_columns = ["Epoch"] + validation_columns
+ self.train_validation_table = wandb.Table(
+ columns=["Model-Name"] + train_columns
+ )
+ self.validation_table = wandb.Table(
+ columns=["Model-Name"] + validation_columns
+ )
+ self.prediction_table = wandb.Table(
+ columns=[
+ "Model-Name",
+ "Image",
+ "Num-Objects",
+ "Mean-Confidence",
+ "Speed",
+ ]
+ )
+ elif self.task == "classify":
+ classification_columns = [
+ "Image",
+ "Predicted-Category",
+ "Prediction-Confidence",
+ "Top-5-Prediction-Categories",
+ "Top-5-Prediction-Confindence",
+ "Probabilities",
+ "Speed",
+ ]
+ validation_columns = ["Data-Index", "Batch-Index"] + classification_columns
+ validation_columns.insert(3, "Ground-Truth-Category")
+ self.train_validation_table = wandb.Table(
+ columns=["Model-Name", "Epoch"] + validation_columns
+ )
+ self.validation_table = wandb.Table(
+ columns=["Model-Name"] + validation_columns
+ )
+ self.prediction_table = wandb.Table(
+ columns=["Model-Name"] + classification_columns
+ )
+ elif self.task == "pose":
+ validation_columns = [
+ "Data-Index",
+ "Batch-Index",
+ "Image-Ground-Truth",
+ "Image-Prediction",
+ "Num-Instances",
+ "Mean-Confidence",
+ "Speed",
+ ]
+ train_columns = ["Epoch"] + validation_columns
+ self.train_validation_table = wandb.Table(
+ columns=["Model-Name"] + train_columns
+ )
+ self.validation_table = wandb.Table(
+ columns=["Model-Name"] + validation_columns
+ )
+ self.prediction_table = wandb.Table(
+ columns=[
+ "Model-Name",
+ "Image-Prediction",
+ "Num-Instances",
+ "Mean-Confidence",
+ "Speed",
+ ]
+ )
+
+ def _make_predictor(self, model: YOLO):
+ overrides = copy.deepcopy(model.overrides)
+ overrides["conf"] = 0.1
+ self.predictor = self.task_map[self.task]["predictor"](overrides=overrides)
+ self.predictor.callbacks = {}
+ self.predictor.args.save = False
+ self.predictor.args.save_txt = False
+ self.predictor.args.save_crop = False
+ self.predictor.args.verbose = None
+
+ def _save_model(self, trainer: TRAINER_TYPE):
+ model_checkpoint_artifact = wandb.Artifact(f"run_{wandb.run.id}_model", "model")
+ checkpoint_dict = {
+ "epoch": trainer.epoch,
+ "best_fitness": trainer.best_fitness,
+ "model": copy.deepcopy(de_parallel(self.model)).half(),
+ "ema": copy.deepcopy(trainer.ema.ema).half(),
+ "updates": trainer.ema.updates,
+ "optimizer": trainer.optimizer.state_dict(),
+ "train_args": vars(trainer.args),
+ "date": datetime.now().isoformat(),
+ "version": __version__,
+ }
+ checkpoint_path = trainer.wdir / f"epoch{trainer.epoch}.pt"
+ torch.save(checkpoint_dict, checkpoint_path, pickle_module=pickle)
+ model_checkpoint_artifact.add_file(checkpoint_path)
+ wandb.log_artifact(
+ model_checkpoint_artifact, aliases=[f"epoch_{trainer.epoch}"]
+ )
+
+ def on_train_start(self, trainer: TRAINER_TYPE):
+ with telemetry.context(run=wandb.run) as tel:
+ tel.feature.ultralytics_yolov8 = True
+ wandb.config.train = vars(trainer.args)
+ self.run_id = wandb.run.id
+
+ @torch.no_grad()
+ def on_fit_epoch_end(self, trainer: DetectionTrainer):
+ if self.task in self.supported_tasks and self.train_epoch != trainer.epoch:
+ self.train_epoch = trainer.epoch
+ if (self.train_epoch + 1) % self.epoch_logging_interval == 0:
+ validator = trainer.validator
+ dataloader = validator.dataloader
+ class_label_map = validator.names
+ self.device = next(trainer.model.parameters()).device
+ if isinstance(trainer.model, torch.nn.parallel.DistributedDataParallel):
+ model = trainer.model.module
+ else:
+ model = trainer.model
+ self.model = copy.deepcopy(model).eval().to(self.device)
+ self.predictor.setup_model(model=self.model, verbose=False)
+ if self.task == "pose":
+ self.train_validation_table = plot_pose_validation_results(
+ dataloader=dataloader,
+ class_label_map=class_label_map,
+ model_name=self.model_name,
+ predictor=self.predictor,
+ visualize_skeleton=self.visualize_skeleton,
+ table=self.train_validation_table,
+ max_validation_batches=self.max_validation_batches,
+ epoch=trainer.epoch,
+ )
+ elif self.task == "segment":
+ self.train_validation_table = plot_segmentation_validation_results(
+ dataloader=dataloader,
+ class_label_map=class_label_map,
+ model_name=self.model_name,
+ predictor=self.predictor,
+ table=self.train_validation_table,
+ max_validation_batches=self.max_validation_batches,
+ epoch=trainer.epoch,
+ )
+ elif self.task == "detect":
+ self.train_validation_table = plot_detection_validation_results(
+ dataloader=dataloader,
+ class_label_map=class_label_map,
+ model_name=self.model_name,
+ predictor=self.predictor,
+ table=self.train_validation_table,
+ max_validation_batches=self.max_validation_batches,
+ epoch=trainer.epoch,
+ )
+ elif self.task == "classify":
+ self.train_validation_table = (
+ plot_classification_validation_results(
+ dataloader=dataloader,
+ model_name=self.model_name,
+ predictor=self.predictor,
+ table=self.train_validation_table,
+ max_validation_batches=self.max_validation_batches,
+ epoch=trainer.epoch,
+ )
+ )
+ if self.enable_model_checkpointing:
+ self._save_model(trainer)
+ trainer.model.to(self.device)
+
+ def on_train_end(self, trainer: TRAINER_TYPE):
+ if self.task in self.supported_tasks:
+ wandb.log({"Train-Table": self.train_validation_table}, commit=False)
+
+ def on_val_start(self, validator: VALIDATOR_TYPE):
+ wandb.run or wandb.init(
+ project=validator.args.project or "YOLOv8",
+ job_type="validation_" + validator.args.task,
+ )
+
+ @torch.no_grad()
+ def on_val_end(self, trainer: VALIDATOR_TYPE):
+ if self.task in self.supported_tasks:
+ validator = trainer
+ dataloader = validator.dataloader
+ class_label_map = validator.names
+ if self.task == "pose":
+ self.validation_table = plot_pose_validation_results(
+ dataloader=dataloader,
+ class_label_map=class_label_map,
+ model_name=self.model_name,
+ predictor=self.predictor,
+ visualize_skeleton=self.visualize_skeleton,
+ table=self.validation_table,
+ max_validation_batches=self.max_validation_batches,
+ )
+ elif self.task == "segment":
+ self.validation_table = plot_segmentation_validation_results(
+ dataloader=dataloader,
+ class_label_map=class_label_map,
+ model_name=self.model_name,
+ predictor=self.predictor,
+ table=self.validation_table,
+ max_validation_batches=self.max_validation_batches,
+ )
+ elif self.task == "detect":
+ self.validation_table = plot_detection_validation_results(
+ dataloader=dataloader,
+ class_label_map=class_label_map,
+ model_name=self.model_name,
+ predictor=self.predictor,
+ table=self.validation_table,
+ max_validation_batches=self.max_validation_batches,
+ )
+ elif self.task == "classify":
+ self.validation_table = plot_classification_validation_results(
+ dataloader=dataloader,
+ model_name=self.model_name,
+ predictor=self.predictor,
+ table=self.validation_table,
+ max_validation_batches=self.max_validation_batches,
+ )
+ wandb.log({"Validation-Table": self.validation_table}, commit=False)
+
+ def on_predict_start(self, predictor: PREDICTOR_TYPE):
+ wandb.run or wandb.init(
+ project=predictor.args.project or "YOLOv8",
+ config=vars(predictor.args),
+ job_type="prediction_" + predictor.args.task,
+ )
+ if isinstance(predictor, SAMPredictor):
+ self.prompts = copy.deepcopy(predictor.prompts)
+ self.prediction_table = wandb.Table(columns=["Image"])
+
+ def on_predict_end(self, predictor: PREDICTOR_TYPE):
+ wandb.config.prediction_configs = vars(predictor.args)
+ if self.task in self.supported_tasks:
+ for result in tqdm(predictor.results):
+ if self.task == "pose":
+ self.prediction_table = plot_pose_predictions(
+ result,
+ self.model_name,
+ self.visualize_skeleton,
+ self.prediction_table,
+ )
+ elif self.task == "segment":
+ if isinstance(predictor, SegmentationPredictor):
+ self.prediction_table = plot_mask_predictions(
+ result, self.model_name, self.prediction_table
+ )
+ elif isinstance(predictor, SAMPredictor):
+ self.prediction_table = plot_sam_predictions(
+ result, self.prompts, self.prediction_table
+ )
+ elif self.task == "detect":
+ self.prediction_table = plot_bbox_predictions(
+ result, self.model_name, self.prediction_table
+ )
+ elif self.task == "classify":
+ self.prediction_table = plot_classification_predictions(
+ result, self.model_name, self.prediction_table
+ )
+
+ wandb.log({"Prediction-Table": self.prediction_table}, commit=False)
+
+ @property
+ def callbacks(self) -> Dict[str, Callable]:
+ """Property contains all the relevant callbacks to add to the YOLO model for the Weights & Biases logging."""
+ return {
+ "on_train_start": self.on_train_start,
+ "on_fit_epoch_end": self.on_fit_epoch_end,
+ "on_train_end": self.on_train_end,
+ "on_val_start": self.on_val_start,
+ "on_val_end": self.on_val_end,
+ "on_predict_start": self.on_predict_start,
+ "on_predict_end": self.on_predict_end,
+ }
+
+
+# TODO: Add epoch interval
+def add_wandb_callback(
+ model: YOLO,
+ epoch_logging_interval: int = 1,
+ enable_model_checkpointing: bool = False,
+ enable_train_validation_logging: bool = True,
+ enable_validation_logging: bool = True,
+ enable_prediction_logging: bool = True,
+ max_validation_batches: Optional[int] = 1,
+ visualize_skeleton: Optional[bool] = True,
+):
+ """Function to add the `WandBUltralyticsCallback` callback to the `YOLO` model.
+
+ Example:
+ ```python
+ from ultralytics.yolo.engine.model import YOLO
+ from wandb.yolov8 import add_wandb_callback
+
+ # initialize YOLO model
+ model = YOLO("yolov8n.pt")
+
+ # add wandb callback
+ add_wandb_callback(
+ model, max_validation_batches=2, enable_model_checkpointing=True
+ )
+
+ # train
+ model.train(data="coco128.yaml", epochs=5, imgsz=640)
+
+ # validate
+ model.val()
+
+ # perform inference
+ model(["img1.jpeg", "img2.jpeg"])
+ ```
+
+ Args:
+ model: (ultralytics.yolo.engine.model.YOLO) YOLO Model of type
+ `ultralytics.yolo.engine.model.YOLO`.
+ epoch_logging_interval: (int) interval to log the prediction visualizations
+ during training.
+ enable_model_checkpointing: (bool) enable logging model checkpoints as
+ artifacts at the end of eveny epoch if set to `True`.
+ enable_train_validation_logging: (bool) enable logging the predictions and
+ ground-truths as interactive image overlays on the images from
+ the validation dataloader to a `wandb.Table` along with
+ mean-confidence of the predictions per-class at the end of each
+ training epoch.
+ enable_validation_logging: (bool) enable logging the predictions and
+ ground-truths as interactive image overlays on the images from the
+ validation dataloader to a `wandb.Table` along with
+ mean-confidence of the predictions per-class at the end of
+ validation.
+ enable_prediction_logging: (bool) enable logging the predictions and
+ ground-truths as interactive image overlays on the images from the
+ validation dataloader to a `wandb.Table` along with mean-confidence
+ of the predictions per-class at the end of each prediction.
+ max_validation_batches: (Optional[int]) maximum number of validation batches to log to
+ a table per epoch.
+ visualize_skeleton: (Optional[bool]) visualize pose skeleton by drawing lines connecting
+ keypoints for human pose.
+
+ Returns:
+ An instance of `ultralytics.yolo.engine.model.YOLO` with the `WandBUltralyticsCallback`.
+ """
+ if RANK in [-1, 0]:
+ wandb_callback = WandBUltralyticsCallback(
+ copy.deepcopy(model),
+ epoch_logging_interval,
+ max_validation_batches,
+ enable_model_checkpointing,
+ visualize_skeleton,
+ )
+ callbacks = wandb_callback.callbacks
+ if not enable_train_validation_logging:
+ _ = callbacks.pop("on_fit_epoch_end")
+ _ = callbacks.pop("on_train_end")
+ if not enable_validation_logging:
+ _ = callbacks.pop("on_val_start")
+ _ = callbacks.pop("on_val_end")
+ if not enable_prediction_logging:
+ _ = callbacks.pop("on_predict_start")
+ _ = callbacks.pop("on_predict_end")
+ for event, callback_fn in callbacks.items():
+ model.add_callback(event, callback_fn)
+ else:
+ wandb.termerror(
+ "The RANK of the process to add the callbacks was neither 0 or "
+ "-1. No Weights & Biases callbacks were added to this instance "
+ "of the YOLO model."
+ )
+ return model
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/ultralytics/classification_utils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/ultralytics/classification_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..9db6db72768dd2d16b7b44ee1ad0514a6322752f
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/ultralytics/classification_utils.py
@@ -0,0 +1,83 @@
+from typing import Any, Optional
+
+import numpy as np
+from tqdm.auto import tqdm
+from ultralytics.engine.results import Results
+from ultralytics.models.yolo.classify import ClassificationPredictor
+
+import wandb
+
+
+def plot_classification_predictions(
+ result: Results,
+ model_name: str,
+ table: Optional[wandb.Table] = None,
+ original_image: Optional[np.array] = None,
+):
+ """Plot classification prediction results to a `wandb.Table` if the table is passed otherwise return the data."""
+ result = result.to("cpu")
+ probabilities = result.probs
+ probabilities_list = probabilities.data.numpy().tolist()
+ class_id_to_label = {int(k): str(v) for k, v in result.names.items()}
+ original_image = (
+ wandb.Image(original_image)
+ if original_image is not None
+ else wandb.Image(result.orig_img)
+ )
+ table_row = [
+ model_name,
+ original_image,
+ class_id_to_label[int(probabilities.top1)],
+ probabilities.top1conf,
+ [class_id_to_label[int(class_idx)] for class_idx in list(probabilities.top5)],
+ [probabilities_list[int(class_idx)] for class_idx in list(probabilities.top5)],
+ {
+ class_id_to_label[int(class_idx)]: probability
+ for class_idx, probability in enumerate(probabilities_list)
+ },
+ result.speed,
+ ]
+ if table is not None:
+ table.add_data(*table_row)
+ return table
+ return class_id_to_label, table_row
+
+
+def plot_classification_validation_results(
+ dataloader: Any,
+ model_name: str,
+ predictor: ClassificationPredictor,
+ table: wandb.Table,
+ max_validation_batches: int,
+ epoch: Optional[int] = None,
+) -> wandb.Table:
+ """Plot classification results to a `wandb.Table`."""
+ data_idx = 0
+ num_dataloader_batches = len(dataloader.dataset) // dataloader.batch_size
+ max_validation_batches = min(max_validation_batches, num_dataloader_batches)
+ for batch_idx, batch in enumerate(dataloader):
+ image_batch = [
+ image for image in np.transpose(batch["img"].numpy(), (0, 2, 3, 1))
+ ]
+ ground_truth = batch["cls"].numpy().tolist()
+ progress_bar_result_iterable = tqdm(
+ range(max_validation_batches),
+ desc=f"Generating Visualizations for batch-{batch_idx + 1}/{max_validation_batches}",
+ )
+ for img_idx in progress_bar_result_iterable:
+ try:
+ prediction_result = predictor(image_batch[img_idx])[0]
+ class_id_to_label, table_row = plot_classification_predictions(
+ prediction_result, model_name, original_image=image_batch[img_idx]
+ )
+ table_row = [data_idx, batch_idx] + table_row[1:]
+ table_row.insert(3, class_id_to_label[ground_truth[img_idx]])
+ table_row = [epoch] + table_row if epoch is not None else table_row
+ table_row = [model_name] + table_row
+ table.add_data(*table_row)
+ data_idx += 1
+ except Exception:
+ pass
+ if batch_idx + 1 == max_validation_batches:
+ break
+ return table
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/ultralytics/mask_utils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/ultralytics/mask_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..5392d964b30ae1330349ce0978ef58eb3e5ee5dd
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/ultralytics/mask_utils.py
@@ -0,0 +1,202 @@
+from typing import Dict, Optional, Tuple
+
+import cv2
+import numpy as np
+from tqdm.auto import tqdm
+from ultralytics.engine.results import Results
+from ultralytics.models.yolo.segment import SegmentationPredictor
+from ultralytics.utils.ops import scale_image
+
+import wandb
+from wandb.integration.ultralytics.bbox_utils import (
+ get_ground_truth_bbox_annotations,
+ get_mean_confidence_map,
+)
+
+
+def instance_mask_to_semantic_mask(instance_mask, class_indices):
+ height, width, num_instances = instance_mask.shape
+ semantic_mask = np.zeros((height, width), dtype=np.uint8)
+ for i in range(num_instances):
+ instance_map = instance_mask[:, :, i]
+ class_index = class_indices[i]
+ semantic_mask[instance_map == 1] = class_index
+ return semantic_mask
+
+
+def get_boxes_and_masks(result: Results) -> Tuple[Dict, Dict, Dict]:
+ boxes = result.boxes.xywh.long().numpy()
+ classes = result.boxes.cls.long().numpy()
+ confidence = result.boxes.conf.numpy()
+ class_id_to_label = {int(k): str(v) for k, v in result.names.items()}
+ class_id_to_label.update({len(result.names.items()): "background"})
+ mean_confidence_map = get_mean_confidence_map(
+ classes, confidence, class_id_to_label
+ )
+ masks = None
+ if result.masks is not None:
+ scaled_instance_mask = scale_image(
+ np.transpose(result.masks.data.numpy(), (1, 2, 0)),
+ result.orig_img[:, :, ::-1].shape,
+ )
+ scaled_semantic_mask = instance_mask_to_semantic_mask(
+ scaled_instance_mask, classes.tolist()
+ )
+ scaled_semantic_mask[scaled_semantic_mask == 0] = len(result.names.items())
+ masks = {
+ "predictions": {
+ "mask_data": scaled_semantic_mask,
+ "class_labels": class_id_to_label,
+ }
+ }
+ box_data, total_confidence = [], 0.0
+ for idx in range(len(boxes)):
+ box_data.append(
+ {
+ "position": {
+ "middle": [int(boxes[idx][0]), int(boxes[idx][1])],
+ "width": int(boxes[idx][2]),
+ "height": int(boxes[idx][3]),
+ },
+ "domain": "pixel",
+ "class_id": int(classes[idx]),
+ "box_caption": class_id_to_label[int(classes[idx])],
+ "scores": {"confidence": float(confidence[idx])},
+ }
+ )
+ total_confidence += float(confidence[idx])
+
+ boxes = {
+ "predictions": {
+ "box_data": box_data,
+ "class_labels": class_id_to_label,
+ },
+ }
+ return boxes, masks, mean_confidence_map
+
+
+def plot_mask_predictions(
+ result: Results, model_name: str, table: Optional[wandb.Table] = None
+) -> Tuple[wandb.Image, Dict, Dict, Dict]:
+ result = result.to("cpu")
+ boxes, masks, mean_confidence_map = get_boxes_and_masks(result)
+ image = wandb.Image(result.orig_img[:, :, ::-1], boxes=boxes, masks=masks)
+ if table is not None:
+ table.add_data(
+ model_name,
+ image,
+ len(boxes["predictions"]["box_data"]),
+ mean_confidence_map,
+ result.speed,
+ )
+ return table
+ return image, masks, boxes["predictions"], mean_confidence_map
+
+
+def structure_prompts_and_image(image: np.array, prompt: Dict) -> Dict:
+ wb_box_data = []
+ if prompt["bboxes"] is not None:
+ wb_box_data.append(
+ {
+ "position": {
+ "middle": [prompt["bboxes"][0], prompt["bboxes"][1]],
+ "width": prompt["bboxes"][2],
+ "height": prompt["bboxes"][3],
+ },
+ "domain": "pixel",
+ "class_id": 1,
+ "box_caption": "Prompt-Box",
+ }
+ )
+ if prompt["points"] is not None:
+ image = image.copy().astype(np.uint8)
+ image = cv2.circle(
+ image, tuple(prompt["points"]), 5, (0, 255, 0), -1, lineType=cv2.LINE_AA
+ )
+ wb_box_data = {
+ "prompts": {
+ "box_data": wb_box_data,
+ "class_labels": {1: "Prompt-Box"},
+ }
+ }
+ return image, wb_box_data
+
+
+def plot_sam_predictions(
+ result: Results, prompt: Dict, table: wandb.Table
+) -> wandb.Table:
+ result = result.to("cpu")
+ image = result.orig_img[:, :, ::-1]
+ image, wb_box_data = structure_prompts_and_image(image, prompt)
+ image = wandb.Image(
+ image,
+ boxes=wb_box_data,
+ masks={
+ "predictions": {
+ "mask_data": np.squeeze(result.masks.data.cpu().numpy().astype(int)),
+ "class_labels": {0: "Background", 1: "Prediction"},
+ }
+ },
+ )
+ table.add_data(image)
+ return table
+
+
+def plot_segmentation_validation_results(
+ dataloader,
+ class_label_map,
+ model_name: str,
+ predictor: SegmentationPredictor,
+ table: wandb.Table,
+ max_validation_batches: int,
+ epoch: Optional[int] = None,
+):
+ data_idx = 0
+ num_dataloader_batches = len(dataloader.dataset) // dataloader.batch_size
+ max_validation_batches = min(max_validation_batches, num_dataloader_batches)
+ for batch_idx, batch in enumerate(dataloader):
+ prediction_results = predictor(batch["im_file"])
+ progress_bar_result_iterable = tqdm(
+ enumerate(prediction_results),
+ total=len(prediction_results),
+ desc=f"Generating Visualizations for batch-{batch_idx + 1}/{max_validation_batches}",
+ )
+ for img_idx, prediction_result in progress_bar_result_iterable:
+ prediction_result = prediction_result.to("cpu")
+ (
+ _,
+ prediction_mask_data,
+ prediction_box_data,
+ mean_confidence_map,
+ ) = plot_mask_predictions(prediction_result, model_name)
+ try:
+ ground_truth_data = get_ground_truth_bbox_annotations(
+ img_idx, batch["im_file"][img_idx], batch, class_label_map
+ )
+ wandb_image = wandb.Image(
+ batch["im_file"][img_idx],
+ boxes={
+ "ground-truth": {
+ "box_data": ground_truth_data,
+ "class_labels": class_label_map,
+ },
+ "predictions": prediction_box_data,
+ },
+ masks=prediction_mask_data,
+ )
+ table_rows = [
+ data_idx,
+ batch_idx,
+ wandb_image,
+ mean_confidence_map,
+ prediction_result.speed,
+ ]
+ table_rows = [epoch] + table_rows if epoch is not None else table_rows
+ table_rows = [model_name] + table_rows
+ table.add_data(*table_rows)
+ data_idx += 1
+ except TypeError:
+ pass
+ if batch_idx + 1 == max_validation_batches:
+ break
+ return table
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/ultralytics/pose_utils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/ultralytics/pose_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4cef5a90353d063e281ae54836d76675029aaa4e
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/ultralytics/pose_utils.py
@@ -0,0 +1,103 @@
+from typing import Any, Optional
+
+import numpy as np
+from PIL import Image
+from tqdm.auto import tqdm
+from ultralytics.engine.results import Results
+from ultralytics.models.yolo.pose import PosePredictor
+from ultralytics.utils.plotting import Annotator
+
+import wandb
+from wandb.integration.ultralytics.bbox_utils import (
+ get_boxes,
+ get_ground_truth_bbox_annotations,
+)
+
+
+def annotate_keypoint_results(result: Results, visualize_skeleton: bool):
+ annotator = Annotator(np.ascontiguousarray(result.orig_img[:, :, ::-1]))
+ key_points = result.keypoints.data.numpy()
+ for idx in range(key_points.shape[0]):
+ annotator.kpts(key_points[idx], kpt_line=visualize_skeleton)
+ return annotator.im
+
+
+def annotate_keypoint_batch(image_path: str, keypoints: Any, visualize_skeleton: bool):
+ with Image.open(image_path) as original_image:
+ original_image = np.ascontiguousarray(original_image)
+ annotator = Annotator(original_image)
+ annotator.kpts(keypoints.numpy(), kpt_line=visualize_skeleton)
+ return annotator.im
+
+
+def plot_pose_predictions(
+ result: Results,
+ model_name: str,
+ visualize_skeleton: bool,
+ table: Optional[wandb.Table] = None,
+):
+ result = result.to("cpu")
+ boxes, mean_confidence_map = get_boxes(result)
+ annotated_image = annotate_keypoint_results(result, visualize_skeleton)
+ prediction_image = wandb.Image(annotated_image, boxes=boxes)
+ table_row = [
+ model_name,
+ prediction_image,
+ len(boxes["predictions"]["box_data"]),
+ mean_confidence_map,
+ result.speed,
+ ]
+ if table is not None:
+ table.add_data(*table_row)
+ return table
+ return table_row
+
+
+def plot_pose_validation_results(
+ dataloader,
+ class_label_map,
+ model_name: str,
+ predictor: PosePredictor,
+ visualize_skeleton: bool,
+ table: wandb.Table,
+ max_validation_batches: int,
+ epoch: Optional[int] = None,
+) -> wandb.Table:
+ data_idx = 0
+ num_dataloader_batches = len(dataloader.dataset) // dataloader.batch_size
+ max_validation_batches = min(max_validation_batches, num_dataloader_batches)
+ for batch_idx, batch in enumerate(dataloader):
+ prediction_results = predictor(batch["im_file"])
+ progress_bar_result_iterable = tqdm(
+ enumerate(prediction_results),
+ total=len(prediction_results),
+ desc=f"Generating Visualizations for batch-{batch_idx + 1}/{max_validation_batches}",
+ )
+ for img_idx, prediction_result in progress_bar_result_iterable:
+ prediction_result = prediction_result.to("cpu")
+ table_row = plot_pose_predictions(
+ prediction_result, model_name, visualize_skeleton
+ )
+ ground_truth_image = wandb.Image(
+ annotate_keypoint_batch(
+ batch["im_file"][img_idx],
+ batch["keypoints"][img_idx],
+ visualize_skeleton,
+ ),
+ boxes={
+ "ground-truth": {
+ "box_data": get_ground_truth_bbox_annotations(
+ img_idx, batch["im_file"][img_idx], batch, class_label_map
+ ),
+ "class_labels": class_label_map,
+ },
+ },
+ )
+ table_row = [data_idx, batch_idx, ground_truth_image] + table_row[1:]
+ table_row = [epoch] + table_row if epoch is not None else table_row
+ table_row = [model_name] + table_row
+ table.add_data(*table_row)
+ data_idx += 1
+ if batch_idx + 1 == max_validation_batches:
+ break
+ return table
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/weave/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/weave/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d83d8eb03d3a48a867a5d695ccc524b1f5eefad3
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/weave/__init__.py
@@ -0,0 +1,6 @@
+"""Weave integration for W&B."""
+
+from .interface import RunPath, active_run_path
+from .weave import setup
+
+__all__ = ("active_run_path", "RunPath", "setup")
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/weave/interface.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/weave/interface.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d1db8ab1d2eb9739e00586bca6f06c7e6f6590b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/weave/interface.py
@@ -0,0 +1,49 @@
+"""Internal APIs for integrating with weave.
+
+The public functions here are intended to be called by weave and care should
+be taken to maintain backward compatibility.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+
+from wandb.sdk import wandb_setup
+
+
+@dataclasses.dataclass(frozen=True)
+class RunPath:
+ entity: str
+ """The entity to which the run is logging. Never empty."""
+
+ project: str
+ """The project to which the run is logging. Never empty."""
+
+ run_id: str
+ """The run's ID. Never empty."""
+
+
+def active_run_path() -> RunPath | None:
+ """Returns the path of an initialized, unfinished run.
+
+ Returns None if all initialized runs are finished. If there is
+ more than one active run, an arbitrary path is returned.
+ The run may be finished by the time its path is returned.
+
+ Thread-safe.
+ """
+ singleton = wandb_setup.singleton()
+
+ if (
+ (run := singleton.most_recent_active_run)
+ and run.entity
+ and run.project
+ and run.id
+ ):
+ return RunPath(
+ entity=run.entity,
+ project=run.project,
+ run_id=run.id,
+ )
+
+ return None
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/weave/weave.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/weave/weave.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9fa2763d65f23f62550b63b852d5ba402f1ba78
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/weave/weave.py
@@ -0,0 +1,118 @@
+"""Integration module for automatic Weave initialization with W&B.
+
+This module provides automatic initialization of Weave when:
+1. Weave is installed
+2. A W&B run is active with a project
+3. Weave is imported (init-on-import)
+
+The integration can be disabled by setting the WANDB_DISABLE_WEAVE environment variable.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import os
+import sys
+import threading
+
+import wandb
+
+_weave_init_lock = threading.Lock()
+
+_DISABLE_WEAVE = "WANDB_DISABLE_WEAVE"
+_WEAVE_PACKAGE_NAME = "weave"
+
+# This list is adapted from https://github.com/wandb/weave/blob/master/weave/integrations/__init__.py
+_AVAILABLE_WEAVE_INTEGRATIONS = [
+ "anthropic",
+ "autogen",
+ "cohere",
+ "crewai",
+ "dspy",
+ "google.genai",
+ "groq",
+ "huggingface_hub.inference",
+ "instructor",
+ "langchain",
+ "litellm",
+ "llama_index",
+ "mcp",
+ "mistral",
+ "notdiamond",
+ "openai",
+ "agents",
+ "smolagents",
+ "verdict",
+ "verifiers",
+ "vertexai",
+]
+
+
+def setup(entity: str | None, project: str | None) -> None:
+ """Set up automatic Weave initialization for the current W&B run.
+
+ Args:
+ project: The W&B project name to use for Weave initialization.
+ """
+ # We can't or shouldn't init weave; return
+ if os.getenv(_DISABLE_WEAVE):
+ return
+ if not project:
+ return
+
+ # Use entity/project when available; otherwise fall back to project only
+ if entity:
+ project_path = f"{entity}/{project}"
+ else:
+ project_path = project
+
+ # If weave is not yet imported, we can't init it from here. Instead, we'll
+ # rely on the weave library itself to detect a run and init itself.
+ if _WEAVE_PACKAGE_NAME not in sys.modules:
+ _maybe_suggest_weave_installation()
+ return
+
+ # If weave has already been imported, initialize immediately
+ with _weave_init_lock:
+ try:
+ # This import should have already happened, so it's effectively a no-op.
+ # We just import to keep the symbol for the init that follows
+ import weave
+ except ImportError:
+ # This should never happen; but we don't raise here to avoid
+ # breaking the wandb run init flow just in case
+ return
+
+ wandb.termlog("Initializing weave.")
+ try:
+ weave.init(project_path)
+ except Exception as e:
+ wandb.termwarn(f"Failed to automatically initialize Weave: {e}")
+
+
+def _maybe_suggest_weave_installation() -> None:
+ """Suggest Weave installation or import if any target library is imported."""
+ imported_libs = [lib for lib in _AVAILABLE_WEAVE_INTEGRATIONS if lib in sys.modules]
+ if not imported_libs:
+ return
+
+ weave_spec = importlib.util.find_spec(_WEAVE_PACKAGE_NAME)
+ if weave_spec is None:
+ # Weave is not installed
+ msg = (
+ "Use W&B Weave for improved LLM call tracing. Install Weave with "
+ "`pip install weave` then add `import weave` to the top of your script."
+ )
+ else:
+ # Weave is installed but not imported
+ msg = (
+ "Use W&B Weave for improved LLM call tracing. Weave is installed "
+ "but not imported. Add `import weave` to the top of your script."
+ )
+
+ wandb.termlog(f"Detected [{', '.join(imported_libs)}] in use.", repeat=False)
+ wandb.termlog(msg, repeat=False)
+ wandb.termlog(
+ "For more information, check out the docs at: https://weave-docs.wandb.ai/",
+ repeat=False,
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/xgboost/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/xgboost/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..052083e0cf7034a469a82582422ff7fee62965a5
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/xgboost/__init__.py
@@ -0,0 +1,11 @@
+"""W&B callback for xgboost.
+
+Simple callback to get logging for each tree
+
+Use the `wandb_callback` to add `wandb` logging to any `XGboost` model. However, it will
+be deprecated in favor of WandbCallback. Use it instead for more features.
+"""
+
+from .xgboost import WandbCallback, wandb_callback
+
+__all__ = ["wandb_callback", "WandbCallback"]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/xgboost/xgboost.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/xgboost/xgboost.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a8b63dfa2f39db9d40989dc8562cc732ba11d98
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/xgboost/xgboost.py
@@ -0,0 +1,189 @@
+"""xgboost init!"""
+
+import json
+import warnings
+from pathlib import Path
+from typing import TYPE_CHECKING, cast
+
+import xgboost as xgb # type: ignore
+from xgboost import Booster
+
+import wandb
+from wandb.sdk.lib import telemetry as wb_telemetry
+
+MINIMIZE_METRICS = [
+ "rmse",
+ "rmsle",
+ "mae",
+ "mape",
+ "mphe",
+ "logloss",
+ "error",
+ "error@t",
+ "merror",
+]
+
+MAXIMIZE_METRICS = ["auc", "aucpr", "ndcg", "map", "ndcg@n", "map@n"]
+
+
+if TYPE_CHECKING:
+ from typing import Callable, List, NamedTuple
+
+ class CallbackEnv(NamedTuple):
+ evaluation_result_list: List
+
+
+def wandb_callback() -> "Callable":
+ """Old style callback that will be deprecated in favor of WandbCallback. Please try the new logger for more features."""
+ warnings.warn(
+ "wandb_callback will be deprecated in favor of WandbCallback. Please use WandbCallback for more features.",
+ UserWarning,
+ stacklevel=2,
+ )
+
+ with wb_telemetry.context() as tel:
+ tel.feature.xgboost_old_wandb_callback = True
+
+ def callback(env: "CallbackEnv") -> None:
+ for k, v in env.evaluation_result_list:
+ wandb.log({k: v}, commit=False)
+ wandb.log({})
+
+ return callback
+
+
+class WandbCallback(xgb.callback.TrainingCallback):
+ """`WandbCallback` automatically integrates XGBoost with wandb.
+
+ Args:
+ log_model: (boolean) if True save and upload the model to Weights & Biases Artifacts
+ log_feature_importance: (boolean) if True log a feature importance bar plot
+ importance_type: (str) one of {weight, gain, cover, total_gain, total_cover} for tree model. weight for linear model.
+ define_metric: (boolean) if True (default) capture model performance at the best step, instead of the last step, of training in your `wandb.summary`.
+
+ Passing `WandbCallback` to XGBoost will:
+
+ - log the booster model configuration to Weights & Biases
+ - log evaluation metrics collected by XGBoost, such as rmse, accuracy etc. to Weights & Biases
+ - log training metric collected by XGBoost (if you provide training data to eval_set)
+ - log the best score and the best iteration
+ - save and upload your trained model to Weights & Biases Artifacts (when `log_model = True`)
+ - log feature importance plot when `log_feature_importance=True` (default).
+ - Capture the best eval metric in `wandb.summary` when `define_metric=True` (default).
+
+ Example:
+ ```python
+ bst_params = dict(
+ objective="reg:squarederror",
+ colsample_bytree=0.3,
+ learning_rate=0.1,
+ max_depth=5,
+ alpha=10,
+ n_estimators=10,
+ tree_method="hist",
+ callbacks=[WandbCallback()],
+ )
+
+ xg_reg = xgb.XGBRegressor(**bst_params)
+ xg_reg.fit(
+ X_train,
+ y_train,
+ eval_set=[(X_test, y_test)],
+ )
+ ```
+ """
+
+ def __init__(
+ self,
+ log_model: bool = False,
+ log_feature_importance: bool = True,
+ importance_type: str = "gain",
+ define_metric: bool = True,
+ ):
+ self.log_model: bool = log_model
+ self.log_feature_importance: bool = log_feature_importance
+ self.importance_type: str = importance_type
+ self.define_metric: bool = define_metric
+
+ if wandb.run is None:
+ raise wandb.Error("You must call wandb.init() before WandbCallback()")
+
+ with wb_telemetry.context() as tel:
+ tel.feature.xgboost_wandb_callback = True
+
+ def before_training(self, model: Booster) -> Booster:
+ """Run before training is finished."""
+ # Update W&B config
+ config = model.save_config()
+ wandb.config.update(json.loads(config))
+
+ return model
+
+ def after_training(self, model: Booster) -> Booster:
+ """Run after training is finished."""
+ # Log the booster model as artifacts
+ if self.log_model:
+ self._log_model_as_artifact(model)
+
+ # Plot feature importance
+ if self.log_feature_importance:
+ self._log_feature_importance(model)
+
+ # Log the best score and best iteration
+ if model.attr("best_score") is not None:
+ wandb.log(
+ {
+ "best_score": float(cast(str, model.attr("best_score"))),
+ "best_iteration": int(cast(str, model.attr("best_iteration"))),
+ }
+ )
+
+ return model
+
+ def after_iteration(self, model: Booster, epoch: int, evals_log: dict) -> bool:
+ """Run after each iteration. Return True when training should stop."""
+ # Log metrics
+ for data, metric in evals_log.items():
+ for metric_name, log in metric.items():
+ if self.define_metric:
+ self._define_metric(data, metric_name)
+ wandb.log({f"{data}-{metric_name}": log[-1]}, commit=False)
+ else:
+ wandb.log({f"{data}-{metric_name}": log[-1]}, commit=False)
+
+ wandb.log({"epoch": epoch})
+
+ self.define_metric = False
+
+ return False
+
+ def _log_model_as_artifact(self, model: Booster) -> None:
+ model_name = f"{wandb.run.id}_model.json" # type: ignore
+ model_path = Path(wandb.run.dir) / model_name # type: ignore
+ model.save_model(str(model_path))
+
+ model_artifact = wandb.Artifact(name=model_name, type="model")
+ model_artifact.add_file(str(model_path))
+ wandb.log_artifact(model_artifact)
+
+ def _log_feature_importance(self, model: Booster) -> None:
+ fi = model.get_score(importance_type=self.importance_type)
+ fi_data = [[k, fi[k]] for k in fi]
+ table = wandb.Table(data=fi_data, columns=["Feature", "Importance"])
+ wandb.log(
+ {
+ "Feature Importance": wandb.plot.bar(
+ table, "Feature", "Importance", title="Feature Importance"
+ )
+ }
+ )
+
+ def _define_metric(self, data: str, metric_name: str) -> None:
+ if "loss" in str.lower(metric_name):
+ wandb.define_metric(f"{data}-{metric_name}", summary="min")
+ elif str.lower(metric_name) in MINIMIZE_METRICS:
+ wandb.define_metric(f"{data}-{metric_name}", summary="min")
+ elif str.lower(metric_name) in MAXIMIZE_METRICS:
+ wandb.define_metric(f"{data}-{metric_name}", summary="max")
+ else:
+ pass
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/yolov8/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/yolov8/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/yolov8/yolov8.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/yolov8/yolov8.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c5dbd0fe8de39f387b6427b4696f28f9c029b44
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/integration/yolov8/yolov8.py
@@ -0,0 +1,284 @@
+from typing import Any, Callable, Dict, List, Optional
+
+from ultralytics.yolo.engine.model import YOLO
+from ultralytics.yolo.engine.trainer import BaseTrainer
+
+try:
+ from ultralytics.yolo.utils import RANK
+ from ultralytics.yolo.utils.torch_utils import get_flops, get_num_params
+except ModuleNotFoundError:
+ from ultralytics.utils import RANK
+ from ultralytics.utils.torch_utils import get_flops, get_num_params
+from ultralytics.yolo.v8.classify.train import ClassificationTrainer
+
+import wandb
+from wandb.sdk.lib import telemetry
+
+
+class WandbCallback:
+ """An internal YOLO model wrapper that tracks metrics, and logs models to Weights & Biases.
+
+ Usage:
+ ```python
+ from wandb.integration.yolov8.yolov8 import WandbCallback
+
+ model = YOLO("yolov8n.pt")
+ wandb_logger = WandbCallback(
+ model,
+ )
+ for event, callback_fn in wandb_logger.callbacks.items():
+ model.add_callback(event, callback_fn)
+ ```
+ """
+
+ def __init__(
+ self,
+ yolo: YOLO,
+ run_name: Optional[str] = None,
+ project: Optional[str] = None,
+ tags: Optional[List[str]] = None,
+ resume: Optional[str] = None,
+ **kwargs: Optional[Any],
+ ) -> None:
+ """A utility class to manage wandb run and various callbacks for the ultralytics YOLOv8 framework.
+
+ Args:
+ yolo: A YOLOv8 model that's inherited from `:class:ultralytics.yolo.engine.model.YOLO`
+ run_name, str: The name of the Weights & Biases run, defaults to an auto generated run_name if `trainer.args.name` is not defined.
+ project, str: The name of the Weights & Biases project, defaults to `"YOLOv8"` if `trainer.args.project` is not defined.
+ tags, List[str]: A list of tags to be added to the Weights & Biases run, defaults to `["YOLOv8"]`.
+ resume, str: Whether to resume a previous run on Weights & Biases, defaults to `None`.
+ **kwargs: Additional arguments to be passed to `wandb.init()`.
+ """
+ self.yolo = yolo
+ self.run_name = run_name
+ self.project = project
+ self.tags = tags
+ self.resume = resume
+ self.kwargs = kwargs
+
+ def on_pretrain_routine_start(self, trainer: BaseTrainer) -> None:
+ """Starts a new wandb run to track the training process and log to Weights & Biases.
+
+ Args:
+ trainer: A task trainer that's inherited from `:class:ultralytics.yolo.engine.trainer.BaseTrainer`
+ that contains the model training and optimization routine.
+ """
+ if wandb.run is None:
+ self.run = wandb.init(
+ name=self.run_name if self.run_name else trainer.args.name,
+ project=self.project
+ if self.project
+ else trainer.args.project or "YOLOv8",
+ tags=self.tags if self.tags else ["YOLOv8"],
+ config=vars(trainer.args),
+ resume=self.resume if self.resume else None,
+ **self.kwargs,
+ )
+ else:
+ self.run = wandb.run
+ assert self.run is not None
+ self.run.define_metric("epoch", hidden=True)
+ self.run.define_metric(
+ "train/*", step_metric="epoch", step_sync=True, summary="min"
+ )
+
+ self.run.define_metric(
+ "val/*", step_metric="epoch", step_sync=True, summary="min"
+ )
+
+ self.run.define_metric(
+ "metrics/*", step_metric="epoch", step_sync=True, summary="max"
+ )
+ self.run.define_metric(
+ "lr/*", step_metric="epoch", step_sync=True, summary="last"
+ )
+
+ with telemetry.context(run=wandb.run) as tel:
+ tel.feature.ultralytics_yolov8 = True
+
+ def on_pretrain_routine_end(self, trainer: BaseTrainer) -> None:
+ assert self.run is not None
+ self.run.summary.update(
+ {
+ "model/parameters": get_num_params(trainer.model),
+ "model/GFLOPs": round(get_flops(trainer.model), 3),
+ }
+ )
+
+ def on_train_epoch_start(self, trainer: BaseTrainer) -> None:
+ """On train epoch start we only log epoch number to the Weights & Biases run."""
+ # We log the epoch number here to commit the previous step,
+ assert self.run is not None
+ self.run.log({"epoch": trainer.epoch + 1})
+
+ def on_train_epoch_end(self, trainer: BaseTrainer) -> None:
+ """On train epoch end we log all the metrics to the Weights & Biases run."""
+ assert self.run is not None
+ self.run.log(
+ {
+ **trainer.metrics,
+ **trainer.label_loss_items(trainer.tloss, prefix="train"),
+ **trainer.lr,
+ },
+ )
+ # Currently only the detection and segmentation trainers save images to the save_dir
+ if not isinstance(trainer, ClassificationTrainer):
+ self.run.log(
+ {
+ "train_batch_images": [
+ wandb.Image(str(image_path), caption=image_path.stem)
+ for image_path in trainer.save_dir.glob("train_batch*.jpg")
+ ]
+ }
+ )
+
+ def on_fit_epoch_end(self, trainer: BaseTrainer) -> None:
+ """On fit epoch end we log all the best metrics and model detail to Weights & Biases run summary."""
+ assert self.run is not None
+ if trainer.epoch == 0:
+ speeds = [
+ trainer.validator.speed.get(
+ key,
+ )
+ for key in (1, "inference")
+ ]
+ speed = speeds[0] if speeds[0] else speeds[1]
+ if speed:
+ self.run.summary.update(
+ {
+ "model/speed(ms/img)": round(speed, 3),
+ }
+ )
+ if trainer.best_fitness == trainer.fitness:
+ self.run.summary.update(
+ {
+ "best/epoch": trainer.epoch + 1,
+ **{f"best/{key}": val for key, val in trainer.metrics.items()},
+ }
+ )
+
+ def on_train_end(self, trainer: BaseTrainer) -> None:
+ """On train end we log all the media, including plots, images and best model artifact to Weights & Biases."""
+ # Currently only the detection and segmentation trainers save images to the save_dir
+ assert self.run is not None
+ if not isinstance(trainer, ClassificationTrainer):
+ assert self.run is not None
+ self.run.log(
+ {
+ "plots": [
+ wandb.Image(str(image_path), caption=image_path.stem)
+ for image_path in trainer.save_dir.glob("*.png")
+ ],
+ "val_images": [
+ wandb.Image(str(image_path), caption=image_path.stem)
+ for image_path in trainer.validator.save_dir.glob("val*.jpg")
+ ],
+ },
+ )
+
+ if trainer.best.exists():
+ assert self.run is not None
+ self.run.log_artifact(
+ str(trainer.best),
+ type="model",
+ name=f"{self.run.name}_{trainer.args.task}.pt",
+ aliases=["best", f"epoch_{trainer.epoch + 1}"],
+ )
+
+ def on_model_save(self, trainer: BaseTrainer) -> None:
+ """On model save we log the model as an artifact to Weights & Biases."""
+ assert self.run is not None
+ self.run.log_artifact(
+ str(trainer.last),
+ type="model",
+ name=f"{self.run.name}_{trainer.args.task}.pt",
+ aliases=["last", f"epoch_{trainer.epoch + 1}"],
+ )
+
+ def teardown(self, _trainer: BaseTrainer) -> None:
+ """On teardown, we finish the Weights & Biases run and set it to None."""
+ assert self.run is not None
+ self.run.finish()
+ self.run = None
+
+ @property
+ def callbacks(
+ self,
+ ) -> Dict[str, Callable]:
+ """Property contains all the relevant callbacks to add to the YOLO model for the Weights & Biases logging."""
+ return {
+ "on_pretrain_routine_start": self.on_pretrain_routine_start,
+ "on_pretrain_routine_end": self.on_pretrain_routine_end,
+ "on_train_epoch_start": self.on_train_epoch_start,
+ "on_train_epoch_end": self.on_train_epoch_end,
+ "on_fit_epoch_end": self.on_fit_epoch_end,
+ "on_train_end": self.on_train_end,
+ "on_model_save": self.on_model_save,
+ "teardown": self.teardown,
+ }
+
+
+def add_callbacks(
+ yolo: YOLO,
+ run_name: Optional[str] = None,
+ project: Optional[str] = None,
+ tags: Optional[List[str]] = None,
+ resume: Optional[str] = None,
+ **kwargs: Optional[Any],
+) -> YOLO:
+ """A YOLO model wrapper that tracks metrics, and logs models to Weights & Biases.
+
+ Args:
+ yolo: A YOLOv8 model that's inherited from `:class:ultralytics.yolo.engine.model.YOLO`
+ run_name, str: The name of the Weights & Biases run, defaults to an auto generated name if `trainer.args.name` is not defined.
+ project, str: The name of the Weights & Biases project, defaults to `"YOLOv8"` if `trainer.args.project` is not defined.
+ tags, List[str]: A list of tags to be added to the Weights & Biases run, defaults to `["YOLOv8"]`.
+ resume, str: Whether to resume a previous run on Weights & Biases, defaults to `None`.
+ **kwargs: Additional arguments to be passed to `wandb.init()`.
+
+ Usage:
+ ```python
+ from wandb.integration.yolov8 import add_callbacks as add_wandb_callbacks
+
+ model = YOLO("yolov8n.pt")
+ add_wandb_callbacks(
+ model,
+ )
+ model.train(
+ data="coco128.yaml",
+ epochs=3,
+ imgsz=640,
+ )
+ ```
+ """
+ wandb.termwarn(
+ """The wandb callback is currently in beta and is subject to change based on updates to `ultralytics yolov8`.
+ The callback is tested and supported for ultralytics v8.0.43 and above.
+ Please report any issues to https://github.com/wandb/wandb/issues with the tag `yolov8`.
+ """,
+ repeat=False,
+ )
+ wandb.termwarn(
+ """This wandb callback is no longer functional and would be deprecated in the near future.
+ We recommend you to use the updated callback using `from wandb.integration.ultralytics import add_wandb_callback`.
+ The updated callback is tested and supported for ultralytics 8.0.167 and above.
+ You can refer to https://docs.wandb.ai/guides/integrations/ultralytics for the updated documentation.
+ Please report any issues to https://github.com/wandb/wandb/issues with the tag `yolov8`.
+ """,
+ repeat=False,
+ )
+
+ if RANK in [-1, 0]:
+ wandb_logger = WandbCallback(
+ yolo, run_name=run_name, project=project, tags=tags, resume=resume, **kwargs
+ )
+ for event, callback_fn in wandb_logger.callbacks.items():
+ yolo.add_callback(event, callback_fn)
+ return yolo
+ else:
+ wandb.termerror(
+ "The RANK of the process to add the callbacks was neither 0 or -1."
+ "No Weights & Biases callbacks were added to this instance of the YOLO model."
+ )
+ return yolo
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/jupyter.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/jupyter.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee69ebc04d620ca5f3803cfe05f66c657839f435
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/jupyter.py
@@ -0,0 +1,538 @@
+from __future__ import annotations
+
+import json
+import logging
+import os
+import re
+import shutil
+import sys
+import traceback
+from base64 import b64encode
+from typing import Any
+
+import IPython
+import IPython.display
+import requests
+from IPython.core.magic import Magics, line_cell_magic, magics_class
+from IPython.core.magic_arguments import argument, magic_arguments, parse_argstring
+from requests.compat import urljoin
+
+import wandb
+import wandb.util
+from wandb.sdk import wandb_setup
+from wandb.sdk.lib import filesystem
+
+logger = logging.getLogger(__name__)
+
+
+def display_if_magic_is_used(run: wandb.Run) -> bool:
+ """Display a run's page if the cell has the %%wandb cell magic.
+
+ Args:
+ run: The run to display.
+
+ Returns:
+ Whether the %%wandb cell magic was present.
+ """
+ if not _current_cell_wandb_magic:
+ return False
+
+ _current_cell_wandb_magic.display_if_allowed(run)
+ return True
+
+
+class _WandbCellMagicState:
+ """State for a cell with the %%wandb cell magic."""
+
+ def __init__(self, *, height: int) -> None:
+ """Initializes the %%wandb cell magic state.
+
+ Args:
+ height: The desired height for displayed iframes.
+ """
+ self._height = height
+ self._already_displayed = False
+
+ def display_if_allowed(self, run: wandb.Run) -> None:
+ """Display a run's iframe if one is not already displayed.
+
+ Args:
+ run: The run to display.
+ """
+ if self._already_displayed:
+ return
+ self._already_displayed = True
+
+ _display_wandb_run(run, height=self._height)
+
+
+_current_cell_wandb_magic: _WandbCellMagicState | None = None
+
+
+def _display_by_wandb_path(path: str, *, height: int) -> None:
+ """Display a wandb object (usually in an iframe) given its URI.
+
+ Args:
+ path: A path to a run, sweep, project, report, etc.
+ height: Height of the iframe in pixels.
+ """
+ api = wandb.Api()
+
+ try:
+ obj = api.from_path(path)
+
+ IPython.display.display_html(
+ obj.to_html(height=height),
+ raw=True,
+ )
+ except wandb.Error:
+ traceback.print_exc()
+ IPython.display.display_html(
+ f"Path {path!r} does not refer to a W&B object you can access.",
+ raw=True,
+ )
+
+
+def _display_wandb_run(run: wandb.Run, *, height: int) -> None:
+ """Display a run (usually in an iframe).
+
+ Args:
+ run: The run to display.
+ height: Height of the iframe in pixels.
+ """
+ IPython.display.display_html(
+ run.to_html(height=height),
+ raw=True,
+ )
+
+
+@magics_class
+class WandBMagics(Magics):
+ def __init__(self, shell):
+ super().__init__(shell)
+
+ @magic_arguments()
+ @argument(
+ "path",
+ default=None,
+ nargs="?",
+ help="The path to a resource you want to display.",
+ )
+ @argument(
+ "-h",
+ "--height",
+ default=420,
+ type=int,
+ help="The height of the iframe in pixels.",
+ )
+ @line_cell_magic
+ def wandb(self, line: str, cell: str | None = None) -> None:
+ """Display wandb resources in Jupyter.
+
+ This can be used as a line magic:
+
+ %wandb USERNAME/PROJECT/runs/RUN_ID
+
+ Or as a cell magic:
+
+ %%wandb -h 1024
+ with wandb.init() as run:
+ run.log({"loss": 1})
+ """
+ global _current_cell_wandb_magic
+
+ args = parse_argstring(self.wandb, line)
+ path: str | None = args.path
+ height: int = args.height
+
+ if path:
+ _display_by_wandb_path(path, height=height)
+ displayed = True
+ elif run := wandb_setup.singleton().most_recent_active_run:
+ _display_wandb_run(run, height=height)
+ displayed = True
+ else:
+ displayed = False
+
+ # If this is being used as a line magic ("%wandb"), we are done.
+ # When used as a cell magic ("%%wandb"), we must run the cell.
+ if cell is None:
+ return
+
+ if not displayed:
+ _current_cell_wandb_magic = _WandbCellMagicState(height=height)
+
+ try:
+ IPython.get_ipython().run_cell(cell)
+ finally:
+ _current_cell_wandb_magic = None
+
+
+def notebook_metadata_from_jupyter_servers_and_kernel_id():
+ servers, kernel_id = jupyter_servers_and_kernel_id()
+ for s in servers:
+ if s.get("password"):
+ raise ValueError("Can't query password protected kernel")
+ res = requests.get(
+ urljoin(s["url"], "api/sessions"), params={"token": s.get("token", "")}
+ ).json()
+ for nn in res:
+ if isinstance(nn, dict) and nn.get("kernel") and "notebook" in nn:
+ if nn["kernel"]["id"] == kernel_id:
+ return {
+ "root": s.get("root_dir", s.get("notebook_dir", os.getcwd())),
+ "path": nn["notebook"]["path"],
+ "name": nn["notebook"]["name"],
+ }
+
+ if not kernel_id:
+ return None
+
+ # Built-in notebook server in VS Code
+ try:
+ from IPython import get_ipython
+
+ ipython = get_ipython()
+ notebook_path = ipython.kernel.shell.user_ns.get("__vsc_ipynb_file__")
+ if notebook_path:
+ return {
+ "root": os.path.dirname(notebook_path),
+ "path": notebook_path,
+ "name": os.path.basename(notebook_path),
+ }
+ except Exception:
+ return None
+
+
+def notebook_metadata(silent: bool) -> dict[str, str]:
+ """Attempt to query jupyter for the path and name of the notebook file.
+
+ This can handle different jupyter environments, specifically:
+
+ 1. Colab
+ 2. Kaggle
+ 3. JupyterLab
+ 4. Notebooks
+ 5. Other?
+ """
+ error_message = (
+ "Failed to detect the name of this notebook. You can set it manually"
+ " with the WANDB_NOTEBOOK_NAME environment variable to enable code"
+ " saving."
+ )
+ try:
+ jupyter_metadata = notebook_metadata_from_jupyter_servers_and_kernel_id()
+
+ # Colab:
+ # request the most recent contents
+ ipynb = attempt_colab_load_ipynb()
+ if ipynb is not None and jupyter_metadata is not None:
+ return {
+ "root": "/content",
+ "path": jupyter_metadata["path"],
+ "name": jupyter_metadata["name"],
+ }
+
+ # Kaggle:
+ if wandb.util._is_kaggle():
+ # request the most recent contents
+ ipynb = attempt_kaggle_load_ipynb()
+ if ipynb:
+ return {
+ "root": "/kaggle/working",
+ "path": ipynb["metadata"]["name"],
+ "name": ipynb["metadata"]["name"],
+ }
+
+ if jupyter_metadata:
+ return jupyter_metadata
+ except Exception:
+ logger.exception(error_message)
+
+ wandb.termerror(error_message)
+ return {}
+
+
+def jupyter_servers_and_kernel_id():
+ """Return a list of servers and the current kernel_id.
+
+ Used to query for the name of the notebook.
+ """
+ try:
+ import ipykernel # type: ignore
+
+ kernel_id = re.search(
+ "kernel-(.*).json", ipykernel.connect.get_connection_file()
+ ).group(1)
+ # We're either in jupyterlab or a notebook, lets prefer the newer jupyter_server package
+ serverapp = wandb.util.get_module("jupyter_server.serverapp")
+ notebookapp = wandb.util.get_module("notebook.notebookapp")
+ servers = []
+ if serverapp is not None:
+ servers.extend(list(serverapp.list_running_servers()))
+ if notebookapp is not None:
+ servers.extend(list(notebookapp.list_running_servers()))
+ except (AttributeError, ValueError, ImportError):
+ return [], None
+
+ return servers, kernel_id
+
+
+def attempt_colab_load_ipynb():
+ colab = wandb.util.get_module("google.colab")
+ if colab:
+ # This isn't thread safe, never call in a thread
+ response = colab._message.blocking_request("get_ipynb", timeout_sec=5)
+ if response:
+ return response["ipynb"]
+
+
+def attempt_kaggle_load_ipynb():
+ kaggle = wandb.util.get_module("kaggle_session")
+ if not kaggle:
+ return None
+
+ try:
+ client = kaggle.UserSessionClient()
+ parsed = json.loads(client.get_exportable_ipynb()["source"])
+ # TODO: couldn't find a way to get the name of the notebook...
+ parsed["metadata"]["name"] = "kaggle.ipynb"
+ except Exception:
+ wandb.termerror("Unable to load kaggle notebook.")
+ logger.exception("Unable to load kaggle notebook.")
+ return None
+
+ return parsed
+
+
+def attempt_colab_login(
+ app_url: str,
+ referrer: str | None = None,
+):
+ """This renders an iframe to wandb in the hopes it posts back an api key."""
+ from google.colab import output # type: ignore
+ from google.colab._message import MessageError # type: ignore
+ from IPython import display
+
+ display.display(
+ display.Javascript(
+ """
+ window._wandbApiKey = new Promise((resolve, reject) => {{
+ function loadScript(url) {{
+ return new Promise(function(resolve, reject) {{
+ let newScript = document.createElement("script");
+ newScript.onerror = reject;
+ newScript.onload = resolve;
+ document.body.appendChild(newScript);
+ newScript.src = url;
+ }});
+ }}
+ loadScript("https://cdn.jsdelivr.net/npm/postmate/build/postmate.min.js").then(() => {{
+ const iframe = document.createElement('iframe')
+ iframe.style.cssText = "width:0;height:0;border:none"
+ document.body.appendChild(iframe)
+ const handshake = new Postmate({{
+ container: iframe,
+ url: '{}/authorize{}'
+ }});
+ const timeout = setTimeout(() => reject("Couldn't auto authenticate"), 5000)
+ handshake.then(function(child) {{
+ child.on('authorize', data => {{
+ clearTimeout(timeout)
+ resolve(data)
+ }});
+ }});
+ }})
+ }});
+ """.format(
+ app_url.replace("http:", "https:"),
+ f"?ref={referrer}" if referrer else "",
+ )
+ )
+ )
+ try:
+ return output.eval_js("_wandbApiKey")
+ except MessageError:
+ return None
+
+
+class Notebook:
+ def __init__(self, settings: wandb.Settings) -> None:
+ self.outputs: dict[int, Any] = {}
+ self.settings = settings
+ self.shell = IPython.get_ipython()
+
+ def save_display(self, exc_count, data_with_metadata):
+ self.outputs[exc_count] = self.outputs.get(exc_count, [])
+
+ # byte values such as images need to be encoded in base64
+ # otherwise nbformat.v4.new_output will throw a NotebookValidationError
+ data = data_with_metadata["data"]
+ b64_data = {}
+ for key in data:
+ val = data[key]
+ if isinstance(val, bytes):
+ b64_data[key] = b64encode(val).decode("utf-8")
+ else:
+ b64_data[key] = val
+
+ self.outputs[exc_count].append(
+ {"data": b64_data, "metadata": data_with_metadata["metadata"]}
+ )
+
+ def probe_ipynb(self):
+ """Return notebook as dict or None."""
+ relpath = self.settings.x_jupyter_path
+ if relpath:
+ if os.path.exists(relpath):
+ with open(relpath) as json_file:
+ data = json.load(json_file)
+ return data
+
+ colab_ipynb = attempt_colab_load_ipynb()
+ if colab_ipynb:
+ return colab_ipynb
+
+ kaggle_ipynb = attempt_kaggle_load_ipynb()
+ if kaggle_ipynb and len(kaggle_ipynb["cells"]) > 0:
+ return kaggle_ipynb
+
+ return
+
+ def save_ipynb(self) -> bool:
+ if not self.settings.save_code:
+ logger.info("not saving jupyter notebook")
+ return False
+ ret = False
+ try:
+ ret = self._save_ipynb()
+ except Exception:
+ wandb.termerror("Failed to save notebook.")
+ logger.exception("Problem saving notebook.")
+ return ret
+
+ def _save_ipynb(self) -> bool:
+ relpath = self.settings.x_jupyter_path
+ logger.info("looking for notebook: %s", relpath)
+ if relpath:
+ if os.path.exists(relpath):
+ shutil.copy(
+ relpath,
+ os.path.join(
+ self.settings._tmp_code_dir, os.path.basename(relpath)
+ ),
+ )
+ return True
+
+ # TODO: likely only save if the code has changed
+ colab_ipynb = attempt_colab_load_ipynb()
+ if colab_ipynb:
+ try:
+ jupyter_metadata = (
+ notebook_metadata_from_jupyter_servers_and_kernel_id()
+ )
+ nb_name = jupyter_metadata["name"]
+ except Exception:
+ nb_name = "colab.ipynb"
+ if not nb_name.endswith(".ipynb"):
+ nb_name += ".ipynb"
+ with open(
+ os.path.join(
+ self.settings._tmp_code_dir,
+ nb_name,
+ ),
+ "w",
+ encoding="utf-8",
+ ) as f:
+ f.write(json.dumps(colab_ipynb))
+ return True
+
+ kaggle_ipynb = attempt_kaggle_load_ipynb()
+ if kaggle_ipynb and len(kaggle_ipynb["cells"]) > 0:
+ with open(
+ os.path.join(
+ self.settings._tmp_code_dir, kaggle_ipynb["metadata"]["name"]
+ ),
+ "w",
+ encoding="utf-8",
+ ) as f:
+ f.write(json.dumps(kaggle_ipynb))
+ return True
+
+ return False
+
+ def save_history(self, run: wandb.Run):
+ """This saves all cell executions in the current session as a new notebook."""
+ try:
+ from nbformat import v4, validator, write # type: ignore
+ except ImportError:
+ wandb.termerror(
+ "The nbformat package was not found."
+ " It is required to save notebook history."
+ )
+ return
+ # TODO: some tests didn't patch ipython properly?
+ if self.shell is None:
+ return
+ cells = []
+ hist = list(self.shell.history_manager.get_range(output=True))
+ if len(hist) <= 1 or not self.settings.save_code:
+ logger.info("not saving jupyter history")
+ return
+ try:
+ for _, execution_count, exc in hist:
+ if exc[1]:
+ # TODO: capture stderr?
+ outputs = [
+ v4.new_output(output_type="stream", name="stdout", text=exc[1])
+ ]
+ else:
+ outputs = []
+ if self.outputs.get(execution_count):
+ for out in self.outputs[execution_count]:
+ outputs.append(
+ v4.new_output(
+ output_type="display_data",
+ data=out["data"],
+ metadata=out["metadata"] or {},
+ )
+ )
+ cells.append(
+ v4.new_code_cell(
+ execution_count=execution_count, source=exc[0], outputs=outputs
+ )
+ )
+ if hasattr(self.shell, "kernel"):
+ language_info = self.shell.kernel.language_info
+ else:
+ language_info = {"name": "python", "version": sys.version}
+ logger.info("saving %i cells to _session_history.ipynb", len(cells))
+ nb = v4.new_notebook(
+ cells=cells,
+ metadata={
+ "kernelspec": {
+ "display_name": f"Python {sys.version_info[0]}",
+ "name": f"python{sys.version_info[0]}",
+ "language": "python",
+ },
+ "language_info": language_info,
+ },
+ )
+ state_path = os.path.join("code", "_session_history.ipynb")
+ run._set_config_wandb("session_history", state_path)
+ filesystem.mkdir_exists_ok(os.path.join(self.settings.files_dir, "code"))
+ with open(
+ os.path.join(self.settings._tmp_code_dir, "_session_history.ipynb"),
+ "w",
+ encoding="utf-8",
+ ) as f:
+ write(nb, f, version=4)
+ with open(
+ os.path.join(self.settings.files_dir, state_path),
+ "w",
+ encoding="utf-8",
+ ) as f:
+ write(nb, f, version=4)
+ except (OSError, validator.NotebookValidationError):
+ wandb.termerror("Unable to save notebook session history.")
+ logger.exception("Unable to save notebook session history.")
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/mpmain/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/mpmain/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/mpmain/__main__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/mpmain/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..02e8a24d9fbce482e31cde126d8407586a61b3fd
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/mpmain/__main__.py
@@ -0,0 +1 @@
+# This module is initialized after multiprocessing spawn
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/old/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/old/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/old/core.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/old/core.py
new file mode 100644
index 0000000000000000000000000000000000000000..15d6d5a410a9a2d843616d09b8cfdc0571b20fc0
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/old/core.py
@@ -0,0 +1,53 @@
+"""Core variables, functions, and classes that we want in the wandb
+module but are also used in modules that import the wandb module.
+
+The purpose of this module is to break circular imports.
+"""
+
+import os
+import tempfile
+import time
+
+import wandb
+from wandb import env
+
+# We use the hidden version if it already exists, otherwise non-hidden.
+if os.path.exists(os.path.join(env.get_dir(os.getcwd()), ".wandb")):
+ __stage_dir__ = ".wandb" + os.sep
+elif os.path.exists(os.path.join(env.get_dir(os.getcwd()), "wandb")):
+ __stage_dir__ = "wandb" + os.sep
+else:
+ __stage_dir__ = None
+
+wandb.START_TIME = time.time()
+
+
+def wandb_dir(root_dir=None):
+ if root_dir is None or root_dir == "":
+ try:
+ cwd = os.getcwd()
+ except OSError:
+ wandb.termwarn("os.getcwd() no longer exists, using system temp directory")
+ cwd = tempfile.gettempdir()
+ root_dir = env.get_dir(cwd)
+ path = os.path.join(root_dir, __stage_dir__ or ("wandb" + os.sep))
+ if not os.access(root_dir, os.W_OK):
+ wandb.termwarn(
+ f"Path {path} wasn't writable, using system temp directory", repeat=False
+ )
+ path = os.path.join(tempfile.gettempdir(), __stage_dir__ or ("wandb" + os.sep))
+ return path
+
+
+def _set_stage_dir(stage_dir):
+ # Used when initing a new project with "wandb init"
+ global __stage_dir__
+ __stage_dir__ = stage_dir
+
+
+__all__ = [
+ "__stage_dir__",
+ "START_TIME",
+ "wandb_dir",
+ "_set_stage_dir",
+]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/old/settings.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/old/settings.py
new file mode 100644
index 0000000000000000000000000000000000000000..b759447aefb7699f14b77604305a9e46ae883065
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/old/settings.py
@@ -0,0 +1,176 @@
+import configparser
+import getpass
+import os
+import tempfile
+from typing import Any, Optional
+
+from wandb import env
+from wandb.old import core
+from wandb.sdk.lib import filesystem
+from wandb.sdk.lib.runid import generate_id
+
+
+class Settings:
+ """Global W&B settings stored under $WANDB_CONFIG_DIR/settings."""
+
+ DEFAULT_SECTION = "default"
+
+ _UNSET = object()
+
+ def __init__(
+ self, load_settings: bool = True, root_dir: Optional[str] = None
+ ) -> None:
+ self._global_settings = Settings._settings()
+ self._local_settings = Settings._settings()
+ self.root_dir = root_dir
+
+ if load_settings:
+ global_path = Settings._global_path()
+ if global_path is not None:
+ self._global_settings.read([global_path])
+ # Only attempt to read if there is a directory existing
+ if os.path.isdir(core.wandb_dir(self.root_dir)):
+ self._local_settings.read([Settings._local_path(self.root_dir)])
+
+ def get(self, section: str, key: str, fallback: Any = _UNSET) -> Any:
+ # Try the local settings first. If we can't find the key, then try the global settings.
+ # If a fallback is provided, return it if we can't find the key in either the local or global
+ # settings.
+ try:
+ return self._local_settings.get(section, key)
+ except configparser.NoOptionError:
+ try:
+ return self._global_settings.get(section, key)
+ except configparser.NoOptionError:
+ if fallback is not Settings._UNSET:
+ return fallback
+ else:
+ raise
+
+ def _persist_settings(self, settings, settings_path) -> None:
+ # write a temp file and then move it to the settings path
+ target_dir = os.path.dirname(settings_path)
+ with tempfile.NamedTemporaryFile(
+ "w+", suffix=".tmp", delete=False, dir=target_dir
+ ) as fp:
+ path = os.path.abspath(fp.name)
+ with open(path, "w+") as f:
+ settings.write(f)
+ try:
+ os.replace(path, settings_path)
+ except AttributeError:
+ os.rename(path, settings_path)
+
+ def set(self, section, key, value, globally=False, persist=False) -> None:
+ """Persist settings to disk if persist = True"""
+
+ def write_setting(settings, settings_path, persist):
+ if not settings.has_section(section):
+ Settings._safe_add_section(settings, Settings.DEFAULT_SECTION)
+ settings.set(section, key, str(value))
+
+ if persist:
+ self._persist_settings(settings, settings_path)
+
+ if globally:
+ global_path = Settings._global_path()
+ if global_path is not None:
+ write_setting(self._global_settings, global_path, persist)
+ else:
+ write_setting(
+ self._local_settings, Settings._local_path(self.root_dir), persist
+ )
+
+ def clear(self, section, key, globally=False, persist=False) -> None:
+ def clear_setting(settings, settings_path, persist):
+ settings.remove_option(section, key)
+ if persist:
+ self._persist_settings(settings, settings_path)
+
+ if globally:
+ global_path = Settings._global_path()
+ if global_path is not None:
+ clear_setting(self._global_settings, global_path, persist)
+ else:
+ clear_setting(
+ self._local_settings, Settings._local_path(self.root_dir), persist
+ )
+
+ def items(self, section=None):
+ section = section if section is not None else Settings.DEFAULT_SECTION
+
+ result = {"section": section}
+
+ try:
+ if section in self._global_settings.sections():
+ for option in self._global_settings.options(section):
+ result[option] = self._global_settings.get(section, option)
+ if section in self._local_settings.sections():
+ for option in self._local_settings.options(section):
+ result[option] = self._local_settings.get(section, option)
+ except configparser.InterpolationSyntaxError:
+ core.termwarn("Unable to parse settings file")
+
+ return result
+
+ @staticmethod
+ def _safe_add_section(settings, section):
+ if not settings.has_section(section):
+ settings.add_section(section)
+
+ @staticmethod
+ def _settings(default_settings={}):
+ settings = configparser.ConfigParser()
+ Settings._safe_add_section(settings, Settings.DEFAULT_SECTION)
+ for key, value in default_settings.items():
+ settings.set(Settings.DEFAULT_SECTION, key, str(value))
+ return settings
+
+ @staticmethod
+ def _global_path() -> Optional[str]:
+ def try_create_dir(path) -> bool:
+ try:
+ os.makedirs(path, exist_ok=True)
+ if os.access(path, os.W_OK):
+ return True
+ except OSError:
+ pass
+ return False
+
+ def get_username() -> str:
+ try:
+ return getpass.getuser()
+ except (ImportError, KeyError):
+ return generate_id()
+
+ try:
+ home_config_dir = os.path.join(os.path.expanduser("~"), ".config", "wandb")
+
+ if os.getenv(env.CONFIG_DIR):
+ try_create_dir(os.getenv(env.CONFIG_DIR))
+ return os.path.join(os.getenv(env.CONFIG_DIR), "settings")
+
+ if not try_create_dir(home_config_dir):
+ temp_config_dir = os.path.join(
+ tempfile.gettempdir(), ".config", "wandb"
+ )
+
+ if not try_create_dir(temp_config_dir):
+ username = get_username()
+ config_dir = os.path.join(
+ tempfile.gettempdir(), username, ".config", "wandb"
+ )
+ try_create_dir(config_dir)
+ else:
+ config_dir = temp_config_dir
+ else:
+ config_dir = home_config_dir
+
+ return os.path.join(config_dir, "settings")
+ except Exception:
+ return None
+
+ @staticmethod
+ def _local_path(root_dir=None):
+ filesystem.mkdir_exists_ok(core.wandb_dir(root_dir))
+ return os.path.join(core.wandb_dir(root_dir), "settings")
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/old/summary.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/old/summary.py
new file mode 100644
index 0000000000000000000000000000000000000000..aad894c30bc338afcd94e1b717f82ea0028fe91d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/old/summary.py
@@ -0,0 +1,438 @@
+import json
+import os
+import time
+
+from wandb_gql import gql
+
+import wandb
+from wandb import util
+from wandb.apis.internal import Api
+from wandb.sdk import lib as wandb_lib
+from wandb.sdk.data_types.utils import val_to_json
+
+DEEP_SUMMARY_FNAME = "wandb.h5"
+H5_TYPES = ("numpy.ndarray", "tensorflow.Tensor", "torch.Tensor")
+h5py = util.get_module("h5py")
+np = util.get_module("numpy")
+
+
+class SummarySubDict:
+ """Nested dict-like object that proxies read and write operations through a root object.
+
+ This lets us do synchronous serialization and lazy loading of large values.
+ """
+
+ def __init__(self, root=None, path=()):
+ self._path = tuple(path)
+ if root is None:
+ self._root = self
+ self._json_dict = {}
+ else:
+ self._root = root
+ json_dict = root._json_dict
+ for k in path:
+ json_dict = json_dict.get(k, {})
+
+ self._json_dict = json_dict
+ self._dict = {}
+
+ # We use this to track which keys the user has set explicitly
+ # so that we don't automatically overwrite them when we update
+ # the summary from the history.
+ self._locked_keys = set()
+
+ def __setattr__(self, k, v):
+ k = k.strip()
+ if k.startswith("_"):
+ object.__setattr__(self, k, v)
+ else:
+ self[k] = v
+
+ def __getattr__(self, k):
+ k = k.strip()
+ if k.startswith("_"):
+ return object.__getattribute__(self, k)
+ else:
+ return self[k]
+
+ def _root_get(self, path, child_dict):
+ """Load a value at a particular path from the root.
+
+ This should only be implemented by the "_root" child class.
+
+ We pass the child_dict so the item can be set on it or not as
+ appropriate. Returning None for a nonexistent path wouldn't be
+ distinguishable from that path being set to the value None.
+ """
+ raise NotImplementedError
+
+ def _root_set(self, path, new_keys_values):
+ """Set a value at a particular path in the root.
+
+ This should only be implemented by the "_root" child class.
+ """
+ raise NotImplementedError
+
+ def _root_del(self, path):
+ """Delete a value at a particular path in the root.
+
+ This should only be implemented by the "_root" child class.
+ """
+ raise NotImplementedError
+
+ def _write(self, commit=False):
+ # should only be implemented on the root summary
+ raise NotImplementedError
+
+ def keys(self):
+ # _json_dict has the full set of keys, including those for h5 objects
+ # that may not have been loaded yet
+ return self._json_dict.keys()
+
+ def get(self, k, default=None):
+ if isinstance(k, str):
+ k = k.strip()
+ if k not in self._dict:
+ self._root._root_get(self._path + (k,), self._dict)
+ return self._dict.get(k, default)
+
+ def items(self):
+ # not all items may be loaded into self._dict, so we
+ # have to build the sequence of items from scratch
+ for k in self.keys():
+ yield k, self[k]
+
+ def __getitem__(self, k):
+ if isinstance(k, str):
+ k = k.strip()
+
+ self.get(k) # load the value into _dict if it should be there
+ res = self._dict[k]
+
+ return res
+
+ def __contains__(self, k):
+ if isinstance(k, str):
+ k = k.strip()
+
+ return k in self._json_dict
+
+ def __setitem__(self, k, v):
+ if isinstance(k, str):
+ k = k.strip()
+
+ path = self._path
+
+ if isinstance(v, dict):
+ self._dict[k] = SummarySubDict(self._root, path + (k,))
+ self._root._root_set(path, [(k, {})])
+ self._dict[k].update(v)
+ else:
+ self._dict[k] = v
+ self._root._root_set(path, [(k, v)])
+
+ self._locked_keys.add(k)
+
+ self._root._write()
+
+ return v
+
+ def __delitem__(self, k):
+ k = k.strip()
+ del self._dict[k]
+ self._root._root_del(self._path + (k,))
+
+ self._root._write()
+
+ def __repr__(self):
+ # use a copy of _dict, except add placeholders for h5 objects, etc.
+ # that haven't been loaded yet
+ repr_dict = dict(self._dict)
+ for k in self._json_dict:
+ v = self._json_dict[k]
+ if (
+ k not in repr_dict
+ and isinstance(v, dict)
+ and v.get("_type") in H5_TYPES
+ ):
+ # unloaded h5 objects may be very large. use a placeholder for them
+ # if we haven't already loaded them
+ repr_dict[k] = "..."
+ else:
+ repr_dict[k] = self[k]
+
+ return repr(repr_dict)
+
+ def update(self, key_vals=None, overwrite=True):
+ """Locked keys will be overwritten unless overwrite=False.
+
+ Otherwise, written keys will be added to the "locked" list.
+ """
+ if key_vals:
+ write_items = self._update(key_vals, overwrite)
+ self._root._root_set(self._path, write_items)
+ self._root._write(commit=True)
+
+ def _update(self, key_vals, overwrite):
+ if not key_vals:
+ return
+ key_vals = {k.strip(): v for k, v in key_vals.items()}
+ if overwrite:
+ write_items = list(key_vals.items())
+ self._locked_keys.update(key_vals.keys())
+ else:
+ write_keys = set(key_vals.keys()) - self._locked_keys
+ write_items = [(k, key_vals[k]) for k in write_keys]
+
+ for key, value in write_items:
+ if isinstance(value, dict):
+ self._dict[key] = SummarySubDict(self._root, self._path + (key,))
+ self._dict[key]._update(value, overwrite)
+ else:
+ self._dict[key] = value
+
+ return write_items
+
+
+class Summary(SummarySubDict):
+ """Store summary metrics (eg. accuracy) during and after a run.
+
+ You can manipulate this as if it's a Python dictionary but the keys
+ get mangled. .strip() is called on them, so spaces at the beginning
+ and end are removed.
+ """
+
+ def __init__(self, run, summary=None):
+ super().__init__()
+ self._run = run
+ self._h5_path = os.path.join(self._run.dir, DEEP_SUMMARY_FNAME)
+ # Lazy load the h5 file
+ self._h5 = None
+
+ # Mirrored version of self._dict with versions of values that get written
+ # to JSON kept up to date by self._root_set() and self._root_del().
+ self._json_dict = {}
+
+ if summary is not None:
+ self._json_dict = summary
+
+ def _json_get(self, path):
+ pass
+
+ def _root_get(self, path, child_dict):
+ json_dict = self._json_dict
+ for key in path[:-1]:
+ json_dict = json_dict[key]
+
+ key = path[-1]
+ if key in json_dict:
+ child_dict[key] = self._decode(path, json_dict[key])
+
+ def _root_del(self, path):
+ json_dict = self._json_dict
+ for key in path[:-1]:
+ json_dict = json_dict[key]
+
+ val = json_dict[path[-1]]
+ del json_dict[path[-1]]
+ if isinstance(val, dict) and val.get("_type") in H5_TYPES:
+ if not h5py:
+ wandb.termerror("Deleting tensors in summary requires h5py")
+ else:
+ self.open_h5()
+ h5_key = "summary/" + ".".join(path)
+ del self._h5[h5_key]
+ self._h5.flush()
+
+ def _root_set(self, path, new_keys_values):
+ json_dict = self._json_dict
+ for key in path:
+ json_dict = json_dict[key]
+
+ for new_key, new_value in new_keys_values:
+ json_dict[new_key] = self._encode(new_value, path + (new_key,))
+
+ def write_h5(self, path, val):
+ # ensure the file is open
+ self.open_h5()
+
+ if not self._h5:
+ wandb.termerror("Storing tensors in summary requires h5py")
+ else:
+ try:
+ del self._h5["summary/" + ".".join(path)]
+ except KeyError:
+ pass
+ self._h5["summary/" + ".".join(path)] = val
+ self._h5.flush()
+
+ def read_h5(self, path, val=None):
+ # ensure the file is open
+ self.open_h5()
+
+ if not self._h5:
+ wandb.termerror("Reading tensors from summary requires h5py")
+ else:
+ return self._h5.get("summary/" + ".".join(path), val)
+
+ def open_h5(self):
+ if not self._h5 and h5py:
+ self._h5 = h5py.File(self._h5_path, "a", libver="latest")
+
+ def _decode(self, path, json_value):
+ """Decode a `dict` encoded by `Summary._encode()`, loading h5 objects.
+
+ h5 objects may be very large, so we won't have loaded them automatically.
+ """
+ if isinstance(json_value, dict):
+ if json_value.get("_type") in H5_TYPES:
+ return self.read_h5(path, json_value)
+ elif json_value.get("_type") == "data-frame":
+ wandb.termerror(
+ "This data frame was saved via the wandb data API. Contact support@wandb.com for help."
+ )
+ return None
+ # TODO: transform wandb objects and plots
+ else:
+ return SummarySubDict(self, path)
+ else:
+ return json_value
+
+ def _encode(self, value, path_from_root):
+ """Normalize, compress, and encode sub-objects for backend storage.
+
+ value: Object to encode.
+ path_from_root: `tuple` of key strings from the top-level summary to the
+ current `value`.
+
+ Returns:
+ A new tree of dict's with large objects replaced with dictionaries
+ with "_type" entries that say which type the original data was.
+ """
+
+ # Constructs a new `dict` tree in `json_value` that discards and/or
+ # encodes objects that aren't JSON serializable.
+
+ if isinstance(value, dict):
+ json_value = {}
+ for key, value in value.items():
+ json_value[key] = self._encode(value, path_from_root + (key,))
+ return json_value
+ else:
+ path = ".".join(path_from_root)
+ friendly_value, converted = util.json_friendly(
+ val_to_json(self._run, path, value, namespace="summary")
+ )
+ json_value, compressed = util.maybe_compress_summary(
+ friendly_value, util.get_h5_typename(value)
+ )
+ if compressed:
+ self.write_h5(path_from_root, friendly_value)
+
+ return json_value
+
+
+def download_h5(run_id, entity=None, project=None, out_dir=None):
+ api = Api()
+ meta = api.download_url(
+ project or api.settings("project"),
+ DEEP_SUMMARY_FNAME,
+ entity=entity or api.settings("entity"),
+ run=run_id,
+ )
+ if meta and "md5" in meta and meta["md5"] is not None:
+ # TODO: make this non-blocking
+ wandb.termlog("Downloading summary data...")
+ path, res = api.download_write_file(meta, out_dir=out_dir)
+ return path
+
+
+def upload_h5(file, run_id, entity=None, project=None):
+ api = Api()
+ wandb.termlog("Uploading summary data...")
+ with open(file, "rb") as f:
+ api.push(
+ {os.path.basename(file): f}, run=run_id, project=project, entity=entity
+ )
+
+
+class FileSummary(Summary):
+ def __init__(self, run):
+ super().__init__(run)
+ self._fname = os.path.join(run.dir, wandb_lib.filenames.SUMMARY_FNAME)
+ self.load()
+
+ def load(self):
+ try:
+ with open(self._fname) as f:
+ self._json_dict = json.load(f)
+ except (OSError, ValueError):
+ self._json_dict = {}
+
+ def _write(self, commit=False):
+ # TODO: we just ignore commit to ensure backward capability
+ with open(self._fname, "w") as f:
+ f.write(util.json_dumps_safer(self._json_dict))
+ f.write("\n")
+ f.flush()
+ os.fsync(f.fileno())
+ if self._h5:
+ self._h5.close()
+ self._h5 = None
+
+
+class HTTPSummary(Summary):
+ def __init__(self, run, client, summary=None):
+ super().__init__(run, summary=summary)
+ self._run = run
+ self._client = client
+ self._started = time.time()
+
+ def __delitem__(self, key):
+ if key not in self._json_dict:
+ raise KeyError(key)
+ del self._json_dict[key]
+
+ def load(self):
+ pass
+
+ def open_h5(self):
+ if not self._h5 and h5py:
+ download_h5(
+ self._run.id,
+ entity=self._run.entity,
+ project=self._run.project,
+ out_dir=self._run.dir,
+ )
+ super().open_h5()
+
+ def _write(self, commit=False):
+ mutation = gql(
+ """
+ mutation UpsertBucket( $id: String, $summaryMetrics: JSONString) {
+ upsertBucket(input: { id: $id, summaryMetrics: $summaryMetrics}) {
+ bucket { id }
+ }
+ }
+ """
+ )
+ if commit:
+ if self._h5:
+ self._h5.close()
+ self._h5 = None
+ res = self._client.execute(
+ mutation,
+ variable_values={
+ "id": self._run.storage_id,
+ "summaryMetrics": util.json_dumps_safer(self._json_dict),
+ },
+ )
+ assert res["upsertBucket"]["bucket"]["id"]
+ entity, project, run = self._run.path
+ if (
+ os.path.exists(self._h5_path)
+ and os.path.getmtime(self._h5_path) >= self._started
+ ):
+ upload_h5(self._h5_path, run, entity=entity, project=project)
+ else:
+ return False
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c49e40ac3ce6a7ffccd97c553a013bdd97fd305b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/__init__.py
@@ -0,0 +1,30 @@
+"""Chart Visualization Utilities
+
+This module offers a collection of predefined chart types, along with functionality
+for creating custom charts, enabling flexible visualization of your data beyond the
+built-in options.
+"""
+
+__all__ = [
+ "line",
+ "histogram",
+ "scatter",
+ "bar",
+ "roc_curve",
+ "pr_curve",
+ "confusion_matrix",
+ "line_series",
+ "plot_table",
+ "visualize", # doc:exclude
+]
+
+from wandb.plot.bar import bar
+from wandb.plot.confusion_matrix import confusion_matrix
+from wandb.plot.custom_chart import CustomChart, plot_table
+from wandb.plot.histogram import histogram
+from wandb.plot.line import line
+from wandb.plot.line_series import line_series
+from wandb.plot.pr_curve import pr_curve
+from wandb.plot.roc_curve import roc_curve
+from wandb.plot.scatter import scatter
+from wandb.plot.viz import Visualize, visualize
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/bar.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/bar.py
new file mode 100644
index 0000000000000000000000000000000000000000..21e6496df9e46a00204b78abb4c599ca0430a3c1
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/bar.py
@@ -0,0 +1,71 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from wandb.plot.custom_chart import plot_table
+
+if TYPE_CHECKING:
+ import wandb
+ from wandb.plot.custom_chart import CustomChart
+
+
+def bar(
+ table: wandb.Table,
+ label: str,
+ value: str,
+ title: str = "",
+ split_table: bool = False,
+) -> CustomChart:
+ """Constructs a bar chart from a wandb.Table of data.
+
+ Args:
+ table: A table containing the data for the bar chart.
+ label: The name of the column to use for the labels of each bar.
+ value: The name of the column to use for the values of each bar.
+ title: The title of the bar chart.
+ split_table: Whether the table should be split into a separate section
+ in the W&B UI. If `True`, the table will be displayed in a section named
+ "Custom Chart Tables". Default is `False`.
+
+ Returns:
+ CustomChart: A custom chart object that can be logged to W&B. To log the
+ chart, pass it to `wandb.log()`.
+
+ Example:
+
+ ```python
+ import random
+ import wandb
+
+ # Generate random data for the table
+ data = [
+ ["car", random.uniform(0, 1)],
+ ["bus", random.uniform(0, 1)],
+ ["road", random.uniform(0, 1)],
+ ["person", random.uniform(0, 1)],
+ ]
+
+ # Create a table with the data
+ table = wandb.Table(data=data, columns=["class", "accuracy"])
+
+ # Initialize a W&B run and log the bar plot
+ with wandb.init(project="bar_chart") as run:
+ # Create a bar plot from the table
+ bar_plot = wandb.plot.bar(
+ table=table,
+ label="class",
+ value="accuracy",
+ title="Object Classification Accuracy",
+ )
+
+ # Log the bar chart to W&B
+ run.log({"bar_plot": bar_plot})
+ ```
+ """
+ return plot_table(
+ data_table=table,
+ vega_spec_name="wandb/bar/v0",
+ fields={"label": label, "value": value},
+ string_fields={"title": title},
+ split_table=split_table,
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/confusion_matrix.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/confusion_matrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..a469632fd9efe8a8fa2e2d17a0d46ddbbfbc9736
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/confusion_matrix.py
@@ -0,0 +1,185 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Sequence, TypeVar
+
+import wandb
+from wandb import util
+from wandb.plot.custom_chart import plot_table
+
+if TYPE_CHECKING:
+ from wandb.plot.custom_chart import CustomChart
+
+T = TypeVar("T")
+
+
+def confusion_matrix(
+ probs: Sequence[Sequence[float]] | None = None,
+ y_true: Sequence[T] | None = None,
+ preds: Sequence[T] | None = None,
+ class_names: Sequence[str] | None = None,
+ title: str = "Confusion Matrix Curve",
+ split_table: bool = False,
+) -> CustomChart:
+ """Constructs a confusion matrix from a sequence of probabilities or predictions.
+
+ Args:
+ probs: A sequence of predicted probabilities for each
+ class. The sequence shape should be (N, K) where N is the number of samples
+ and K is the number of classes. If provided, `preds` should not be provided.
+ y_true: A sequence of true labels.
+ preds: A sequence of predicted class labels. If provided,
+ `probs` should not be provided.
+ class_names: Sequence of class names. If not
+ provided, class names will be defined as "Class_1", "Class_2", etc.
+ title: Title of the confusion matrix chart.
+ split_table: Whether the table should be split into a separate section
+ in the W&B UI. If `True`, the table will be displayed in a section named
+ "Custom Chart Tables". Default is `False`.
+
+ Returns:
+ CustomChart: A custom chart object that can be logged to W&B. To log the
+ chart, pass it to `wandb.log()`.
+
+ Raises:
+ ValueError: If both `probs` and `preds` are provided or if the number of
+ predictions and true labels are not equal. If the number of unique
+ predicted classes exceeds the number of class names or if the number of
+ unique true labels exceeds the number of class names.
+ wandb.Error: If numpy is not installed.
+
+ Examples:
+ Logging a confusion matrix with random probabilities for wildlife
+ classification:
+
+ ```python
+ import numpy as np
+ import wandb
+
+ # Define class names for wildlife
+ wildlife_class_names = ["Lion", "Tiger", "Elephant", "Zebra"]
+
+ # Generate random true labels (0 to 3 for 10 samples)
+ wildlife_y_true = np.random.randint(0, 4, size=10)
+
+ # Generate random probabilities for each class (10 samples x 4 classes)
+ wildlife_probs = np.random.rand(10, 4)
+ wildlife_probs = np.exp(wildlife_probs) / np.sum(
+ np.exp(wildlife_probs),
+ axis=1,
+ keepdims=True,
+ )
+
+ # Initialize W&B run and log confusion matrix
+ with wandb.init(project="wildlife_classification") as run:
+ confusion_matrix = wandb.plot.confusion_matrix(
+ probs=wildlife_probs,
+ y_true=wildlife_y_true,
+ class_names=wildlife_class_names,
+ title="Wildlife Classification Confusion Matrix",
+ )
+ run.log({"wildlife_confusion_matrix": confusion_matrix})
+ ```
+
+ In this example, random probabilities are used to generate a confusion
+ matrix.
+
+ Logging a confusion matrix with simulated model predictions and 85%
+ accuracy:
+
+ ```python
+ import numpy as np
+ import wandb
+
+ # Define class names for wildlife
+ wildlife_class_names = ["Lion", "Tiger", "Elephant", "Zebra"]
+
+ # Simulate true labels for 200 animal images (imbalanced distribution)
+ wildlife_y_true = np.random.choice(
+ [0, 1, 2, 3],
+ size=200,
+ p=[0.2, 0.3, 0.25, 0.25],
+ )
+
+ # Simulate model predictions with 85% accuracy
+ wildlife_preds = [
+ y_t
+ if np.random.rand() < 0.85
+ else np.random.choice([x for x in range(4) if x != y_t])
+ for y_t in wildlife_y_true
+ ]
+
+ # Initialize W&B run and log confusion matrix
+ with wandb.init(project="wildlife_classification") as run:
+ confusion_matrix = wandb.plot.confusion_matrix(
+ preds=wildlife_preds,
+ y_true=wildlife_y_true,
+ class_names=wildlife_class_names,
+ title="Simulated Wildlife Classification Confusion Matrix",
+ )
+ run.log({"wildlife_confusion_matrix": confusion_matrix})
+ ```
+
+ In this example, predictions are simulated with 85% accuracy to generate a
+ confusion matrix.
+ """
+ np = util.get_module(
+ "numpy",
+ required=(
+ "numpy is required to use wandb.plot.confusion_matrix, "
+ "install with `pip install numpy`",
+ ),
+ )
+
+ if probs is not None and preds is not None:
+ raise ValueError("Only one of `probs` or `preds` should be provided, not both.")
+
+ if probs is not None:
+ preds = np.argmax(probs, axis=1).tolist()
+
+ if len(preds) != len(y_true):
+ raise ValueError("The number of predictions and true labels must be equal.")
+
+ if class_names is not None:
+ n_classes = len(class_names)
+ class_idx = list(range(n_classes))
+ if len(set(preds)) > len(class_names):
+ raise ValueError(
+ "The number of unique predicted classes exceeds the number of class names."
+ )
+
+ if len(set(y_true)) > len(class_names):
+ raise ValueError(
+ "The number of unique true labels exceeds the number of class names."
+ )
+ else:
+ class_idx = set(preds).union(set(y_true))
+ n_classes = len(class_idx)
+ class_names = [f"Class_{i + 1}" for i in range(n_classes)]
+
+ # Create a mapping from class name to index
+ class_mapping = {val: i for i, val in enumerate(sorted(list(class_idx)))}
+
+ counts = np.zeros((n_classes, n_classes))
+ for i in range(len(preds)):
+ counts[class_mapping[y_true[i]], class_mapping[preds[i]]] += 1
+
+ data = [
+ [class_names[i], class_names[j], counts[i, j]]
+ for i in range(n_classes)
+ for j in range(n_classes)
+ ]
+
+ return plot_table(
+ data_table=wandb.Table(
+ columns=["Actual", "Predicted", "nPredictions"],
+ data=data,
+ ),
+ vega_spec_name="wandb/confusion_matrix/v1",
+ fields={
+ "Actual": "Actual",
+ "Predicted": "Predicted",
+ "nPredictions": "nPredictions",
+ },
+ string_fields={"title": title},
+ split_table=split_table,
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/custom_chart.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/custom_chart.py
new file mode 100644
index 0000000000000000000000000000000000000000..62cd8784cdc63b2af264cd51ae7ebb80e7bddbbc
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/custom_chart.py
@@ -0,0 +1,147 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
+import wandb
+
+
+@dataclass
+class CustomChartSpec:
+ spec_name: str
+ fields: dict[str, Any]
+ string_fields: dict[str, Any]
+ key: str = ""
+ panel_type: str = "Vega2"
+ split_table: bool = False
+
+ @property
+ def table_key(self) -> str:
+ if not self.key:
+ raise wandb.Error("Key for the custom chart spec is not set.")
+ if self.split_table:
+ return f"Custom Chart Tables/{self.key}_table"
+ return f"{self.key}_table"
+
+ @property
+ def config_value(self) -> dict[str, Any]:
+ return {
+ "panel_type": self.panel_type,
+ "panel_config": {
+ "panelDefId": self.spec_name,
+ "fieldSettings": self.fields,
+ "stringSettings": self.string_fields,
+ "transform": {"name": "tableWithLeafColNames"},
+ "userQuery": {
+ "queryFields": [
+ {
+ "name": "runSets",
+ "args": [{"name": "runSets", "value": "${runSets}"}],
+ "fields": [
+ {"name": "id", "fields": []},
+ {"name": "name", "fields": []},
+ {"name": "_defaultColorIndex", "fields": []},
+ {
+ "name": "summaryTable",
+ "args": [
+ {
+ "name": "tableKey",
+ "value": self.table_key,
+ }
+ ],
+ "fields": [],
+ },
+ ],
+ }
+ ],
+ },
+ },
+ }
+
+ @property
+ def config_key(self) -> tuple[str, str, str]:
+ return ("_wandb", "visualize", self.key)
+
+
+@dataclass
+class CustomChart:
+ table: wandb.Table
+ spec: CustomChartSpec
+
+ def set_key(self, key: str):
+ """Sets the key for the spec and updates dependent configurations."""
+ self.spec.key = key
+
+
+def plot_table(
+ vega_spec_name: str,
+ data_table: wandb.Table,
+ fields: dict[str, Any],
+ string_fields: dict[str, Any] | None = None,
+ split_table: bool = False,
+) -> CustomChart:
+ """Creates a custom charts using a Vega-Lite specification and a `wandb.Table`.
+
+ This function creates a custom chart based on a Vega-Lite specification and
+ a data table represented by a `wandb.Table` object. The specification needs
+ to be predefined and stored in the W&B backend. The function returns a custom
+ chart object that can be logged to W&B using `wandb.Run.log()`.
+
+ Args:
+ vega_spec_name: The name or identifier of the Vega-Lite spec
+ that defines the visualization structure.
+ data_table: A `wandb.Table` object containing the data to be
+ visualized.
+ fields: A mapping between the fields in the Vega-Lite spec and the
+ corresponding columns in the data table to be visualized.
+ string_fields: A dictionary for providing values for any string constants
+ required by the custom visualization.
+ split_table: Whether the table should be split into a separate section
+ in the W&B UI. If `True`, the table will be displayed in a section named
+ "Custom Chart Tables". Default is `False`.
+
+ Returns:
+ CustomChart: A custom chart object that can be logged to W&B. To log the
+ chart, pass the chart object as argument to `wandb.Run.log()`.
+
+ Raises:
+ wandb.Error: If `data_table` is not a `wandb.Table` object.
+
+ Example:
+ ```python
+ # Create a custom chart using a Vega-Lite spec and the data table.
+ import wandb
+
+ data = [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]]
+ table = wandb.Table(data=data, columns=["x", "y"])
+ fields = {"x": "x", "y": "y", "title": "MY TITLE"}
+
+ with wandb.init() as run:
+ # Training code goes here
+
+ # Create a custom title with `string_fields`.
+ my_custom_chart = wandb.plot_table(
+ vega_spec_name="wandb/line/v0",
+ data_table=table,
+ fields=fields,
+ string_fields={"title": "Title"},
+ )
+
+ run.log({"custom_chart": my_custom_chart})
+ ```
+ """
+
+ if not isinstance(data_table, wandb.Table):
+ raise wandb.Error(
+ f"Expected `data_table` to be `wandb.Table` type, instead got {type(data_table).__name__}"
+ )
+
+ return CustomChart(
+ table=data_table,
+ spec=CustomChartSpec(
+ spec_name=vega_spec_name,
+ fields=fields,
+ string_fields=string_fields or {},
+ split_table=split_table,
+ ),
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/histogram.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/histogram.py
new file mode 100644
index 0000000000000000000000000000000000000000..b62cb1142d94cbe59101d6ded8cc6a523c05d769
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/histogram.py
@@ -0,0 +1,66 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from wandb.plot.custom_chart import plot_table
+
+if TYPE_CHECKING:
+ import wandb
+ from wandb.plot.custom_chart import CustomChart
+
+
+def histogram(
+ table: wandb.Table,
+ value: str,
+ title: str = "",
+ split_table: bool = False,
+) -> CustomChart:
+ """Constructs a histogram chart from a W&B Table.
+
+ Args:
+ table: The W&B Table containing the data for the histogram.
+ value: The label for the bin axis (x-axis).
+ title: The title of the histogram plot.
+ split_table: Whether the table should be split into a separate section
+ in the W&B UI. If `True`, the table will be displayed in a section named
+ "Custom Chart Tables". Default is `False`.
+
+ Returns:
+ CustomChart: A custom chart object that can be logged to W&B. To log the
+ chart, pass it to `wandb.log()`.
+
+ Example:
+
+ ```python
+ import math
+ import random
+ import wandb
+
+ # Generate random data
+ data = [[i, random.random() + math.sin(i / 10)] for i in range(100)]
+
+ # Create a W&B Table
+ table = wandb.Table(
+ data=data,
+ columns=["step", "height"],
+ )
+
+ # Create a histogram plot
+ histogram = wandb.plot.histogram(
+ table,
+ value="height",
+ title="My Histogram",
+ )
+
+ # Log the histogram plot to W&B
+ with wandb.init(...) as run:
+ run.log({"histogram-plot1": histogram})
+ ```
+ """
+ return plot_table(
+ data_table=table,
+ vega_spec_name="wandb/histogram/v0",
+ fields={"value": value},
+ string_fields={"title": title},
+ split_table=split_table,
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/line.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/line.py
new file mode 100644
index 0000000000000000000000000000000000000000..34857a4053ac3d699f447f927b7d6d0ea8d6ca14
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/line.py
@@ -0,0 +1,75 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from wandb.plot.custom_chart import plot_table
+
+if TYPE_CHECKING:
+ import wandb
+ from wandb.plot.custom_chart import CustomChart
+
+
+def line(
+ table: wandb.Table,
+ x: str,
+ y: str,
+ stroke: str | None = None,
+ title: str = "",
+ split_table: bool = False,
+) -> CustomChart:
+ """Constructs a customizable line chart.
+
+ Args:
+ table: The table containing data for the chart.
+ x: Column name for the x-axis values.
+ y: Column name for the y-axis values.
+ stroke: Column name to differentiate line strokes (e.g., for
+ grouping lines).
+ title: Title of the chart.
+ split_table: Whether the table should be split into a separate section
+ in the W&B UI. If `True`, the table will be displayed in a section named
+ "Custom Chart Tables". Default is `False`.
+
+ Returns:
+ CustomChart: A custom chart object that can be logged to W&B. To log the
+ chart, pass it to `wandb.log()`.
+
+ Example:
+
+ ```python
+ import math
+ import random
+ import wandb
+
+ # Create multiple series of data with different patterns
+ data = []
+ for i in range(100):
+ # Series 1: Sinusoidal pattern with random noise
+ data.append([i, math.sin(i / 10) + random.uniform(-0.1, 0.1), "series_1"])
+ # Series 2: Cosine pattern with random noise
+ data.append([i, math.cos(i / 10) + random.uniform(-0.1, 0.1), "series_2"])
+ # Series 3: Linear increase with random noise
+ data.append([i, i / 10 + random.uniform(-0.5, 0.5), "series_3"])
+
+ # Define the columns for the table
+ table = wandb.Table(data=data, columns=["step", "value", "series"])
+
+ # Initialize wandb run and log the line chart
+ with wandb.init(project="line_chart_example") as run:
+ line_chart = wandb.plot.line(
+ table=table,
+ x="step",
+ y="value",
+ stroke="series", # Group by the "series" column
+ title="Multi-Series Line Plot",
+ )
+ run.log({"line-chart": line_chart})
+ ```
+ """
+ return plot_table(
+ data_table=table,
+ vega_spec_name="wandb/line/v0",
+ fields={"x": x, "y": y, "stroke": stroke},
+ string_fields={"title": title},
+ split_table=split_table,
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/line_series.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/line_series.py
new file mode 100644
index 0000000000000000000000000000000000000000..de43caa5495d4699d900521497498bd9cdfce259
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/line_series.py
@@ -0,0 +1,173 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Iterable
+
+import wandb
+from wandb.plot.custom_chart import plot_table
+
+if TYPE_CHECKING:
+ from wandb.plot.custom_chart import CustomChart
+
+
+def line_series(
+ xs: Iterable[Iterable[Any]] | Iterable[Any],
+ ys: Iterable[Iterable[Any]],
+ keys: Iterable[str] | None = None,
+ title: str = "",
+ xname: str = "x",
+ split_table: bool = False,
+) -> CustomChart:
+ """Constructs a line series chart.
+
+ Args:
+ xs: Sequence of x values. If a singular
+ array is provided, all y values are plotted against that x array. If
+ an array of arrays is provided, each y value is plotted against the
+ corresponding x array.
+ ys: Sequence of y values, where each iterable represents
+ a separate line series.
+ keys: Sequence of keys for labeling each line series. If
+ not provided, keys will be automatically generated as "line_1",
+ "line_2", etc.
+ title: Title of the chart.
+ xname: Label for the x-axis.
+ split_table: Whether the table should be split into a separate section
+ in the W&B UI. If `True`, the table will be displayed in a section named
+ "Custom Chart Tables". Default is `False`.
+
+ Returns:
+ CustomChart: A custom chart object that can be logged to W&B. To log the
+ chart, pass it to `wandb.log()`.
+
+ Examples:
+ Logging a single x array where all y series are plotted against the same x values:
+
+ ```python
+ import wandb
+
+ # Initialize W&B run
+ with wandb.init(project="line_series_example") as run:
+ # x values shared across all y series
+ xs = list(range(10))
+
+ # Multiple y series to plot
+ ys = [
+ [i for i in range(10)], # y = x
+ [i**2 for i in range(10)], # y = x^2
+ [i**3 for i in range(10)], # y = x^3
+ ]
+
+ # Generate and log the line series chart
+ line_series_chart = wandb.plot.line_series(
+ xs,
+ ys,
+ title="title",
+ xname="step",
+ )
+ run.log({"line-series-single-x": line_series_chart})
+ ```
+
+ In this example, a single `xs` series (shared x-values) is used for all
+ `ys` series. This results in each y-series being plotted against the
+ same x-values (0-9).
+
+ Logging multiple x arrays where each y series is plotted against its corresponding x array:
+
+ ```python
+ import wandb
+
+ # Initialize W&B run
+ with wandb.init(project="line_series_example") as run:
+ # Separate x values for each y series
+ xs = [
+ [i for i in range(10)], # x for first series
+ [2 * i for i in range(10)], # x for second series (stretched)
+ [3 * i for i in range(10)], # x for third series (stretched more)
+ ]
+
+ # Corresponding y series
+ ys = [
+ [i for i in range(10)], # y = x
+ [i**2 for i in range(10)], # y = x^2
+ [i**3 for i in range(10)], # y = x^3
+ ]
+
+ # Generate and log the line series chart
+ line_series_chart = wandb.plot.line_series(
+ xs, ys, title="Multiple X Arrays Example", xname="Step"
+ )
+ run.log({"line-series-multiple-x": line_series_chart})
+ ```
+
+ In this example, each y series is plotted against its own unique x series.
+ This allows for more flexibility when the x values are not uniform across
+ the data series.
+
+ Customizing line labels using `keys`:
+
+ ```python
+ import wandb
+
+ # Initialize W&B run
+ with wandb.init(project="line_series_example") as run:
+ xs = list(range(10)) # Single x array
+ ys = [
+ [i for i in range(10)], # y = x
+ [i**2 for i in range(10)], # y = x^2
+ [i**3 for i in range(10)], # y = x^3
+ ]
+
+ # Custom labels for each line
+ keys = ["Linear", "Quadratic", "Cubic"]
+
+ # Generate and log the line series chart
+ line_series_chart = wandb.plot.line_series(
+ xs,
+ ys,
+ keys=keys, # Custom keys (line labels)
+ title="Custom Line Labels Example",
+ xname="Step",
+ )
+ run.log({"line-series-custom-keys": line_series_chart})
+ ```
+
+ This example shows how to provide custom labels for the lines using
+ the `keys` argument. The keys will appear in the legend as "Linear",
+ "Quadratic", and "Cubic".
+ """
+ # If xs is a single array, repeat it for each y in ys
+ if not isinstance(xs[0], Iterable) or isinstance(xs[0], (str, bytes)):
+ xs = [xs] * len(ys)
+
+ if len(xs) != len(ys):
+ msg = f"Number of x-series ({len(xs)}) must match y-series ({len(ys)})."
+ raise ValueError(msg)
+
+ if keys is None:
+ keys = [f"line_{i}" for i in range(len(ys))]
+
+ if len(keys) != len(ys):
+ msg = f"Number of keys ({len(keys)}) must match y-series ({len(ys)})."
+ raise ValueError(msg)
+
+ data = [
+ [x, keys[i], y]
+ for i, (xx, yy) in enumerate(zip(xs, ys))
+ for x, y in zip(xx, yy)
+ ]
+ table = wandb.Table(
+ data=data,
+ columns=["step", "lineKey", "lineVal"],
+ )
+
+ return plot_table(
+ data_table=table,
+ vega_spec_name="wandb/lineseries/v0",
+ fields={
+ "step": "step",
+ "lineKey": "lineKey",
+ "lineVal": "lineVal",
+ },
+ string_fields={"title": title, "xname": xname},
+ split_table=split_table,
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/pr_curve.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/pr_curve.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8ade060c3dab946002f48d3b3164ed901b8efe3
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/pr_curve.py
@@ -0,0 +1,186 @@
+from __future__ import annotations
+
+import numbers
+from typing import TYPE_CHECKING, Iterable, TypeVar
+
+import wandb
+from wandb import util
+from wandb.plot.custom_chart import plot_table
+from wandb.plot.utils import test_missing, test_types
+
+if TYPE_CHECKING:
+ from wandb.plot.custom_chart import CustomChart
+
+
+T = TypeVar("T")
+
+
+def pr_curve(
+ y_true: Iterable[T] | None = None,
+ y_probas: Iterable[numbers.Number] | None = None,
+ labels: list[str] | None = None,
+ classes_to_plot: list[T] | None = None,
+ interp_size: int = 21,
+ title: str = "Precision-Recall Curve",
+ split_table: bool = False,
+) -> CustomChart:
+ """Constructs a Precision-Recall (PR) curve.
+
+ The Precision-Recall curve is particularly useful for evaluating classifiers
+ on imbalanced datasets. A high area under the PR curve signifies both high
+ precision (a low false positive rate) and high recall (a low false negative
+ rate). The curve provides insights into the balance between false positives
+ and false negatives at various threshold levels, aiding in the assessment of
+ a model's performance.
+
+ Args:
+ y_true: True binary labels. The shape should be (`num_samples`,).
+ y_probas: Predicted scores or probabilities for each class.
+ These can be probability estimates, confidence scores, or non-thresholded
+ decision values. The shape should be (`num_samples`, `num_classes`).
+ labels: Optional list of class names to replace
+ numeric values in `y_true` for easier plot interpretation.
+ For example, `labels = ['dog', 'cat', 'owl']` will replace 0 with
+ 'dog', 1 with 'cat', and 2 with 'owl' in the plot. If not provided,
+ numeric values from `y_true` will be used.
+ classes_to_plot: Optional list of unique class values from
+ y_true to be included in the plot. If not specified, all unique
+ classes in y_true will be plotted.
+ interp_size: Number of points to interpolate recall values. The
+ recall values will be fixed to `interp_size` uniformly distributed
+ points in the range [0, 1], and the precision will be interpolated
+ accordingly.
+ title: Title of the plot. Defaults to "Precision-Recall Curve".
+ split_table: Whether the table should be split into a separate section
+ in the W&B UI. If `True`, the table will be displayed in a section named
+ "Custom Chart Tables". Default is `False`.
+
+ Returns:
+ CustomChart: A custom chart object that can be logged to W&B. To log the
+ chart, pass it to `wandb.log()`.
+
+ Raises:
+ wandb.Error: If NumPy, pandas, or scikit-learn is not installed.
+
+
+ Example:
+
+ ```python
+ import wandb
+
+ # Example for spam detection (binary classification)
+ y_true = [0, 1, 1, 0, 1] # 0 = not spam, 1 = spam
+ y_probas = [
+ [0.9, 0.1], # Predicted probabilities for the first sample (not spam)
+ [0.2, 0.8], # Second sample (spam), and so on
+ [0.1, 0.9],
+ [0.8, 0.2],
+ [0.3, 0.7],
+ ]
+
+ labels = ["not spam", "spam"] # Optional class names for readability
+
+ with wandb.init(project="spam-detection") as run:
+ pr_curve = wandb.plot.pr_curve(
+ y_true=y_true,
+ y_probas=y_probas,
+ labels=labels,
+ title="Precision-Recall Curve for Spam Detection",
+ )
+ run.log({"pr-curve": pr_curve})
+ ```
+ """
+ np = util.get_module(
+ "numpy",
+ required="roc requires the numpy library, install with `pip install numpy`",
+ )
+ pd = util.get_module(
+ "pandas",
+ required="roc requires the pandas library, install with `pip install pandas`",
+ )
+ sklearn_metrics = util.get_module(
+ "sklearn.metrics",
+ "roc requires the scikit library, install with `pip install scikit-learn`",
+ )
+ sklearn_utils = util.get_module(
+ "sklearn.utils",
+ "roc requires the scikit library, install with `pip install scikit-learn`",
+ )
+
+ def _step(x):
+ y = np.array(x)
+ for i in range(1, len(y)):
+ y[i] = max(y[i], y[i - 1])
+ return y
+
+ y_true = np.array(y_true)
+ y_probas = np.array(y_probas)
+
+ if not test_missing(y_true=y_true, y_probas=y_probas):
+ return
+ if not test_types(y_true=y_true, y_probas=y_probas):
+ return
+
+ classes = np.unique(y_true)
+ if classes_to_plot is None:
+ classes_to_plot = classes
+
+ precision = {}
+ interp_recall = np.linspace(0, 1, interp_size)[::-1]
+ indices_to_plot = np.where(np.isin(classes, classes_to_plot))[0]
+ for i in indices_to_plot:
+ if labels is not None and (
+ isinstance(classes[i], int) or isinstance(classes[0], np.integer)
+ ):
+ class_label = labels[classes[i]]
+ else:
+ class_label = classes[i]
+
+ cur_precision, cur_recall, _ = sklearn_metrics.precision_recall_curve(
+ y_true, y_probas[:, i], pos_label=classes[i]
+ )
+ # smooth the precision (monotonically increasing)
+ cur_precision = _step(cur_precision)
+
+ # reverse order so that recall in ascending
+ cur_precision = cur_precision[::-1]
+ cur_recall = cur_recall[::-1]
+ indices = np.searchsorted(cur_recall, interp_recall, side="left")
+ precision[class_label] = cur_precision[indices]
+
+ df = pd.DataFrame(
+ {
+ "class": np.hstack([[k] * len(v) for k, v in precision.items()]),
+ "precision": np.hstack(list(precision.values())),
+ "recall": np.tile(interp_recall, len(precision)),
+ }
+ ).round(3)
+
+ if len(df) > wandb.Table.MAX_ROWS:
+ wandb.termwarn(
+ f"Table has a limit of {wandb.Table.MAX_ROWS} rows. Resampling to fit."
+ )
+ # different sampling could be applied, possibly to ensure endpoints are kept
+ df = sklearn_utils.resample(
+ df,
+ replace=False,
+ n_samples=wandb.Table.MAX_ROWS,
+ random_state=42,
+ stratify=df["class"],
+ ).sort_values(["precision", "recall", "class"])
+
+ return plot_table(
+ data_table=wandb.Table(dataframe=df),
+ vega_spec_name="wandb/area-under-curve/v0",
+ fields={
+ "x": "recall",
+ "y": "precision",
+ "class": "class",
+ },
+ string_fields={
+ "title": title,
+ "x-axis-title": "Recall",
+ "y-axis-title": "Precision",
+ },
+ split_table=split_table,
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/roc_curve.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/roc_curve.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce42232a9d0a3a91ed0017a3c126b4acc7063402
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/roc_curve.py
@@ -0,0 +1,163 @@
+from __future__ import annotations
+
+import numbers
+from typing import TYPE_CHECKING, Sequence
+
+import wandb
+from wandb import util
+from wandb.plot.custom_chart import plot_table
+from wandb.plot.utils import test_missing, test_types
+
+if TYPE_CHECKING:
+ from wandb.plot.custom_chart import CustomChart
+
+
+def roc_curve(
+ y_true: Sequence[numbers.Number],
+ y_probas: Sequence[Sequence[float]] | None = None,
+ labels: list[str] | None = None,
+ classes_to_plot: list[numbers.Number] | None = None,
+ title: str = "ROC Curve",
+ split_table: bool = False,
+) -> CustomChart:
+ """Constructs Receiver Operating Characteristic (ROC) curve chart.
+
+ Args:
+ y_true: The true class labels (ground truth)
+ for the target variable. Shape should be (num_samples,).
+ y_probas: The predicted probabilities or
+ decision scores for each class. Shape should be (num_samples, num_classes).
+ labels: Human-readable labels corresponding to the class
+ indices in `y_true`. For example, if `labels=['dog', 'cat']`,
+ class 0 will be displayed as 'dog' and class 1 as 'cat' in the plot.
+ If None, the raw class indices from `y_true` will be used.
+ Default is None.
+ classes_to_plot: A subset of unique class labels
+ to include in the ROC curve. If None, all classes in `y_true` will
+ be plotted. Default is None.
+ title: Title of the ROC curve plot. Default is "ROC Curve".
+ split_table: Whether the table should be split into a separate
+ section in the W&B UI. If `True`, the table will be displayed in a
+ section named "Custom Chart Tables". Default is `False`.
+
+ Returns:
+ CustomChart: A custom chart object that can be logged to W&B. To log the
+ chart, pass it to `wandb.log()`.
+
+ Raises:
+ wandb.Error: If numpy, pandas, or scikit-learn are not found.
+
+ Example:
+ ```python
+ import numpy as np
+ import wandb
+
+ # Simulate a medical diagnosis classification problem with three diseases
+ n_samples = 200
+ n_classes = 3
+
+ # True labels: assign "Diabetes", "Hypertension", or "Heart Disease" to
+ # each sample
+ disease_labels = ["Diabetes", "Hypertension", "Heart Disease"]
+ # 0: Diabetes, 1: Hypertension, 2: Heart Disease
+ y_true = np.random.choice([0, 1, 2], size=n_samples)
+
+ # Predicted probabilities: simulate predictions, ensuring they sum to 1
+ # for each sample
+ y_probas = np.random.dirichlet(np.ones(n_classes), size=n_samples)
+
+ # Specify classes to plot (plotting all three diseases)
+ classes_to_plot = [0, 1, 2]
+
+ # Initialize a W&B run and log a ROC curve plot for disease classification
+ with wandb.init(project="medical_diagnosis") as run:
+ roc_plot = wandb.plot.roc_curve(
+ y_true=y_true,
+ y_probas=y_probas,
+ labels=disease_labels,
+ classes_to_plot=classes_to_plot,
+ title="ROC Curve for Disease Classification",
+ )
+ run.log({"roc-curve": roc_plot})
+ ```
+ """
+ np = util.get_module(
+ "numpy",
+ required="roc requires the numpy library, install with `pip install numpy`",
+ )
+ pd = util.get_module(
+ "pandas",
+ required="roc requires the pandas library, install with `pip install pandas`",
+ )
+ sklearn_metrics = util.get_module(
+ "sklearn.metrics",
+ "roc requires the scikit library, install with `pip install scikit-learn`",
+ )
+ sklearn_utils = util.get_module(
+ "sklearn.utils",
+ "roc requires the scikit library, install with `pip install scikit-learn`",
+ )
+
+ y_true = np.array(y_true)
+ y_probas = np.array(y_probas)
+
+ if not test_missing(y_true=y_true, y_probas=y_probas):
+ return
+ if not test_types(y_true=y_true, y_probas=y_probas):
+ return
+
+ classes = np.unique(y_true)
+ if classes_to_plot is None:
+ classes_to_plot = classes
+
+ fpr = {}
+ tpr = {}
+ indices_to_plot = np.where(np.isin(classes, classes_to_plot))[0]
+ for i in indices_to_plot:
+ if labels is not None and (
+ isinstance(classes[i], int) or isinstance(classes[0], np.integer)
+ ):
+ class_label = labels[classes[i]]
+ else:
+ class_label = classes[i]
+
+ fpr[class_label], tpr[class_label], _ = sklearn_metrics.roc_curve(
+ y_true, y_probas[..., i], pos_label=classes[i]
+ )
+
+ df = pd.DataFrame(
+ {
+ "class": np.hstack([[k] * len(v) for k, v in fpr.items()]),
+ "fpr": np.hstack(list(fpr.values())),
+ "tpr": np.hstack(list(tpr.values())),
+ }
+ ).round(3)
+
+ if len(df) > wandb.Table.MAX_ROWS:
+ wandb.termwarn(
+ f"wandb uses only {wandb.Table.MAX_ROWS} data points to create the plots."
+ )
+ # different sampling could be applied, possibly to ensure endpoints are kept
+ df = sklearn_utils.resample(
+ df,
+ replace=False,
+ n_samples=wandb.Table.MAX_ROWS,
+ random_state=42,
+ stratify=df["class"],
+ ).sort_values(["fpr", "tpr", "class"])
+
+ return plot_table(
+ data_table=wandb.Table(dataframe=df),
+ vega_spec_name="wandb/area-under-curve/v0",
+ fields={
+ "x": "fpr",
+ "y": "tpr",
+ "class": "class",
+ },
+ string_fields={
+ "title": title,
+ "x-axis-title": "False positive rate",
+ "y-axis-title": "True positive rate",
+ },
+ split_table=split_table,
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/scatter.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/scatter.py
new file mode 100644
index 0000000000000000000000000000000000000000..40e3d8033e2d6249554e3de56904add3ef30ffbd
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/scatter.py
@@ -0,0 +1,66 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from wandb.plot.custom_chart import plot_table
+
+if TYPE_CHECKING:
+ import wandb
+ from wandb.plot.custom_chart import CustomChart
+
+
+def scatter(
+ table: wandb.Table,
+ x: str,
+ y: str,
+ title: str = "",
+ split_table: bool = False,
+) -> CustomChart:
+ """Constructs a scatter plot from a wandb.Table of data.
+
+ Args:
+ table: The W&B Table containing the data to visualize.
+ x: The name of the column used for the x-axis.
+ y: The name of the column used for the y-axis.
+ title: The title of the scatter chart.
+ split_table: Whether the table should be split into a separate section
+ in the W&B UI. If `True`, the table will be displayed in a section named
+ "Custom Chart Tables". Default is `False`.
+
+ Returns:
+ CustomChart: A custom chart object that can be logged to W&B. To log the
+ chart, pass it to `wandb.log()`.
+ Example:
+ ```python
+ import math
+ import random
+ import wandb
+
+ # Simulate temperature variations at different altitudes over time
+ data = [
+ [i, random.uniform(-10, 20) - 0.005 * i + 5 * math.sin(i / 50)]
+ for i in range(300)
+ ]
+
+ # Create W&B table with altitude (m) and temperature (°C) columns
+ table = wandb.Table(data=data, columns=["altitude (m)", "temperature (°C)"])
+
+ # Initialize W&B run and log the scatter plot
+ with wandb.init(project="temperature-altitude-scatter") as run:
+ # Create and log the scatter plot
+ scatter_plot = wandb.plot.scatter(
+ table=table,
+ x="altitude (m)",
+ y="temperature (°C)",
+ title="Altitude vs Temperature",
+ )
+ run.log({"altitude-temperature-scatter": scatter_plot})
+ ```
+ """
+ return plot_table(
+ data_table=table,
+ vega_spec_name="wandb/scatter/v0",
+ fields={"x": x, "y": y},
+ string_fields={"title": title},
+ split_table=split_table,
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/utils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..9436dce8e3394acd731d3efffed23af8188490e6
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/utils.py
@@ -0,0 +1,184 @@
+from typing import Iterable, Sequence
+
+import wandb
+from wandb import util
+
+
+def test_missing(**kwargs):
+ np = util.get_module("numpy", required="Logging plots requires numpy")
+ pd = util.get_module("pandas", required="Logging dataframes requires pandas")
+ scipy = util.get_module("scipy", required="Logging scipy matrices requires scipy")
+
+ test_passed = True
+ for k, v in kwargs.items():
+ # Missing/empty params/datapoint arrays
+ if v is None:
+ wandb.termerror(f"{k} is None. Please try again.")
+ test_passed = False
+ if (k == "X") or (k == "X_test"):
+ if isinstance(v, scipy.sparse.csr.csr_matrix):
+ v = v.toarray()
+ elif isinstance(v, (pd.DataFrame, pd.Series)):
+ v = v.to_numpy()
+ elif isinstance(v, list):
+ v = np.asarray(v)
+
+ # Warn the user about missing values
+ missing = 0
+ missing = np.count_nonzero(pd.isnull(v))
+ if missing > 0:
+ wandb.termwarn("%s contains %d missing values. " % (k, missing))
+ test_passed = False
+ # Ensure the dataset contains only integers
+ non_nums = 0
+ if v.ndim == 1:
+ non_nums = sum(
+ 1
+ for val in v
+ if (
+ not isinstance(val, (int, float, complex))
+ and not isinstance(val, np.number)
+ )
+ )
+ else:
+ non_nums = sum(
+ 1
+ for sl in v
+ for val in sl
+ if (
+ not isinstance(val, (int, float, complex))
+ and not isinstance(val, np.number)
+ )
+ )
+ if non_nums > 0:
+ wandb.termerror(
+ f"{k} contains values that are not numbers. Please vectorize, "
+ f"label encode or one hot encode {k} and call the plotting function again."
+ )
+ test_passed = False
+ return test_passed
+
+
+def test_fitted(model):
+ np = util.get_module("numpy", required="Logging plots requires numpy")
+ _ = util.get_module("pandas", required="Logging dataframes requires pandas")
+ _ = util.get_module("scipy", required="Logging scipy matrices requires scipy")
+ scikit_utils = util.get_module(
+ "sklearn.utils",
+ required="roc requires the scikit utils submodule, install with `pip install scikit-learn`",
+ )
+ scikit_exceptions = util.get_module(
+ "sklearn.exceptions",
+ "roc requires the scikit preprocessing submodule, install with `pip install scikit-learn`",
+ )
+
+ try:
+ model.predict(np.zeros((7, 3)))
+ except scikit_exceptions.NotFittedError:
+ wandb.termerror("Please fit the model before passing it in.")
+ return False
+ except AttributeError:
+ # Some clustering models (LDA, PCA, Agglomerative) don't implement ``predict``
+ try:
+ scikit_utils.validation.check_is_fitted(
+ model,
+ [
+ "coef_",
+ "estimator_",
+ "labels_",
+ "n_clusters_",
+ "children_",
+ "components_",
+ "n_components_",
+ "n_iter_",
+ "n_batch_iter_",
+ "explained_variance_",
+ "singular_values_",
+ "mean_",
+ ],
+ all_or_any=any,
+ )
+ except scikit_exceptions.NotFittedError:
+ wandb.termerror("Please fit the model before passing it in.")
+ return False
+ else:
+ return True
+ except Exception:
+ # Assume it's fitted, since ``NotFittedError`` wasn't raised
+ return True
+
+
+def encode_labels(df):
+ _ = util.get_module("pandas", required="Logging dataframes requires pandas")
+ preprocessing = util.get_module(
+ "sklearn.preprocessing",
+ "roc requires the scikit preprocessing submodule, install with `pip install scikit-learn`",
+ )
+
+ le = preprocessing.LabelEncoder()
+ # apply le on categorical feature columns
+ categorical_cols = df.select_dtypes(
+ exclude=["int", "float", "float64", "float32", "int32", "int64"]
+ ).columns
+ df[categorical_cols] = df[categorical_cols].apply(lambda col: le.fit_transform(col))
+
+
+def test_types(**kwargs):
+ np = util.get_module("numpy", required="Logging plots requires numpy")
+ pd = util.get_module("pandas", required="Logging dataframes requires pandas")
+ _ = util.get_module("scipy", required="Logging scipy matrices requires scipy")
+
+ base = util.get_module(
+ "sklearn.base",
+ "roc requires the scikit base submodule, install with `pip install scikit-learn`",
+ )
+
+ test_passed = True
+ for k, v in kwargs.items():
+ # check for incorrect types
+ if (
+ (k == "X")
+ or (k == "X_test")
+ or (k == "y")
+ or (k == "y_test")
+ or (k == "y_true")
+ or (k == "y_probas")
+ or (k == "x_labels")
+ or (k == "y_labels")
+ or (k == "matrix_values")
+ ):
+ # FIXME: do this individually
+ if not isinstance(
+ v,
+ (
+ Sequence,
+ Iterable,
+ np.ndarray,
+ np.generic,
+ pd.DataFrame,
+ pd.Series,
+ list,
+ ),
+ ):
+ wandb.termerror(f"{k} is not an array. Please try again.")
+ test_passed = False
+ # check for classifier types
+ if k == "model":
+ if (not base.is_classifier(v)) and (not base.is_regressor(v)):
+ wandb.termerror(
+ f"{k} is not a classifier or regressor. Please try again."
+ )
+ test_passed = False
+ elif k == "clf" or k == "binary_clf":
+ if not (base.is_classifier(v)):
+ wandb.termerror(f"{k} is not a classifier. Please try again.")
+ test_passed = False
+ elif k == "regressor":
+ if not base.is_regressor(v):
+ wandb.termerror(f"{k} is not a regressor. Please try again.")
+ test_passed = False
+ elif k == "clusterer":
+ if not (getattr(v, "_estimator_type", None) == "clusterer"):
+ wandb.termerror(f"{k} is not a clusterer. Please try again.")
+ test_passed = False
+ return test_passed
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/viz.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/viz.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea6be2f8805891b5d0c77b557c040a4377e9f4f9
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/plot/viz.py
@@ -0,0 +1,41 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
+from wandb.data_types import Table
+from wandb.errors import Error
+
+
+@dataclass
+class VisualizeSpec:
+ name: str
+ key: str = ""
+
+ @property
+ def config_value(self) -> dict[str, Any]:
+ return {
+ "id": self.name,
+ "historyFieldSettings": {"x-axis": "_step", "key": self.key},
+ }
+
+ @property
+ def config_key(self) -> tuple[str, str, str]:
+ return ("_wandb", "viz", self.key)
+
+
+@dataclass
+class Visualize:
+ table: Table
+ spec: VisualizeSpec
+
+ def set_key(self, key: str) -> None:
+ self.spec.key = key
+
+
+def visualize(id: str, value: Table) -> Visualize:
+ if not isinstance(value, Table):
+ raise Error(
+ f"Expected `value` to be `wandb.Table` type, instead got {type(value).__name__}"
+ )
+ return Visualize(table=value, spec=VisualizeSpec(name=id))
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/wandb_api_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/wandb_api_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..4df9ea48d995282ec67e072d42cfa9ed7f3dafcf
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/wandb_api_pb2.py
@@ -0,0 +1,86 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: wandb/proto/wandb_api.proto
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import message as _message
+from google.protobuf import reflection as _reflection
+from google.protobuf import symbol_database as _symbol_database
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1bwandb/proto/wandb_api.proto\x12\x0ewandb_internal\x1a\x1cwandb/proto/wandb_base.proto\"]\n\nApiRequest\x12\x44\n\x10read_run_history\x18\x01 \x01(\x0b\x32(.wandb_internal.ReadRunHistoryApiRequestH\x00\x42\t\n\x07request\"`\n\x0b\x41piResponse\x12\x45\n\x10read_run_history\x18\x01 \x01(\x0b\x32).wandb_internal.ReadRunHistoryApiResponseH\x00\x42\n\n\x08response\"\xaa\x01\n\x18ReadRunHistoryApiRequest\x12\x0e\n\x06\x65ntity\x18\x01 \x01(\t\x12\x0f\n\x07project\x18\x02 \x01(\t\x12\x0e\n\x06run_id\x18\x03 \x01(\t\x12\x0c\n\x04keys\x18\x04 \x03(\t\x12\x10\n\x08min_step\x18\x05 \x01(\x03\x12\x10\n\x08max_step\x18\x06 \x01(\x03\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"d\n\x19ReadRunHistoryApiResponse\x12\x30\n\x0chistory_rows\x18\x01 \x03(\x0b\x32\x1a.wandb_internal.HistoryRow\x12\x15\n\rerror_message\x18\x02 \x01(\t\"G\n\nHistoryRow\x12\x39\n\rhistory_items\x18\x01 \x03(\x0b\x32\".wandb_internal.ParquetHistoryItem\"5\n\x12ParquetHistoryItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\tB\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+
+
+_APIREQUEST = DESCRIPTOR.message_types_by_name['ApiRequest']
+_APIRESPONSE = DESCRIPTOR.message_types_by_name['ApiResponse']
+_READRUNHISTORYAPIREQUEST = DESCRIPTOR.message_types_by_name['ReadRunHistoryApiRequest']
+_READRUNHISTORYAPIRESPONSE = DESCRIPTOR.message_types_by_name['ReadRunHistoryApiResponse']
+_HISTORYROW = DESCRIPTOR.message_types_by_name['HistoryRow']
+_PARQUETHISTORYITEM = DESCRIPTOR.message_types_by_name['ParquetHistoryItem']
+ApiRequest = _reflection.GeneratedProtocolMessageType('ApiRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _APIREQUEST,
+ '__module__' : 'wandb.proto.wandb_api_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ApiRequest)
+ })
+_sym_db.RegisterMessage(ApiRequest)
+
+ApiResponse = _reflection.GeneratedProtocolMessageType('ApiResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _APIRESPONSE,
+ '__module__' : 'wandb.proto.wandb_api_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ApiResponse)
+ })
+_sym_db.RegisterMessage(ApiResponse)
+
+ReadRunHistoryApiRequest = _reflection.GeneratedProtocolMessageType('ReadRunHistoryApiRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _READRUNHISTORYAPIREQUEST,
+ '__module__' : 'wandb.proto.wandb_api_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ReadRunHistoryApiRequest)
+ })
+_sym_db.RegisterMessage(ReadRunHistoryApiRequest)
+
+ReadRunHistoryApiResponse = _reflection.GeneratedProtocolMessageType('ReadRunHistoryApiResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _READRUNHISTORYAPIRESPONSE,
+ '__module__' : 'wandb.proto.wandb_api_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ReadRunHistoryApiResponse)
+ })
+_sym_db.RegisterMessage(ReadRunHistoryApiResponse)
+
+HistoryRow = _reflection.GeneratedProtocolMessageType('HistoryRow', (_message.Message,), {
+ 'DESCRIPTOR' : _HISTORYROW,
+ '__module__' : 'wandb.proto.wandb_api_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.HistoryRow)
+ })
+_sym_db.RegisterMessage(HistoryRow)
+
+ParquetHistoryItem = _reflection.GeneratedProtocolMessageType('ParquetHistoryItem', (_message.Message,), {
+ 'DESCRIPTOR' : _PARQUETHISTORYITEM,
+ '__module__' : 'wandb.proto.wandb_api_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ParquetHistoryItem)
+ })
+_sym_db.RegisterMessage(ParquetHistoryItem)
+
+if _descriptor._USE_C_DESCRIPTORS == False:
+
+ DESCRIPTOR._options = None
+ DESCRIPTOR._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _APIREQUEST._serialized_start=77
+ _APIREQUEST._serialized_end=170
+ _APIRESPONSE._serialized_start=172
+ _APIRESPONSE._serialized_end=268
+ _READRUNHISTORYAPIREQUEST._serialized_start=271
+ _READRUNHISTORYAPIREQUEST._serialized_end=441
+ _READRUNHISTORYAPIRESPONSE._serialized_start=443
+ _READRUNHISTORYAPIRESPONSE._serialized_end=543
+ _HISTORYROW._serialized_start=545
+ _HISTORYROW._serialized_end=616
+ _PARQUETHISTORYITEM._serialized_start=618
+ _PARQUETHISTORYITEM._serialized_end=671
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/wandb_base_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/wandb_base_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..39db329f85b1bcaee10ef3120c377b6b011035a7
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/wandb_base_pb2.py
@@ -0,0 +1,55 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: wandb/proto/wandb_base.proto
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import message as _message
+from google.protobuf import reflection as _reflection
+from google.protobuf import symbol_database as _symbol_database
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1cwandb/proto/wandb_base.proto\x12\x0ewandb_internal\"6\n\x0b_RecordInfo\x12\x11\n\tstream_id\x18\x01 \x01(\t\x12\x14\n\x0c_tracelog_id\x18\x64 \x01(\t\"!\n\x0c_RequestInfo\x12\x11\n\tstream_id\x18\x01 \x01(\t\"#\n\x0b_ResultInfo\x12\x14\n\x0c_tracelog_id\x18\x64 \x01(\tB\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+
+
+__RECORDINFO = DESCRIPTOR.message_types_by_name['_RecordInfo']
+__REQUESTINFO = DESCRIPTOR.message_types_by_name['_RequestInfo']
+__RESULTINFO = DESCRIPTOR.message_types_by_name['_ResultInfo']
+_RecordInfo = _reflection.GeneratedProtocolMessageType('_RecordInfo', (_message.Message,), {
+ 'DESCRIPTOR' : __RECORDINFO,
+ '__module__' : 'wandb.proto.wandb_base_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal._RecordInfo)
+ })
+_sym_db.RegisterMessage(_RecordInfo)
+
+_RequestInfo = _reflection.GeneratedProtocolMessageType('_RequestInfo', (_message.Message,), {
+ 'DESCRIPTOR' : __REQUESTINFO,
+ '__module__' : 'wandb.proto.wandb_base_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal._RequestInfo)
+ })
+_sym_db.RegisterMessage(_RequestInfo)
+
+_ResultInfo = _reflection.GeneratedProtocolMessageType('_ResultInfo', (_message.Message,), {
+ 'DESCRIPTOR' : __RESULTINFO,
+ '__module__' : 'wandb.proto.wandb_base_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal._ResultInfo)
+ })
+_sym_db.RegisterMessage(_ResultInfo)
+
+if _descriptor._USE_C_DESCRIPTORS == False:
+
+ DESCRIPTOR._options = None
+ DESCRIPTOR._serialized_options = b'Z\031core/pkg/service_go_proto'
+ __RECORDINFO._serialized_start=48
+ __RECORDINFO._serialized_end=102
+ __REQUESTINFO._serialized_start=104
+ __REQUESTINFO._serialized_end=137
+ __RESULTINFO._serialized_start=139
+ __RESULTINFO._serialized_end=174
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/wandb_internal_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/wandb_internal_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f99dfbcc7a00d537f9d6a7298dcef323d989716
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/wandb_internal_pb2.py
@@ -0,0 +1,1739 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: wandb/proto/wandb_internal.proto
+"""Generated protocol buffer code."""
+from google.protobuf.internal import enum_type_wrapper
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import message as _message
+from google.protobuf import reflection as _reflection
+from google.protobuf import symbol_database as _symbol_database
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
+from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
+from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2
+from wandb.proto import wandb_telemetry_pb2 as wandb_dot_proto_dot_wandb__telemetry__pb2
+from wandb.proto import wandb_api_pb2 as wandb_dot_proto_dot_wandb__api__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n wandb/proto/wandb_internal.proto\x12\x0ewandb_internal\x1a\x1bgoogle/protobuf/empty.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1cwandb/proto/wandb_base.proto\x1a!wandb/proto/wandb_telemetry.proto\x1a\x1bwandb/proto/wandb_api.proto\"\x82\n\n\x06Record\x12\x0b\n\x03num\x18\x01 \x01(\x03\x12\x30\n\x07history\x18\x02 \x01(\x0b\x32\x1d.wandb_internal.HistoryRecordH\x00\x12\x30\n\x07summary\x18\x03 \x01(\x0b\x32\x1d.wandb_internal.SummaryRecordH\x00\x12.\n\x06output\x18\x04 \x01(\x0b\x32\x1c.wandb_internal.OutputRecordH\x00\x12.\n\x06\x63onfig\x18\x05 \x01(\x0b\x32\x1c.wandb_internal.ConfigRecordH\x00\x12,\n\x05\x66iles\x18\x06 \x01(\x0b\x32\x1b.wandb_internal.FilesRecordH\x00\x12,\n\x05stats\x18\x07 \x01(\x0b\x32\x1b.wandb_internal.StatsRecordH\x00\x12\x32\n\x08\x61rtifact\x18\x08 \x01(\x0b\x32\x1e.wandb_internal.ArtifactRecordH\x00\x12,\n\x08tbrecord\x18\t \x01(\x0b\x32\x18.wandb_internal.TBRecordH\x00\x12,\n\x05\x61lert\x18\n \x01(\x0b\x32\x1b.wandb_internal.AlertRecordH\x00\x12\x34\n\ttelemetry\x18\x0b \x01(\x0b\x32\x1f.wandb_internal.TelemetryRecordH\x00\x12.\n\x06metric\x18\x0c \x01(\x0b\x32\x1c.wandb_internal.MetricRecordH\x00\x12\x35\n\noutput_raw\x18\r \x01(\x0b\x32\x1f.wandb_internal.OutputRawRecordH\x00\x12(\n\x03run\x18\x11 \x01(\x0b\x32\x19.wandb_internal.RunRecordH\x00\x12-\n\x04\x65xit\x18\x12 \x01(\x0b\x32\x1d.wandb_internal.RunExitRecordH\x00\x12,\n\x05\x66inal\x18\x14 \x01(\x0b\x32\x1b.wandb_internal.FinalRecordH\x00\x12.\n\x06header\x18\x15 \x01(\x0b\x32\x1c.wandb_internal.HeaderRecordH\x00\x12.\n\x06\x66ooter\x18\x16 \x01(\x0b\x32\x1c.wandb_internal.FooterRecordH\x00\x12\x39\n\npreempting\x18\x17 \x01(\x0b\x32#.wandb_internal.RunPreemptingRecordH\x00\x12\x34\n\x12noop_link_artifact\x18\x18 \x01(\x0b\x32\x16.google.protobuf.EmptyH\x00\x12\x39\n\x0cuse_artifact\x18\x19 \x01(\x0b\x32!.wandb_internal.UseArtifactRecordH\x00\x12\x38\n\x0b\x65nvironment\x18\x1a \x01(\x0b\x32!.wandb_internal.EnvironmentRecordH\x00\x12*\n\x07request\x18\x64 \x01(\x0b\x32\x17.wandb_internal.RequestH\x00\x12\x31\n\x0b\x61pi_request\x18\x65 \x01(\x0b\x32\x1a.wandb_internal.ApiRequestH\x00\x12(\n\x07\x63ontrol\x18\x10 \x01(\x0b\x32\x17.wandb_internal.Control\x12\x0c\n\x04uuid\x18\x13 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfoB\r\n\x0brecord_type\"\xa8\x01\n\x07\x43ontrol\x12\x10\n\x08req_resp\x18\x01 \x01(\x08\x12\r\n\x05local\x18\x02 \x01(\x08\x12\x10\n\x08relay_id\x18\x03 \x01(\t\x12\x14\n\x0cmailbox_slot\x18\x04 \x01(\t\x12\x13\n\x0b\x61lways_send\x18\x05 \x01(\x08\x12\x14\n\x0c\x66low_control\x18\x06 \x01(\x08\x12\x12\n\nend_offset\x18\x07 \x01(\x03\x12\x15\n\rconnection_id\x18\x08 \x01(\t\"\xf3\x03\n\x06Result\x12\x35\n\nrun_result\x18\x11 \x01(\x0b\x32\x1f.wandb_internal.RunUpdateResultH\x00\x12\x34\n\x0b\x65xit_result\x18\x12 \x01(\x0b\x32\x1d.wandb_internal.RunExitResultH\x00\x12\x33\n\nlog_result\x18\x14 \x01(\x0b\x32\x1d.wandb_internal.HistoryResultH\x00\x12\x37\n\x0esummary_result\x18\x15 \x01(\x0b\x32\x1d.wandb_internal.SummaryResultH\x00\x12\x35\n\routput_result\x18\x16 \x01(\x0b\x32\x1c.wandb_internal.OutputResultH\x00\x12\x35\n\rconfig_result\x18\x17 \x01(\x0b\x32\x1c.wandb_internal.ConfigResultH\x00\x12,\n\x08response\x18\x64 \x01(\x0b\x32\x18.wandb_internal.ResponseH\x00\x12(\n\x07\x63ontrol\x18\x10 \x01(\x0b\x32\x17.wandb_internal.Control\x12\x0c\n\x04uuid\x18\x18 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._ResultInfoB\r\n\x0bresult_type\":\n\x0b\x46inalRecord\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"b\n\x0bVersionInfo\x12\x10\n\x08producer\x18\x01 \x01(\t\x12\x14\n\x0cmin_consumer\x18\x02 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"n\n\x0cHeaderRecord\x12\x31\n\x0cversion_info\x18\x01 \x01(\x0b\x32\x1b.wandb_internal.VersionInfo\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\";\n\x0c\x46ooterRecord\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"9\n\x0b\x42ranchPoint\x12\x0b\n\x03run\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x01\x12\x0e\n\x06metric\x18\x03 \x01(\t\"\x91\x05\n\tRunRecord\x12\x0e\n\x06run_id\x18\x01 \x01(\t\x12\x0e\n\x06\x65ntity\x18\x02 \x01(\t\x12\x0f\n\x07project\x18\x03 \x01(\t\x12,\n\x06\x63onfig\x18\x04 \x01(\x0b\x32\x1c.wandb_internal.ConfigRecord\x12.\n\x07summary\x18\x05 \x01(\x0b\x32\x1d.wandb_internal.SummaryRecord\x12\x11\n\trun_group\x18\x06 \x01(\t\x12\x10\n\x08job_type\x18\x07 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x08 \x01(\t\x12\r\n\x05notes\x18\t \x01(\t\x12\x0c\n\x04tags\x18\n \x03(\t\x12\x30\n\x08settings\x18\x0b \x01(\x0b\x32\x1e.wandb_internal.SettingsRecord\x12\x10\n\x08sweep_id\x18\x0c \x01(\t\x12\x0c\n\x04host\x18\r \x01(\t\x12\x15\n\rstarting_step\x18\x0e \x01(\x03\x12\x12\n\nstorage_id\x18\x10 \x01(\t\x12.\n\nstart_time\x18\x11 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07resumed\x18\x12 \x01(\x08\x12\x32\n\ttelemetry\x18\x13 \x01(\x0b\x32\x1f.wandb_internal.TelemetryRecord\x12\x0f\n\x07runtime\x18\x14 \x01(\x05\x12*\n\x03git\x18\x15 \x01(\x0b\x32\x1d.wandb_internal.GitRepoRecord\x12\x0e\n\x06\x66orked\x18\x16 \x01(\x08\x12\x31\n\x0c\x62ranch_point\x18\x17 \x01(\x0b\x32\x1b.wandb_internal.BranchPoint\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\";\n\rGitRepoRecord\x12\x1a\n\nremote_url\x18\x01 \x01(\tR\x06remote\x12\x0e\n\x06\x63ommit\x18\x02 \x01(\t\"c\n\x0fRunUpdateResult\x12&\n\x03run\x18\x01 \x01(\x0b\x32\x19.wandb_internal.RunRecord\x12(\n\x05\x65rror\x18\x02 \x01(\x0b\x32\x19.wandb_internal.ErrorInfo\"\xac\x01\n\tErrorInfo\x12\x0f\n\x07message\x18\x01 \x01(\t\x12\x31\n\x04\x63ode\x18\x02 \x01(\x0e\x32#.wandb_internal.ErrorInfo.ErrorCode\"[\n\tErrorCode\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x11\n\rCOMMUNICATION\x10\x01\x12\x12\n\x0e\x41UTHENTICATION\x10\x02\x12\t\n\x05USAGE\x10\x03\x12\x0f\n\x0bUNSUPPORTED\x10\x04\"`\n\rRunExitRecord\x12\x11\n\texit_code\x18\x01 \x01(\x05\x12\x0f\n\x07runtime\x18\x02 \x01(\x05\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x0f\n\rRunExitResult\"B\n\x13RunPreemptingRecord\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x15\n\x13RunPreemptingResult\"i\n\x0eSettingsRecord\x12*\n\x04item\x18\x01 \x03(\x0b\x32\x1c.wandb_internal.SettingsItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"/\n\x0cSettingsItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\x1a\n\x0bHistoryStep\x12\x0b\n\x03num\x18\x01 \x01(\x03\"\x92\x01\n\rHistoryRecord\x12)\n\x04item\x18\x01 \x03(\x0b\x32\x1b.wandb_internal.HistoryItem\x12)\n\x04step\x18\x02 \x01(\x0b\x32\x1b.wandb_internal.HistoryStep\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"B\n\x0bHistoryItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nnested_key\x18\x02 \x03(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\x0f\n\rHistoryResult\"\xdc\x01\n\x0cOutputRecord\x12<\n\x0boutput_type\x18\x01 \x01(\x0e\x32\'.wandb_internal.OutputRecord.OutputType\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0c\n\x04line\x18\x03 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"$\n\nOutputType\x12\n\n\x06STDERR\x10\x00\x12\n\n\x06STDOUT\x10\x01\"\x0e\n\x0cOutputResult\"\xe2\x01\n\x0fOutputRawRecord\x12?\n\x0boutput_type\x18\x01 \x01(\x0e\x32*.wandb_internal.OutputRawRecord.OutputType\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0c\n\x04line\x18\x03 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"$\n\nOutputType\x12\n\n\x06STDERR\x10\x00\x12\n\n\x06STDOUT\x10\x01\"\x11\n\x0fOutputRawResult\"\xb4\x03\n\x0cMetricRecord\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x11\n\tglob_name\x18\x02 \x01(\t\x12\x13\n\x0bstep_metric\x18\x04 \x01(\t\x12\x19\n\x11step_metric_index\x18\x05 \x01(\x05\x12.\n\x07options\x18\x06 \x01(\x0b\x32\x1d.wandb_internal.MetricOptions\x12.\n\x07summary\x18\x07 \x01(\x0b\x32\x1d.wandb_internal.MetricSummary\x12\x35\n\x04goal\x18\x08 \x01(\x0e\x32\'.wandb_internal.MetricRecord.MetricGoal\x12/\n\x08_control\x18\t \x01(\x0b\x32\x1d.wandb_internal.MetricControl\x12\x1a\n\x12\x65xpanded_from_glob\x18\n \x01(\x08\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"B\n\nMetricGoal\x12\x0e\n\nGOAL_UNSET\x10\x00\x12\x11\n\rGOAL_MINIMIZE\x10\x01\x12\x11\n\rGOAL_MAXIMIZE\x10\x02\"\x0e\n\x0cMetricResult\"C\n\rMetricOptions\x12\x11\n\tstep_sync\x18\x01 \x01(\x08\x12\x0e\n\x06hidden\x18\x02 \x01(\x08\x12\x0f\n\x07\x64\x65\x66ined\x18\x03 \x01(\x08\"\"\n\rMetricControl\x12\x11\n\toverwrite\x18\x01 \x01(\x08\"~\n\rMetricSummary\x12\x0b\n\x03min\x18\x01 \x01(\x08\x12\x0b\n\x03max\x18\x02 \x01(\x08\x12\x0c\n\x04mean\x18\x03 \x01(\x08\x12\x0c\n\x04\x62\x65st\x18\x04 \x01(\x08\x12\x0c\n\x04last\x18\x05 \x01(\x08\x12\x0c\n\x04none\x18\x06 \x01(\x08\x12\x0c\n\x04\x63opy\x18\x07 \x01(\x08\x12\r\n\x05\x66irst\x18\x08 \x01(\x08\"\x93\x01\n\x0c\x43onfigRecord\x12*\n\x06update\x18\x01 \x03(\x0b\x32\x1a.wandb_internal.ConfigItem\x12*\n\x06remove\x18\x02 \x03(\x0b\x32\x1a.wandb_internal.ConfigItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"A\n\nConfigItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nnested_key\x18\x02 \x03(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\x0e\n\x0c\x43onfigResult\"\x96\x01\n\rSummaryRecord\x12+\n\x06update\x18\x01 \x03(\x0b\x32\x1b.wandb_internal.SummaryItem\x12+\n\x06remove\x18\x02 \x03(\x0b\x32\x1b.wandb_internal.SummaryItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"B\n\x0bSummaryItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nnested_key\x18\x02 \x03(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\x0f\n\rSummaryResult\"d\n\x0b\x46ilesRecord\x12(\n\x05\x66iles\x18\x01 \x03(\x0b\x32\x19.wandb_internal.FilesItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\xec\x01\n\tFilesItem\x12\x0c\n\x04path\x18\x01 \x01(\t\x12\x34\n\x06policy\x18\x02 \x01(\x0e\x32$.wandb_internal.FilesItem.PolicyType\x12\x30\n\x04type\x18\x03 \x01(\x0e\x32\".wandb_internal.FilesItem.FileType\"(\n\nPolicyType\x12\x07\n\x03NOW\x10\x00\x12\x07\n\x03\x45ND\x10\x01\x12\x08\n\x04LIVE\x10\x02\"9\n\x08\x46ileType\x12\t\n\x05OTHER\x10\x00\x12\t\n\x05WANDB\x10\x01\x12\t\n\x05MEDIA\x10\x02\x12\x0c\n\x08\x41RTIFACT\x10\x03J\x04\x08\x10\x10\x11\"\r\n\x0b\x46ilesResult\"\xe6\x01\n\x0bStatsRecord\x12\x39\n\nstats_type\x18\x01 \x01(\x0e\x32%.wandb_internal.StatsRecord.StatsType\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\'\n\x04item\x18\x03 \x03(\x0b\x32\x19.wandb_internal.StatsItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x17\n\tStatsType\x12\n\n\x06SYSTEM\x10\x00\",\n\tStatsItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\xe7\x03\n\x0e\x41rtifactRecord\x12\x0e\n\x06run_id\x18\x01 \x01(\t\x12\x0f\n\x07project\x18\x02 \x01(\t\x12\x0e\n\x06\x65ntity\x18\x03 \x01(\t\x12\x0c\n\x04type\x18\x04 \x01(\t\x12\x0c\n\x04name\x18\x05 \x01(\t\x12\x0e\n\x06\x64igest\x18\x06 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x07 \x01(\t\x12\x10\n\x08metadata\x18\x08 \x01(\t\x12\x14\n\x0cuser_created\x18\t \x01(\x08\x12\x18\n\x10use_after_commit\x18\n \x01(\x08\x12\x0f\n\x07\x61liases\x18\x0b \x03(\t\x12\x32\n\x08manifest\x18\x0c \x01(\x0b\x32 .wandb_internal.ArtifactManifest\x12\x16\n\x0e\x64istributed_id\x18\r \x01(\t\x12\x10\n\x08\x66inalize\x18\x0e \x01(\x08\x12\x11\n\tclient_id\x18\x0f \x01(\t\x12\x1a\n\x12sequence_client_id\x18\x10 \x01(\t\x12\x0f\n\x07\x62\x61se_id\x18\x11 \x01(\t\x12\x1c\n\x14ttl_duration_seconds\x18\x12 \x01(\x03\x12\x0c\n\x04tags\x18\x13 \x03(\t\x12\x19\n\x11incremental_beta1\x18\x64 \x01(\x08\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\xd8\x01\n\x10\x41rtifactManifest\x12\x0f\n\x07version\x18\x01 \x01(\x05\x12\x16\n\x0estorage_policy\x18\x02 \x01(\t\x12\x46\n\x15storage_policy_config\x18\x03 \x03(\x0b\x32\'.wandb_internal.StoragePolicyConfigItem\x12\x37\n\x08\x63ontents\x18\x04 \x03(\x0b\x32%.wandb_internal.ArtifactManifestEntry\x12\x1a\n\x12manifest_file_path\x18\x05 \x01(\t\"\xcf\x01\n\x15\x41rtifactManifestEntry\x12\x0c\n\x04path\x18\x01 \x01(\t\x12\x0e\n\x06\x64igest\x18\x02 \x01(\t\x12\x0b\n\x03ref\x18\x03 \x01(\t\x12\x0c\n\x04size\x18\x04 \x01(\x03\x12\x10\n\x08mimetype\x18\x05 \x01(\t\x12\x12\n\nlocal_path\x18\x06 \x01(\t\x12\x19\n\x11\x62irth_artifact_id\x18\x07 \x01(\t\x12\x12\n\nskip_cache\x18\x08 \x01(\x08\x12(\n\x05\x65xtra\x18\x10 \x03(\x0b\x32\x19.wandb_internal.ExtraItem\",\n\tExtraItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x02 \x01(\t\":\n\x17StoragePolicyConfigItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x02 \x01(\t\"\x10\n\x0e\x41rtifactResult\"\x14\n\x12LinkArtifactResult\"\xf0\x01\n\x13LinkArtifactRequest\x12\x11\n\tclient_id\x18\x01 \x01(\t\x12\x11\n\tserver_id\x18\x02 \x01(\t\x12\x16\n\x0eportfolio_name\x18\x03 \x01(\t\x12\x18\n\x10portfolio_entity\x18\x04 \x01(\t\x12\x19\n\x11portfolio_project\x18\x05 \x01(\t\x12\x19\n\x11portfolio_aliases\x18\x06 \x03(\t\x12\x1e\n\x16portfolio_organization\x18\x07 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"[\n\x14LinkArtifactResponse\x12\x15\n\rerror_message\x18\x01 \x01(\t\x12\x1a\n\rversion_index\x18\x02 \x01(\x05H\x00\x88\x01\x01\x42\x10\n\x0e_version_index\"h\n\x08TBRecord\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\x12\x0f\n\x07log_dir\x18\x01 \x01(\t\x12\x10\n\x08root_dir\x18\x03 \x01(\t\x12\x0c\n\x04save\x18\x02 \x01(\x08\"\n\n\x08TBResult\"}\n\x0b\x41lertRecord\x12\r\n\x05title\x18\x01 \x01(\t\x12\x0c\n\x04text\x18\x02 \x01(\t\x12\r\n\x05level\x18\x03 \x01(\t\x12\x15\n\rwait_duration\x18\x04 \x01(\x03\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\r\n\x0b\x41lertResult\"\xf8\x11\n\x07Request\x12\x38\n\x0bstop_status\x18\x01 \x01(\x0b\x32!.wandb_internal.StopStatusRequestH\x00\x12>\n\x0enetwork_status\x18\x02 \x01(\x0b\x32$.wandb_internal.NetworkStatusRequestH\x00\x12-\n\x05\x64\x65\x66\x65r\x18\x03 \x01(\x0b\x32\x1c.wandb_internal.DeferRequestH\x00\x12\x38\n\x0bget_summary\x18\x04 \x01(\x0b\x32!.wandb_internal.GetSummaryRequestH\x00\x12-\n\x05login\x18\x05 \x01(\x0b\x32\x1c.wandb_internal.LoginRequestH\x00\x12-\n\x05pause\x18\x06 \x01(\x0b\x32\x1c.wandb_internal.PauseRequestH\x00\x12/\n\x06resume\x18\x07 \x01(\x0b\x32\x1d.wandb_internal.ResumeRequestH\x00\x12\x34\n\tpoll_exit\x18\x08 \x01(\x0b\x32\x1f.wandb_internal.PollExitRequestH\x00\x12@\n\x0fsampled_history\x18\t \x01(\x0b\x32%.wandb_internal.SampledHistoryRequestH\x00\x12@\n\x0fpartial_history\x18\n \x01(\x0b\x32%.wandb_internal.PartialHistoryRequestH\x00\x12\x34\n\trun_start\x18\x0b \x01(\x0b\x32\x1f.wandb_internal.RunStartRequestH\x00\x12<\n\rcheck_version\x18\x0c \x01(\x0b\x32#.wandb_internal.CheckVersionRequestH\x00\x12:\n\x0clog_artifact\x18\r \x01(\x0b\x32\".wandb_internal.LogArtifactRequestH\x00\x12\x44\n\x11\x64ownload_artifact\x18\x0e \x01(\x0b\x32\'.wandb_internal.DownloadArtifactRequestH\x00\x12\x35\n\tkeepalive\x18\x11 \x01(\x0b\x32 .wandb_internal.KeepaliveRequestH\x00\x12>\n\x0eserver_feature\x18\x12 \x01(\x0b\x32$.wandb_internal.ServerFeatureRequestH\x00\x12\x36\n\nrun_status\x18\x14 \x01(\x0b\x32 .wandb_internal.RunStatusRequestH\x00\x12/\n\x06\x63\x61ncel\x18\x15 \x01(\x0b\x32\x1d.wandb_internal.CancelRequestH\x00\x12\x44\n\x11internal_messages\x18\x17 \x01(\x0b\x32\'.wandb_internal.InternalMessagesRequestH\x00\x12@\n\x0fpython_packages\x18\x18 \x01(\x0b\x32%.wandb_internal.PythonPackagesRequestH\x00\x12\x33\n\x08shutdown\x18@ \x01(\x0b\x32\x1f.wandb_internal.ShutdownRequestH\x00\x12/\n\x06\x61ttach\x18\x41 \x01(\x0b\x32\x1d.wandb_internal.AttachRequestH\x00\x12/\n\x06status\x18\x42 \x01(\x0b\x32\x1d.wandb_internal.StatusRequestH\x00\x12\x38\n\x0bserver_info\x18\x43 \x01(\x0b\x32!.wandb_internal.ServerInfoRequestH\x00\x12\x38\n\x0bsender_mark\x18\x44 \x01(\x0b\x32!.wandb_internal.SenderMarkRequestH\x00\x12\x38\n\x0bsender_read\x18\x45 \x01(\x0b\x32!.wandb_internal.SenderReadRequestH\x00\x12<\n\rstatus_report\x18\x46 \x01(\x0b\x32#.wandb_internal.StatusReportRequestH\x00\x12>\n\x0esummary_record\x18G \x01(\x0b\x32$.wandb_internal.SummaryRecordRequestH\x00\x12\x42\n\x10telemetry_record\x18H \x01(\x0b\x32&.wandb_internal.TelemetryRecordRequestH\x00\x12\x32\n\x08job_info\x18I \x01(\x0b\x32\x1e.wandb_internal.JobInfoRequestH\x00\x12\x45\n\x12get_system_metrics\x18J \x01(\x0b\x32\'.wandb_internal.GetSystemMetricsRequestH\x00\x12\x34\n\tjob_input\x18M \x01(\x0b\x32\x1f.wandb_internal.JobInputRequestH\x00\x12<\n\rlink_artifact\x18N \x01(\x0b\x32#.wandb_internal.LinkArtifactRequestH\x00\x12N\n\x17run_finish_without_exit\x18O \x01(\x0b\x32+.wandb_internal.RunFinishWithoutExitRequestH\x00\x12\x38\n\x0bsync_finish\x18Q \x01(\x0b\x32!.wandb_internal.SyncFinishRequestH\x00\x12;\n\noperations\x18R \x01(\x0b\x32%.wandb_internal.OperationStatsRequestH\x00\x12\x43\n\x11probe_system_info\x18S \x01(\x0b\x32&.wandb_internal.ProbeSystemInfoRequestH\x00\x12\x39\n\x0btest_inject\x18\xe8\x07 \x01(\x0b\x32!.wandb_internal.TestInjectRequestH\x00\x42\x0e\n\x0crequest_typeJ\x04\x08\x16\x10\x17J\x04\x08K\x10LJ\x04\x08L\x10MJ\x04\x08P\x10Q\"\xd0\x0e\n\x08Response\x12?\n\x12keepalive_response\x18\x12 \x01(\x0b\x32!.wandb_internal.KeepaliveResponseH\x00\x12\x42\n\x14stop_status_response\x18\x13 \x01(\x0b\x32\".wandb_internal.StopStatusResponseH\x00\x12H\n\x17network_status_response\x18\x14 \x01(\x0b\x32%.wandb_internal.NetworkStatusResponseH\x00\x12\x37\n\x0elogin_response\x18\x18 \x01(\x0b\x32\x1d.wandb_internal.LoginResponseH\x00\x12\x42\n\x14get_summary_response\x18\x19 \x01(\x0b\x32\".wandb_internal.GetSummaryResponseH\x00\x12>\n\x12poll_exit_response\x18\x1a \x01(\x0b\x32 .wandb_internal.PollExitResponseH\x00\x12J\n\x18sampled_history_response\x18\x1b \x01(\x0b\x32&.wandb_internal.SampledHistoryResponseH\x00\x12>\n\x12run_start_response\x18\x1c \x01(\x0b\x32 .wandb_internal.RunStartResponseH\x00\x12\x46\n\x16\x63heck_version_response\x18\x1d \x01(\x0b\x32$.wandb_internal.CheckVersionResponseH\x00\x12\x44\n\x15log_artifact_response\x18\x1e \x01(\x0b\x32#.wandb_internal.LogArtifactResponseH\x00\x12N\n\x1a\x64ownload_artifact_response\x18\x1f \x01(\x0b\x32(.wandb_internal.DownloadArtifactResponseH\x00\x12H\n\x17server_feature_response\x18 \x01(\x0b\x32%.wandb_internal.ServerFeatureResponseH\x00\x12@\n\x13run_status_response\x18# \x01(\x0b\x32!.wandb_internal.RunStatusResponseH\x00\x12\x39\n\x0f\x63\x61ncel_response\x18$ \x01(\x0b\x32\x1e.wandb_internal.CancelResponseH\x00\x12N\n\x1ainternal_messages_response\x18% \x01(\x0b\x32(.wandb_internal.InternalMessagesResponseH\x00\x12=\n\x11shutdown_response\x18@ \x01(\x0b\x32 .wandb_internal.ShutdownResponseH\x00\x12\x39\n\x0f\x61ttach_response\x18\x41 \x01(\x0b\x32\x1e.wandb_internal.AttachResponseH\x00\x12\x39\n\x0fstatus_response\x18\x42 \x01(\x0b\x32\x1e.wandb_internal.StatusResponseH\x00\x12\x42\n\x14server_info_response\x18\x43 \x01(\x0b\x32\".wandb_internal.ServerInfoResponseH\x00\x12<\n\x11job_info_response\x18\x44 \x01(\x0b\x32\x1f.wandb_internal.JobInfoResponseH\x00\x12O\n\x1bget_system_metrics_response\x18\x45 \x01(\x0b\x32(.wandb_internal.GetSystemMetricsResponseH\x00\x12\x46\n\x16link_artifact_response\x18G \x01(\x0b\x32$.wandb_internal.LinkArtifactResponseH\x00\x12\x35\n\rsync_response\x18\x46 \x01(\x0b\x32\x1c.wandb_internal.SyncResponseH\x00\x12X\n run_finish_without_exit_response\x18H \x01(\x0b\x32,.wandb_internal.RunFinishWithoutExitResponseH\x00\x12\x45\n\x13operations_response\x18J \x01(\x0b\x32&.wandb_internal.OperationStatsResponseH\x00\x12\x33\n\x0c\x61pi_response\x18T \x01(\x0b\x32\x1b.wandb_internal.ApiResponseH\x00\x12\x43\n\x14test_inject_response\x18\xe8\x07 \x01(\x0b\x32\".wandb_internal.TestInjectResponseH\x00\x42\x0f\n\rresponse_typeJ\x04\x08I\x10J\"\xc0\x02\n\x0c\x44\x65\x66\x65rRequest\x12\x36\n\x05state\x18\x01 \x01(\x0e\x32\'.wandb_internal.DeferRequest.DeferState\"\xf7\x01\n\nDeferState\x12\t\n\x05\x42\x45GIN\x10\x00\x12\r\n\tFLUSH_RUN\x10\x01\x12\x0f\n\x0b\x46LUSH_STATS\x10\x02\x12\x19\n\x15\x46LUSH_PARTIAL_HISTORY\x10\x03\x12\x0c\n\x08\x46LUSH_TB\x10\x04\x12\r\n\tFLUSH_SUM\x10\x05\x12\x13\n\x0f\x46LUSH_DEBOUNCER\x10\x06\x12\x10\n\x0c\x46LUSH_OUTPUT\x10\x07\x12\r\n\tFLUSH_JOB\x10\x08\x12\r\n\tFLUSH_DIR\x10\t\x12\x0c\n\x08\x46LUSH_FP\x10\n\x12\x0b\n\x07JOIN_FP\x10\x0b\x12\x0c\n\x08\x46LUSH_FS\x10\x0c\x12\x0f\n\x0b\x46LUSH_FINAL\x10\r\x12\x07\n\x03\x45ND\x10\x0e\"<\n\x0cPauseRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x0f\n\rPauseResponse\"=\n\rResumeRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x10\n\x0eResumeResponse\"M\n\x0cLoginRequest\x12\x0f\n\x07\x61pi_key\x18\x01 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"&\n\rLoginResponse\x12\x15\n\ractive_entity\x18\x01 \x01(\t\"A\n\x11GetSummaryRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"?\n\x12GetSummaryResponse\x12)\n\x04item\x18\x01 \x03(\x0b\x32\x1b.wandb_internal.SummaryItem\"G\n\x17GetSystemMetricsRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"R\n\x12SystemMetricSample\x12-\n\ttimestamp\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\r\n\x05value\x18\x02 \x01(\x02\"I\n\x13SystemMetricsBuffer\x12\x32\n\x06record\x18\x01 \x03(\x0b\x32\".wandb_internal.SystemMetricSample\"\xca\x01\n\x18GetSystemMetricsResponse\x12S\n\x0esystem_metrics\x18\x01 \x03(\x0b\x32;.wandb_internal.GetSystemMetricsResponse.SystemMetricsEntry\x1aY\n\x12SystemMetricsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x32\n\x05value\x18\x02 \x01(\x0b\x32#.wandb_internal.SystemMetricsBuffer:\x02\x38\x01\"=\n\rStatusRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\")\n\x0eStatusResponse\x12\x17\n\x0frun_should_stop\x18\x01 \x01(\x08\"A\n\x11StopStatusRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"-\n\x12StopStatusResponse\x12\x17\n\x0frun_should_stop\x18\x01 \x01(\x08\"D\n\x14NetworkStatusRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"P\n\x15NetworkStatusResponse\x12\x37\n\x11network_responses\x18\x01 \x03(\x0b\x32\x1c.wandb_internal.HttpResponse\"D\n\x0cHttpResponse\x12\x18\n\x10http_status_code\x18\x01 \x01(\x05\x12\x1a\n\x12http_response_text\x18\x02 \x01(\t\"G\n\x17InternalMessagesRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"N\n\x18InternalMessagesResponse\x12\x32\n\x08messages\x18\x01 \x01(\x0b\x32 .wandb_internal.InternalMessages\"#\n\x10InternalMessages\x12\x0f\n\x07warning\x18\x01 \x03(\t\"?\n\x0fPollExitRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\xf5\x01\n\x10PollExitResponse\x12\x0c\n\x04\x64one\x18\x01 \x01(\x08\x12\x32\n\x0b\x65xit_result\x18\x02 \x01(\x0b\x32\x1d.wandb_internal.RunExitResult\x12\x35\n\x0cpusher_stats\x18\x03 \x01(\x0b\x32\x1f.wandb_internal.FilePusherStats\x12/\n\x0b\x66ile_counts\x18\x04 \x01(\x0b\x32\x1a.wandb_internal.FileCounts\x12\x37\n\x0foperation_stats\x18\x05 \x01(\x0b\x32\x1e.wandb_internal.OperationStats\"E\n\x15OperationStatsRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"Q\n\x16OperationStatsResponse\x12\x37\n\x0foperation_stats\x18\x01 \x01(\x0b\x32\x1e.wandb_internal.OperationStats\"Y\n\x0eOperationStats\x12-\n\noperations\x18\x01 \x03(\x0b\x32\x19.wandb_internal.Operation\x12\x18\n\x10total_operations\x18\x02 \x01(\x03\"\x87\x01\n\tOperation\x12\x0c\n\x04\x64\x65sc\x18\x01 \x01(\t\x12\x17\n\x0fruntime_seconds\x18\x02 \x01(\x01\x12\x10\n\x08progress\x18\x03 \x01(\t\x12\x14\n\x0c\x65rror_status\x18\x04 \x01(\t\x12+\n\x08subtasks\x18\x05 \x03(\x0b\x32\x19.wandb_internal.Operation\"\x13\n\x11SenderMarkRequest\"\x13\n\x11SyncFinishRequest\"E\n\x0cSyncResponse\x12\x0b\n\x03url\x18\x01 \x01(\t\x12(\n\x05\x65rror\x18\x02 \x01(\x0b\x32\x19.wandb_internal.ErrorInfo\"?\n\x11SenderReadRequest\x12\x14\n\x0cstart_offset\x18\x01 \x01(\x03\x12\x14\n\x0c\x66inal_offset\x18\x02 \x01(\x03\"m\n\x13StatusReportRequest\x12\x12\n\nrecord_num\x18\x01 \x01(\x03\x12\x13\n\x0bsent_offset\x18\x02 \x01(\x03\x12-\n\tsync_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"F\n\x14SummaryRecordRequest\x12.\n\x07summary\x18\x01 \x01(\x0b\x32\x1d.wandb_internal.SummaryRecord\"L\n\x16TelemetryRecordRequest\x12\x32\n\ttelemetry\x18\x01 \x01(\x0b\x32\x1f.wandb_internal.TelemetryRecord\"A\n\x11ServerInfoRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"|\n\x12ServerInfoResponse\x12-\n\nlocal_info\x18\x01 \x01(\x0b\x32\x19.wandb_internal.LocalInfo\x12\x37\n\x0fserver_messages\x18\x02 \x01(\x0b\x32\x1e.wandb_internal.ServerMessages\"=\n\x0eServerMessages\x12+\n\x04item\x18\x01 \x03(\x0b\x32\x1d.wandb_internal.ServerMessage\"e\n\rServerMessage\x12\x12\n\nplain_text\x18\x01 \x01(\t\x12\x10\n\x08utf_text\x18\x02 \x01(\t\x12\x11\n\thtml_text\x18\x03 \x01(\t\x12\x0c\n\x04type\x18\x04 \x01(\t\x12\r\n\x05level\x18\x05 \x01(\x05\"c\n\nFileCounts\x12\x13\n\x0bwandb_count\x18\x01 \x01(\x05\x12\x13\n\x0bmedia_count\x18\x02 \x01(\x05\x12\x16\n\x0e\x61rtifact_count\x18\x03 \x01(\x05\x12\x13\n\x0bother_count\x18\x04 \x01(\x05\"U\n\x0f\x46ilePusherStats\x12\x16\n\x0euploaded_bytes\x18\x01 \x01(\x03\x12\x13\n\x0btotal_bytes\x18\x02 \x01(\x03\x12\x15\n\rdeduped_bytes\x18\x03 \x01(\x03\"\x1e\n\rFilesUploaded\x12\r\n\x05\x66iles\x18\x01 \x03(\t\"\xf4\x01\n\x17\x46ileTransferInfoRequest\x12\x42\n\x04type\x18\x01 \x01(\x0e\x32\x34.wandb_internal.FileTransferInfoRequest.TransferType\x12\x0c\n\x04path\x18\x02 \x01(\t\x12\x0b\n\x03url\x18\x03 \x01(\t\x12\x0c\n\x04size\x18\x04 \x01(\x03\x12\x11\n\tprocessed\x18\x05 \x01(\x03\x12/\n\x0b\x66ile_counts\x18\x06 \x01(\x0b\x32\x1a.wandb_internal.FileCounts\"(\n\x0cTransferType\x12\n\n\x06Upload\x10\x00\x12\x0c\n\x08\x44ownload\x10\x01\"1\n\tLocalInfo\x12\x0f\n\x07version\x18\x01 \x01(\t\x12\x13\n\x0bout_of_date\x18\x02 \x01(\x08\"?\n\x0fShutdownRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x12\n\x10ShutdownResponse\"P\n\rAttachRequest\x12\x11\n\tattach_id\x18\x14 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"b\n\x0e\x41ttachResponse\x12&\n\x03run\x18\x01 \x01(\x0b\x32\x19.wandb_internal.RunRecord\x12(\n\x05\x65rror\x18\x02 \x01(\x0b\x32\x19.wandb_internal.ErrorInfo\"\xd5\x02\n\x11TestInjectRequest\x12\x13\n\x0bhandler_exc\x18\x01 \x01(\x08\x12\x14\n\x0chandler_exit\x18\x02 \x01(\x08\x12\x15\n\rhandler_abort\x18\x03 \x01(\x08\x12\x12\n\nsender_exc\x18\x04 \x01(\x08\x12\x13\n\x0bsender_exit\x18\x05 \x01(\x08\x12\x14\n\x0csender_abort\x18\x06 \x01(\x08\x12\x0f\n\x07req_exc\x18\x07 \x01(\x08\x12\x10\n\x08req_exit\x18\x08 \x01(\x08\x12\x11\n\treq_abort\x18\t \x01(\x08\x12\x10\n\x08resp_exc\x18\n \x01(\x08\x12\x11\n\tresp_exit\x18\x0b \x01(\x08\x12\x12\n\nresp_abort\x18\x0c \x01(\x08\x12\x10\n\x08msg_drop\x18\r \x01(\x08\x12\x10\n\x08msg_hang\x18\x0e \x01(\x08\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x14\n\x12TestInjectResponse\"\x1e\n\rHistoryAction\x12\r\n\x05\x66lush\x18\x01 \x01(\x08\"\xca\x01\n\x15PartialHistoryRequest\x12)\n\x04item\x18\x01 \x03(\x0b\x32\x1b.wandb_internal.HistoryItem\x12)\n\x04step\x18\x02 \x01(\x0b\x32\x1b.wandb_internal.HistoryStep\x12-\n\x06\x61\x63tion\x18\x03 \x01(\x0b\x32\x1d.wandb_internal.HistoryAction\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x18\n\x16PartialHistoryResponse\"E\n\x15SampledHistoryRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"_\n\x12SampledHistoryItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nnested_key\x18\x02 \x03(\t\x12\x14\n\x0cvalues_float\x18\x03 \x03(\x02\x12\x12\n\nvalues_int\x18\x04 \x03(\x03\"J\n\x16SampledHistoryResponse\x12\x30\n\x04item\x18\x01 \x03(\x0b\x32\".wandb_internal.SampledHistoryItem\"@\n\x10RunStatusRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"x\n\x11RunStatusResponse\x12\x18\n\x10sync_items_total\x18\x01 \x01(\x03\x12\x1a\n\x12sync_items_pending\x18\x02 \x01(\x03\x12-\n\tsync_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"g\n\x0fRunStartRequest\x12&\n\x03run\x18\x01 \x01(\x0b\x32\x19.wandb_internal.RunRecord\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x12\n\x10RunStartResponse\"K\n\x1bRunFinishWithoutExitRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x1e\n\x1cRunFinishWithoutExitResponse\"\\\n\x13\x43heckVersionRequest\x12\x17\n\x0f\x63urrent_version\x18\x01 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"]\n\x14\x43heckVersionResponse\x12\x17\n\x0fupgrade_message\x18\x01 \x01(\t\x12\x14\n\x0cyank_message\x18\x02 \x01(\t\x12\x16\n\x0e\x64\x65lete_message\x18\x03 \x01(\t\">\n\x0eJobInfoRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"6\n\x0fJobInfoResponse\x12\x12\n\nsequenceId\x18\x01 \x01(\t\x12\x0f\n\x07version\x18\x02 \x01(\t\"\x9f\x01\n\x12LogArtifactRequest\x12\x30\n\x08\x61rtifact\x18\x01 \x01(\x0b\x32\x1e.wandb_internal.ArtifactRecord\x12\x14\n\x0chistory_step\x18\x02 \x01(\x03\x12\x13\n\x0bstaging_dir\x18\x03 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"A\n\x13LogArtifactResponse\x12\x13\n\x0b\x61rtifact_id\x18\x01 \x01(\t\x12\x15\n\rerror_message\x18\x02 \x01(\t\"\xbe\x01\n\x17\x44ownloadArtifactRequest\x12\x13\n\x0b\x61rtifact_id\x18\x01 \x01(\t\x12\x15\n\rdownload_root\x18\x02 \x01(\t\x12 \n\x18\x61llow_missing_references\x18\x04 \x01(\x08\x12\x12\n\nskip_cache\x18\x05 \x01(\x08\x12\x13\n\x0bpath_prefix\x18\x06 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"1\n\x18\x44ownloadArtifactResponse\x12\x15\n\rerror_message\x18\x01 \x01(\t\"@\n\x10KeepaliveRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x13\n\x11KeepaliveResponse\"q\n\x0c\x41rtifactInfo\x12\x10\n\x08\x61rtifact\x18\x01 \x01(\t\x12\x12\n\nentrypoint\x18\x02 \x03(\t\x12\x10\n\x08notebook\x18\x03 \x01(\x08\x12\x15\n\rbuild_context\x18\x04 \x01(\t\x12\x12\n\ndockerfile\x18\x05 \x01(\t\")\n\x07GitInfo\x12\x0e\n\x06remote\x18\x01 \x01(\t\x12\x0e\n\x06\x63ommit\x18\x02 \x01(\t\"\x87\x01\n\tGitSource\x12)\n\x08git_info\x18\x01 \x01(\x0b\x32\x17.wandb_internal.GitInfo\x12\x12\n\nentrypoint\x18\x02 \x03(\t\x12\x10\n\x08notebook\x18\x03 \x01(\x08\x12\x15\n\rbuild_context\x18\x04 \x01(\t\x12\x12\n\ndockerfile\x18\x05 \x01(\t\"\x1c\n\x0bImageSource\x12\r\n\x05image\x18\x01 \x01(\t\"\x8c\x01\n\x06Source\x12&\n\x03git\x18\x01 \x01(\x0b\x32\x19.wandb_internal.GitSource\x12.\n\x08\x61rtifact\x18\x02 \x01(\x0b\x32\x1c.wandb_internal.ArtifactInfo\x12*\n\x05image\x18\x03 \x01(\x0b\x32\x1b.wandb_internal.ImageSource\"k\n\tJobSource\x12\x10\n\x08_version\x18\x01 \x01(\t\x12\x13\n\x0bsource_type\x18\x02 \x01(\t\x12&\n\x06source\x18\x03 \x01(\x0b\x32\x16.wandb_internal.Source\x12\x0f\n\x07runtime\x18\x04 \x01(\t\"V\n\x12PartialJobArtifact\x12\x10\n\x08job_name\x18\x01 \x01(\t\x12.\n\x0bsource_info\x18\x02 \x01(\x0b\x32\x19.wandb_internal.JobSource\"\x9d\x01\n\x11UseArtifactRecord\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0c\n\x04type\x18\x02 \x01(\t\x12\x0c\n\x04name\x18\x03 \x01(\t\x12\x33\n\x07partial\x18\x04 \x01(\x0b\x32\".wandb_internal.PartialJobArtifact\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x13\n\x11UseArtifactResult\"R\n\rCancelRequest\x12\x13\n\x0b\x63\x61ncel_slot\x18\x01 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x10\n\x0e\x43\x61ncelResponse\"\x18\n\x16ProbeSystemInfoRequest\"\'\n\x08\x44iskInfo\x12\r\n\x05total\x18\x01 \x01(\x04\x12\x0c\n\x04used\x18\x02 \x01(\x04\"\x1b\n\nMemoryInfo\x12\r\n\x05total\x18\x01 \x01(\x04\"/\n\x07\x43puInfo\x12\r\n\x05\x63ount\x18\x01 \x01(\r\x12\x15\n\rcount_logical\x18\x02 \x01(\r\"\x9a\x01\n\tAppleInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\necpu_cores\x18\x02 \x01(\r\x12\x12\n\npcpu_cores\x18\x03 \x01(\r\x12\x11\n\tgpu_cores\x18\x04 \x01(\r\x12\x11\n\tmemory_gb\x18\x05 \x01(\r\x12\x18\n\x10swap_total_bytes\x18\x06 \x01(\x04\x12\x17\n\x0fram_total_bytes\x18\x07 \x01(\x04\"k\n\rGpuNvidiaInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0cmemory_total\x18\x02 \x01(\x04\x12\x12\n\ncuda_cores\x18\x03 \x01(\r\x12\x14\n\x0c\x61rchitecture\x18\x04 \x01(\t\x12\x0c\n\x04uuid\x18\x05 \x01(\t\"\x89\x02\n\nGpuAmdInfo\x12\n\n\x02id\x18\x01 \x01(\t\x12\x11\n\tunique_id\x18\x02 \x01(\t\x12\x15\n\rvbios_version\x18\x03 \x01(\t\x12\x19\n\x11performance_level\x18\x04 \x01(\t\x12\x15\n\rgpu_overdrive\x18\x05 \x01(\t\x12\x1c\n\x14gpu_memory_overdrive\x18\x06 \x01(\t\x12\x11\n\tmax_power\x18\x07 \x01(\t\x12\x0e\n\x06series\x18\x08 \x01(\t\x12\r\n\x05model\x18\t \x01(\t\x12\x0e\n\x06vendor\x18\n \x01(\t\x12\x0b\n\x03sku\x18\x0b \x01(\t\x12\x12\n\nsclk_range\x18\x0c \x01(\t\x12\x12\n\nmclk_range\x18\r \x01(\t\"n\n\x0cTrainiumInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06vendor\x18\x02 \x01(\t\x12\x1b\n\x13neuron_device_count\x18\x03 \x01(\r\x12#\n\x1bneuroncore_per_device_count\x18\x04 \x01(\r\"Q\n\x07TPUInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07hbm_gib\x18\x02 \x01(\r\x12\x18\n\x10\x64\x65vices_per_chip\x18\x03 \x01(\r\x12\r\n\x05\x63ount\x18\x04 \x01(\r\"E\n\rCoreWeaveInfo\x12\x14\n\x0c\x63luster_name\x18\x01 \x01(\t\x12\x0e\n\x06org_id\x18\x02 \x01(\t\x12\x0e\n\x06region\x18\x03 \x01(\t\"\xa8\t\n\x11\x45nvironmentRecord\x12\n\n\x02os\x18\x01 \x01(\t\x12\x0e\n\x06python\x18\x02 \x01(\t\x12\x39\n\nstarted_at\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.TimestampR\tstartedAt\x12\x0e\n\x06\x64ocker\x18\x04 \x01(\t\x12\x0c\n\x04\x61rgs\x18\x05 \x03(\t\x12\x0f\n\x07program\x18\x06 \x01(\t\x12\x1b\n\tcode_path\x18\x07 \x01(\tR\x08\x63odePath\x12&\n\x0f\x63ode_path_local\x18\x08 \x01(\tR\rcodePathLocal\x12*\n\x03git\x18\t \x01(\x0b\x32\x1d.wandb_internal.GitRepoRecord\x12\r\n\x05\x65mail\x18\n \x01(\t\x12\x0c\n\x04root\x18\x0b \x01(\t\x12\x0c\n\x04host\x18\x0c \x01(\t\x12\x10\n\x08username\x18\r \x01(\t\x12\x12\n\nexecutable\x18\x0e \x01(\t\x12\r\n\x05\x63olab\x18\x0f \x01(\t\x12\x1c\n\tcpu_count\x18\x10 \x01(\rR\tcpu_count\x12,\n\x11\x63pu_count_logical\x18\x11 \x01(\rR\x11\x63pu_count_logical\x12\x15\n\x08gpu_type\x18\x12 \x01(\tR\x03gpu\x12\x1c\n\tgpu_count\x18\x13 \x01(\rR\tgpu_count\x12\x39\n\x04\x64isk\x18\x14 \x03(\x0b\x32+.wandb_internal.EnvironmentRecord.DiskEntry\x12*\n\x06memory\x18\x15 \x01(\x0b\x32\x1a.wandb_internal.MemoryInfo\x12$\n\x03\x63pu\x18\x16 \x01(\x0b\x32\x17.wandb_internal.CpuInfo\x12(\n\x05\x61pple\x18\x17 \x01(\x0b\x32\x19.wandb_internal.AppleInfo\x12=\n\ngpu_nvidia\x18\x18 \x03(\x0b\x32\x1d.wandb_internal.GpuNvidiaInfoR\ngpu_nvidia\x12\x14\n\x0c\x63uda_version\x18\x19 \x01(\t\x12\x34\n\x07gpu_amd\x18\x1a \x03(\x0b\x32\x1a.wandb_internal.GpuAmdInfoR\x07gpu_amd\x12;\n\x05slurm\x18\x1b \x03(\x0b\x32,.wandb_internal.EnvironmentRecord.SlurmEntry\x12.\n\x08trainium\x18\x1c \x01(\x0b\x32\x1c.wandb_internal.TrainiumInfo\x12$\n\x03tpu\x18\x1d \x01(\x0b\x32\x17.wandb_internal.TPUInfo\x12\x30\n\tcoreweave\x18\x1e \x01(\x0b\x32\x1d.wandb_internal.CoreWeaveInfo\x12\x12\n\twriter_id\x18\xc7\x01 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\x1a\x45\n\tDiskEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\'\n\x05value\x18\x02 \x01(\x0b\x32\x18.wandb_internal.DiskInfo:\x02\x38\x01\x1a,\n\nSlurmEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x8d\x01\n\x15PythonPackagesRequest\x12\x44\n\x07package\x18\x01 \x03(\x0b\x32\x33.wandb_internal.PythonPackagesRequest.PythonPackage\x1a.\n\rPythonPackage\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07version\x18\x02 \x01(\t\"\x1c\n\x0cJobInputPath\x12\x0c\n\x04path\x18\x01 \x03(\t\"\xd6\x01\n\x0eJobInputSource\x12\x44\n\nrun_config\x18\x01 \x01(\x0b\x32..wandb_internal.JobInputSource.RunConfigSourceH\x00\x12?\n\x04\x66ile\x18\x02 \x01(\x0b\x32/.wandb_internal.JobInputSource.ConfigFileSourceH\x00\x1a\x11\n\x0fRunConfigSource\x1a \n\x10\x43onfigFileSource\x12\x0c\n\x04path\x18\x01 \x01(\tB\x08\n\x06source\"\xc7\x01\n\x0fJobInputRequest\x12\x34\n\x0cinput_source\x18\x01 \x01(\x0b\x32\x1e.wandb_internal.JobInputSource\x12\x33\n\rinclude_paths\x18\x02 \x03(\x0b\x32\x1c.wandb_internal.JobInputPath\x12\x33\n\rexclude_paths\x18\x03 \x03(\x0b\x32\x1c.wandb_internal.JobInputPath\x12\x14\n\x0cinput_schema\x18\x04 \x01(\t\"t\n\x14ServerFeatureRequest\x12.\n\x07\x66\x65\x61ture\x18\x01 \x01(\x0e\x32\x1d.wandb_internal.ServerFeature\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"K\n\x15ServerFeatureResponse\x12\x32\n\x07\x66\x65\x61ture\x18\x01 \x01(\x0b\x32!.wandb_internal.ServerFeatureItem\"2\n\x11ServerFeatureItem\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07\x65nabled\x18\x02 \x01(\x08*\xb3\x04\n\rServerFeature\x12\x13\n\x0fLARGE_FILENAMES\x10\x00\x12\x11\n\rARTIFACT_TAGS\x10\x01\x12\x0e\n\nCLIENT_IDS\x10\x02\x12\x1c\n\x18\x41RTIFACT_REGISTRY_SEARCH\x10\x03\x12\x1b\n\x17STRUCTURED_CONSOLE_LOGS\x10\x04\x12(\n$ARTIFACT_COLLECTION_MEMBERSHIP_FILES\x10\x05\x12\x38\n4ARTIFACT_COLLECTION_MEMBERSHIP_FILE_DOWNLOAD_HANDLER\x10\x06\x12\x34\n0USE_ARTIFACT_WITH_ENTITY_AND_PROJECT_INFORMATION\x10\x07\x12\x1f\n\x1b\x45XPAND_DEFINED_METRIC_GLOBS\x10\x08\x12\x1f\n\x1b\x41UTOMATION_EVENT_RUN_METRIC\x10\t\x12&\n\"AUTOMATION_EVENT_RUN_METRIC_CHANGE\x10\n\x12\x1b\n\x17\x41UTOMATION_ACTION_NO_OP\x10\x0b\x12/\n+INCLUDE_ARTIFACT_TYPES_IN_REGISTRY_CREATION\x10\x0c\x12*\n&PROJECT_ARTIFACT_COLLECTION_MEMBERSHIP\x10\r\x12\x31\n-ARTIFACT_MEMBERSHIP_IN_LINK_ARTIFACT_RESPONSE\x10\x0e\x42\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_SERVERFEATURE = DESCRIPTOR.enum_types_by_name['ServerFeature']
+ServerFeature = enum_type_wrapper.EnumTypeWrapper(_SERVERFEATURE)
+LARGE_FILENAMES = 0
+ARTIFACT_TAGS = 1
+CLIENT_IDS = 2
+ARTIFACT_REGISTRY_SEARCH = 3
+STRUCTURED_CONSOLE_LOGS = 4
+ARTIFACT_COLLECTION_MEMBERSHIP_FILES = 5
+ARTIFACT_COLLECTION_MEMBERSHIP_FILE_DOWNLOAD_HANDLER = 6
+USE_ARTIFACT_WITH_ENTITY_AND_PROJECT_INFORMATION = 7
+EXPAND_DEFINED_METRIC_GLOBS = 8
+AUTOMATION_EVENT_RUN_METRIC = 9
+AUTOMATION_EVENT_RUN_METRIC_CHANGE = 10
+AUTOMATION_ACTION_NO_OP = 11
+INCLUDE_ARTIFACT_TYPES_IN_REGISTRY_CREATION = 12
+PROJECT_ARTIFACT_COLLECTION_MEMBERSHIP = 13
+ARTIFACT_MEMBERSHIP_IN_LINK_ARTIFACT_RESPONSE = 14
+
+
+_RECORD = DESCRIPTOR.message_types_by_name['Record']
+_CONTROL = DESCRIPTOR.message_types_by_name['Control']
+_RESULT = DESCRIPTOR.message_types_by_name['Result']
+_FINALRECORD = DESCRIPTOR.message_types_by_name['FinalRecord']
+_VERSIONINFO = DESCRIPTOR.message_types_by_name['VersionInfo']
+_HEADERRECORD = DESCRIPTOR.message_types_by_name['HeaderRecord']
+_FOOTERRECORD = DESCRIPTOR.message_types_by_name['FooterRecord']
+_BRANCHPOINT = DESCRIPTOR.message_types_by_name['BranchPoint']
+_RUNRECORD = DESCRIPTOR.message_types_by_name['RunRecord']
+_GITREPORECORD = DESCRIPTOR.message_types_by_name['GitRepoRecord']
+_RUNUPDATERESULT = DESCRIPTOR.message_types_by_name['RunUpdateResult']
+_ERRORINFO = DESCRIPTOR.message_types_by_name['ErrorInfo']
+_RUNEXITRECORD = DESCRIPTOR.message_types_by_name['RunExitRecord']
+_RUNEXITRESULT = DESCRIPTOR.message_types_by_name['RunExitResult']
+_RUNPREEMPTINGRECORD = DESCRIPTOR.message_types_by_name['RunPreemptingRecord']
+_RUNPREEMPTINGRESULT = DESCRIPTOR.message_types_by_name['RunPreemptingResult']
+_SETTINGSRECORD = DESCRIPTOR.message_types_by_name['SettingsRecord']
+_SETTINGSITEM = DESCRIPTOR.message_types_by_name['SettingsItem']
+_HISTORYSTEP = DESCRIPTOR.message_types_by_name['HistoryStep']
+_HISTORYRECORD = DESCRIPTOR.message_types_by_name['HistoryRecord']
+_HISTORYITEM = DESCRIPTOR.message_types_by_name['HistoryItem']
+_HISTORYRESULT = DESCRIPTOR.message_types_by_name['HistoryResult']
+_OUTPUTRECORD = DESCRIPTOR.message_types_by_name['OutputRecord']
+_OUTPUTRESULT = DESCRIPTOR.message_types_by_name['OutputResult']
+_OUTPUTRAWRECORD = DESCRIPTOR.message_types_by_name['OutputRawRecord']
+_OUTPUTRAWRESULT = DESCRIPTOR.message_types_by_name['OutputRawResult']
+_METRICRECORD = DESCRIPTOR.message_types_by_name['MetricRecord']
+_METRICRESULT = DESCRIPTOR.message_types_by_name['MetricResult']
+_METRICOPTIONS = DESCRIPTOR.message_types_by_name['MetricOptions']
+_METRICCONTROL = DESCRIPTOR.message_types_by_name['MetricControl']
+_METRICSUMMARY = DESCRIPTOR.message_types_by_name['MetricSummary']
+_CONFIGRECORD = DESCRIPTOR.message_types_by_name['ConfigRecord']
+_CONFIGITEM = DESCRIPTOR.message_types_by_name['ConfigItem']
+_CONFIGRESULT = DESCRIPTOR.message_types_by_name['ConfigResult']
+_SUMMARYRECORD = DESCRIPTOR.message_types_by_name['SummaryRecord']
+_SUMMARYITEM = DESCRIPTOR.message_types_by_name['SummaryItem']
+_SUMMARYRESULT = DESCRIPTOR.message_types_by_name['SummaryResult']
+_FILESRECORD = DESCRIPTOR.message_types_by_name['FilesRecord']
+_FILESITEM = DESCRIPTOR.message_types_by_name['FilesItem']
+_FILESRESULT = DESCRIPTOR.message_types_by_name['FilesResult']
+_STATSRECORD = DESCRIPTOR.message_types_by_name['StatsRecord']
+_STATSITEM = DESCRIPTOR.message_types_by_name['StatsItem']
+_ARTIFACTRECORD = DESCRIPTOR.message_types_by_name['ArtifactRecord']
+_ARTIFACTMANIFEST = DESCRIPTOR.message_types_by_name['ArtifactManifest']
+_ARTIFACTMANIFESTENTRY = DESCRIPTOR.message_types_by_name['ArtifactManifestEntry']
+_EXTRAITEM = DESCRIPTOR.message_types_by_name['ExtraItem']
+_STORAGEPOLICYCONFIGITEM = DESCRIPTOR.message_types_by_name['StoragePolicyConfigItem']
+_ARTIFACTRESULT = DESCRIPTOR.message_types_by_name['ArtifactResult']
+_LINKARTIFACTRESULT = DESCRIPTOR.message_types_by_name['LinkArtifactResult']
+_LINKARTIFACTREQUEST = DESCRIPTOR.message_types_by_name['LinkArtifactRequest']
+_LINKARTIFACTRESPONSE = DESCRIPTOR.message_types_by_name['LinkArtifactResponse']
+_TBRECORD = DESCRIPTOR.message_types_by_name['TBRecord']
+_TBRESULT = DESCRIPTOR.message_types_by_name['TBResult']
+_ALERTRECORD = DESCRIPTOR.message_types_by_name['AlertRecord']
+_ALERTRESULT = DESCRIPTOR.message_types_by_name['AlertResult']
+_REQUEST = DESCRIPTOR.message_types_by_name['Request']
+_RESPONSE = DESCRIPTOR.message_types_by_name['Response']
+_DEFERREQUEST = DESCRIPTOR.message_types_by_name['DeferRequest']
+_PAUSEREQUEST = DESCRIPTOR.message_types_by_name['PauseRequest']
+_PAUSERESPONSE = DESCRIPTOR.message_types_by_name['PauseResponse']
+_RESUMEREQUEST = DESCRIPTOR.message_types_by_name['ResumeRequest']
+_RESUMERESPONSE = DESCRIPTOR.message_types_by_name['ResumeResponse']
+_LOGINREQUEST = DESCRIPTOR.message_types_by_name['LoginRequest']
+_LOGINRESPONSE = DESCRIPTOR.message_types_by_name['LoginResponse']
+_GETSUMMARYREQUEST = DESCRIPTOR.message_types_by_name['GetSummaryRequest']
+_GETSUMMARYRESPONSE = DESCRIPTOR.message_types_by_name['GetSummaryResponse']
+_GETSYSTEMMETRICSREQUEST = DESCRIPTOR.message_types_by_name['GetSystemMetricsRequest']
+_SYSTEMMETRICSAMPLE = DESCRIPTOR.message_types_by_name['SystemMetricSample']
+_SYSTEMMETRICSBUFFER = DESCRIPTOR.message_types_by_name['SystemMetricsBuffer']
+_GETSYSTEMMETRICSRESPONSE = DESCRIPTOR.message_types_by_name['GetSystemMetricsResponse']
+_GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY = _GETSYSTEMMETRICSRESPONSE.nested_types_by_name['SystemMetricsEntry']
+_STATUSREQUEST = DESCRIPTOR.message_types_by_name['StatusRequest']
+_STATUSRESPONSE = DESCRIPTOR.message_types_by_name['StatusResponse']
+_STOPSTATUSREQUEST = DESCRIPTOR.message_types_by_name['StopStatusRequest']
+_STOPSTATUSRESPONSE = DESCRIPTOR.message_types_by_name['StopStatusResponse']
+_NETWORKSTATUSREQUEST = DESCRIPTOR.message_types_by_name['NetworkStatusRequest']
+_NETWORKSTATUSRESPONSE = DESCRIPTOR.message_types_by_name['NetworkStatusResponse']
+_HTTPRESPONSE = DESCRIPTOR.message_types_by_name['HttpResponse']
+_INTERNALMESSAGESREQUEST = DESCRIPTOR.message_types_by_name['InternalMessagesRequest']
+_INTERNALMESSAGESRESPONSE = DESCRIPTOR.message_types_by_name['InternalMessagesResponse']
+_INTERNALMESSAGES = DESCRIPTOR.message_types_by_name['InternalMessages']
+_POLLEXITREQUEST = DESCRIPTOR.message_types_by_name['PollExitRequest']
+_POLLEXITRESPONSE = DESCRIPTOR.message_types_by_name['PollExitResponse']
+_OPERATIONSTATSREQUEST = DESCRIPTOR.message_types_by_name['OperationStatsRequest']
+_OPERATIONSTATSRESPONSE = DESCRIPTOR.message_types_by_name['OperationStatsResponse']
+_OPERATIONSTATS = DESCRIPTOR.message_types_by_name['OperationStats']
+_OPERATION = DESCRIPTOR.message_types_by_name['Operation']
+_SENDERMARKREQUEST = DESCRIPTOR.message_types_by_name['SenderMarkRequest']
+_SYNCFINISHREQUEST = DESCRIPTOR.message_types_by_name['SyncFinishRequest']
+_SYNCRESPONSE = DESCRIPTOR.message_types_by_name['SyncResponse']
+_SENDERREADREQUEST = DESCRIPTOR.message_types_by_name['SenderReadRequest']
+_STATUSREPORTREQUEST = DESCRIPTOR.message_types_by_name['StatusReportRequest']
+_SUMMARYRECORDREQUEST = DESCRIPTOR.message_types_by_name['SummaryRecordRequest']
+_TELEMETRYRECORDREQUEST = DESCRIPTOR.message_types_by_name['TelemetryRecordRequest']
+_SERVERINFOREQUEST = DESCRIPTOR.message_types_by_name['ServerInfoRequest']
+_SERVERINFORESPONSE = DESCRIPTOR.message_types_by_name['ServerInfoResponse']
+_SERVERMESSAGES = DESCRIPTOR.message_types_by_name['ServerMessages']
+_SERVERMESSAGE = DESCRIPTOR.message_types_by_name['ServerMessage']
+_FILECOUNTS = DESCRIPTOR.message_types_by_name['FileCounts']
+_FILEPUSHERSTATS = DESCRIPTOR.message_types_by_name['FilePusherStats']
+_FILESUPLOADED = DESCRIPTOR.message_types_by_name['FilesUploaded']
+_FILETRANSFERINFOREQUEST = DESCRIPTOR.message_types_by_name['FileTransferInfoRequest']
+_LOCALINFO = DESCRIPTOR.message_types_by_name['LocalInfo']
+_SHUTDOWNREQUEST = DESCRIPTOR.message_types_by_name['ShutdownRequest']
+_SHUTDOWNRESPONSE = DESCRIPTOR.message_types_by_name['ShutdownResponse']
+_ATTACHREQUEST = DESCRIPTOR.message_types_by_name['AttachRequest']
+_ATTACHRESPONSE = DESCRIPTOR.message_types_by_name['AttachResponse']
+_TESTINJECTREQUEST = DESCRIPTOR.message_types_by_name['TestInjectRequest']
+_TESTINJECTRESPONSE = DESCRIPTOR.message_types_by_name['TestInjectResponse']
+_HISTORYACTION = DESCRIPTOR.message_types_by_name['HistoryAction']
+_PARTIALHISTORYREQUEST = DESCRIPTOR.message_types_by_name['PartialHistoryRequest']
+_PARTIALHISTORYRESPONSE = DESCRIPTOR.message_types_by_name['PartialHistoryResponse']
+_SAMPLEDHISTORYREQUEST = DESCRIPTOR.message_types_by_name['SampledHistoryRequest']
+_SAMPLEDHISTORYITEM = DESCRIPTOR.message_types_by_name['SampledHistoryItem']
+_SAMPLEDHISTORYRESPONSE = DESCRIPTOR.message_types_by_name['SampledHistoryResponse']
+_RUNSTATUSREQUEST = DESCRIPTOR.message_types_by_name['RunStatusRequest']
+_RUNSTATUSRESPONSE = DESCRIPTOR.message_types_by_name['RunStatusResponse']
+_RUNSTARTREQUEST = DESCRIPTOR.message_types_by_name['RunStartRequest']
+_RUNSTARTRESPONSE = DESCRIPTOR.message_types_by_name['RunStartResponse']
+_RUNFINISHWITHOUTEXITREQUEST = DESCRIPTOR.message_types_by_name['RunFinishWithoutExitRequest']
+_RUNFINISHWITHOUTEXITRESPONSE = DESCRIPTOR.message_types_by_name['RunFinishWithoutExitResponse']
+_CHECKVERSIONREQUEST = DESCRIPTOR.message_types_by_name['CheckVersionRequest']
+_CHECKVERSIONRESPONSE = DESCRIPTOR.message_types_by_name['CheckVersionResponse']
+_JOBINFOREQUEST = DESCRIPTOR.message_types_by_name['JobInfoRequest']
+_JOBINFORESPONSE = DESCRIPTOR.message_types_by_name['JobInfoResponse']
+_LOGARTIFACTREQUEST = DESCRIPTOR.message_types_by_name['LogArtifactRequest']
+_LOGARTIFACTRESPONSE = DESCRIPTOR.message_types_by_name['LogArtifactResponse']
+_DOWNLOADARTIFACTREQUEST = DESCRIPTOR.message_types_by_name['DownloadArtifactRequest']
+_DOWNLOADARTIFACTRESPONSE = DESCRIPTOR.message_types_by_name['DownloadArtifactResponse']
+_KEEPALIVEREQUEST = DESCRIPTOR.message_types_by_name['KeepaliveRequest']
+_KEEPALIVERESPONSE = DESCRIPTOR.message_types_by_name['KeepaliveResponse']
+_ARTIFACTINFO = DESCRIPTOR.message_types_by_name['ArtifactInfo']
+_GITINFO = DESCRIPTOR.message_types_by_name['GitInfo']
+_GITSOURCE = DESCRIPTOR.message_types_by_name['GitSource']
+_IMAGESOURCE = DESCRIPTOR.message_types_by_name['ImageSource']
+_SOURCE = DESCRIPTOR.message_types_by_name['Source']
+_JOBSOURCE = DESCRIPTOR.message_types_by_name['JobSource']
+_PARTIALJOBARTIFACT = DESCRIPTOR.message_types_by_name['PartialJobArtifact']
+_USEARTIFACTRECORD = DESCRIPTOR.message_types_by_name['UseArtifactRecord']
+_USEARTIFACTRESULT = DESCRIPTOR.message_types_by_name['UseArtifactResult']
+_CANCELREQUEST = DESCRIPTOR.message_types_by_name['CancelRequest']
+_CANCELRESPONSE = DESCRIPTOR.message_types_by_name['CancelResponse']
+_PROBESYSTEMINFOREQUEST = DESCRIPTOR.message_types_by_name['ProbeSystemInfoRequest']
+_DISKINFO = DESCRIPTOR.message_types_by_name['DiskInfo']
+_MEMORYINFO = DESCRIPTOR.message_types_by_name['MemoryInfo']
+_CPUINFO = DESCRIPTOR.message_types_by_name['CpuInfo']
+_APPLEINFO = DESCRIPTOR.message_types_by_name['AppleInfo']
+_GPUNVIDIAINFO = DESCRIPTOR.message_types_by_name['GpuNvidiaInfo']
+_GPUAMDINFO = DESCRIPTOR.message_types_by_name['GpuAmdInfo']
+_TRAINIUMINFO = DESCRIPTOR.message_types_by_name['TrainiumInfo']
+_TPUINFO = DESCRIPTOR.message_types_by_name['TPUInfo']
+_COREWEAVEINFO = DESCRIPTOR.message_types_by_name['CoreWeaveInfo']
+_ENVIRONMENTRECORD = DESCRIPTOR.message_types_by_name['EnvironmentRecord']
+_ENVIRONMENTRECORD_DISKENTRY = _ENVIRONMENTRECORD.nested_types_by_name['DiskEntry']
+_ENVIRONMENTRECORD_SLURMENTRY = _ENVIRONMENTRECORD.nested_types_by_name['SlurmEntry']
+_PYTHONPACKAGESREQUEST = DESCRIPTOR.message_types_by_name['PythonPackagesRequest']
+_PYTHONPACKAGESREQUEST_PYTHONPACKAGE = _PYTHONPACKAGESREQUEST.nested_types_by_name['PythonPackage']
+_JOBINPUTPATH = DESCRIPTOR.message_types_by_name['JobInputPath']
+_JOBINPUTSOURCE = DESCRIPTOR.message_types_by_name['JobInputSource']
+_JOBINPUTSOURCE_RUNCONFIGSOURCE = _JOBINPUTSOURCE.nested_types_by_name['RunConfigSource']
+_JOBINPUTSOURCE_CONFIGFILESOURCE = _JOBINPUTSOURCE.nested_types_by_name['ConfigFileSource']
+_JOBINPUTREQUEST = DESCRIPTOR.message_types_by_name['JobInputRequest']
+_SERVERFEATUREREQUEST = DESCRIPTOR.message_types_by_name['ServerFeatureRequest']
+_SERVERFEATURERESPONSE = DESCRIPTOR.message_types_by_name['ServerFeatureResponse']
+_SERVERFEATUREITEM = DESCRIPTOR.message_types_by_name['ServerFeatureItem']
+_ERRORINFO_ERRORCODE = _ERRORINFO.enum_types_by_name['ErrorCode']
+_OUTPUTRECORD_OUTPUTTYPE = _OUTPUTRECORD.enum_types_by_name['OutputType']
+_OUTPUTRAWRECORD_OUTPUTTYPE = _OUTPUTRAWRECORD.enum_types_by_name['OutputType']
+_METRICRECORD_METRICGOAL = _METRICRECORD.enum_types_by_name['MetricGoal']
+_FILESITEM_POLICYTYPE = _FILESITEM.enum_types_by_name['PolicyType']
+_FILESITEM_FILETYPE = _FILESITEM.enum_types_by_name['FileType']
+_STATSRECORD_STATSTYPE = _STATSRECORD.enum_types_by_name['StatsType']
+_DEFERREQUEST_DEFERSTATE = _DEFERREQUEST.enum_types_by_name['DeferState']
+_FILETRANSFERINFOREQUEST_TRANSFERTYPE = _FILETRANSFERINFOREQUEST.enum_types_by_name['TransferType']
+Record = _reflection.GeneratedProtocolMessageType('Record', (_message.Message,), {
+ 'DESCRIPTOR' : _RECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.Record)
+ })
+_sym_db.RegisterMessage(Record)
+
+Control = _reflection.GeneratedProtocolMessageType('Control', (_message.Message,), {
+ 'DESCRIPTOR' : _CONTROL,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.Control)
+ })
+_sym_db.RegisterMessage(Control)
+
+Result = _reflection.GeneratedProtocolMessageType('Result', (_message.Message,), {
+ 'DESCRIPTOR' : _RESULT,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.Result)
+ })
+_sym_db.RegisterMessage(Result)
+
+FinalRecord = _reflection.GeneratedProtocolMessageType('FinalRecord', (_message.Message,), {
+ 'DESCRIPTOR' : _FINALRECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.FinalRecord)
+ })
+_sym_db.RegisterMessage(FinalRecord)
+
+VersionInfo = _reflection.GeneratedProtocolMessageType('VersionInfo', (_message.Message,), {
+ 'DESCRIPTOR' : _VERSIONINFO,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.VersionInfo)
+ })
+_sym_db.RegisterMessage(VersionInfo)
+
+HeaderRecord = _reflection.GeneratedProtocolMessageType('HeaderRecord', (_message.Message,), {
+ 'DESCRIPTOR' : _HEADERRECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.HeaderRecord)
+ })
+_sym_db.RegisterMessage(HeaderRecord)
+
+FooterRecord = _reflection.GeneratedProtocolMessageType('FooterRecord', (_message.Message,), {
+ 'DESCRIPTOR' : _FOOTERRECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.FooterRecord)
+ })
+_sym_db.RegisterMessage(FooterRecord)
+
+BranchPoint = _reflection.GeneratedProtocolMessageType('BranchPoint', (_message.Message,), {
+ 'DESCRIPTOR' : _BRANCHPOINT,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.BranchPoint)
+ })
+_sym_db.RegisterMessage(BranchPoint)
+
+RunRecord = _reflection.GeneratedProtocolMessageType('RunRecord', (_message.Message,), {
+ 'DESCRIPTOR' : _RUNRECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.RunRecord)
+ })
+_sym_db.RegisterMessage(RunRecord)
+
+GitRepoRecord = _reflection.GeneratedProtocolMessageType('GitRepoRecord', (_message.Message,), {
+ 'DESCRIPTOR' : _GITREPORECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.GitRepoRecord)
+ })
+_sym_db.RegisterMessage(GitRepoRecord)
+
+RunUpdateResult = _reflection.GeneratedProtocolMessageType('RunUpdateResult', (_message.Message,), {
+ 'DESCRIPTOR' : _RUNUPDATERESULT,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.RunUpdateResult)
+ })
+_sym_db.RegisterMessage(RunUpdateResult)
+
+ErrorInfo = _reflection.GeneratedProtocolMessageType('ErrorInfo', (_message.Message,), {
+ 'DESCRIPTOR' : _ERRORINFO,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ErrorInfo)
+ })
+_sym_db.RegisterMessage(ErrorInfo)
+
+RunExitRecord = _reflection.GeneratedProtocolMessageType('RunExitRecord', (_message.Message,), {
+ 'DESCRIPTOR' : _RUNEXITRECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.RunExitRecord)
+ })
+_sym_db.RegisterMessage(RunExitRecord)
+
+RunExitResult = _reflection.GeneratedProtocolMessageType('RunExitResult', (_message.Message,), {
+ 'DESCRIPTOR' : _RUNEXITRESULT,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.RunExitResult)
+ })
+_sym_db.RegisterMessage(RunExitResult)
+
+RunPreemptingRecord = _reflection.GeneratedProtocolMessageType('RunPreemptingRecord', (_message.Message,), {
+ 'DESCRIPTOR' : _RUNPREEMPTINGRECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.RunPreemptingRecord)
+ })
+_sym_db.RegisterMessage(RunPreemptingRecord)
+
+RunPreemptingResult = _reflection.GeneratedProtocolMessageType('RunPreemptingResult', (_message.Message,), {
+ 'DESCRIPTOR' : _RUNPREEMPTINGRESULT,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.RunPreemptingResult)
+ })
+_sym_db.RegisterMessage(RunPreemptingResult)
+
+SettingsRecord = _reflection.GeneratedProtocolMessageType('SettingsRecord', (_message.Message,), {
+ 'DESCRIPTOR' : _SETTINGSRECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.SettingsRecord)
+ })
+_sym_db.RegisterMessage(SettingsRecord)
+
+SettingsItem = _reflection.GeneratedProtocolMessageType('SettingsItem', (_message.Message,), {
+ 'DESCRIPTOR' : _SETTINGSITEM,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.SettingsItem)
+ })
+_sym_db.RegisterMessage(SettingsItem)
+
+HistoryStep = _reflection.GeneratedProtocolMessageType('HistoryStep', (_message.Message,), {
+ 'DESCRIPTOR' : _HISTORYSTEP,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.HistoryStep)
+ })
+_sym_db.RegisterMessage(HistoryStep)
+
+HistoryRecord = _reflection.GeneratedProtocolMessageType('HistoryRecord', (_message.Message,), {
+ 'DESCRIPTOR' : _HISTORYRECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.HistoryRecord)
+ })
+_sym_db.RegisterMessage(HistoryRecord)
+
+HistoryItem = _reflection.GeneratedProtocolMessageType('HistoryItem', (_message.Message,), {
+ 'DESCRIPTOR' : _HISTORYITEM,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.HistoryItem)
+ })
+_sym_db.RegisterMessage(HistoryItem)
+
+HistoryResult = _reflection.GeneratedProtocolMessageType('HistoryResult', (_message.Message,), {
+ 'DESCRIPTOR' : _HISTORYRESULT,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.HistoryResult)
+ })
+_sym_db.RegisterMessage(HistoryResult)
+
+OutputRecord = _reflection.GeneratedProtocolMessageType('OutputRecord', (_message.Message,), {
+ 'DESCRIPTOR' : _OUTPUTRECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.OutputRecord)
+ })
+_sym_db.RegisterMessage(OutputRecord)
+
+OutputResult = _reflection.GeneratedProtocolMessageType('OutputResult', (_message.Message,), {
+ 'DESCRIPTOR' : _OUTPUTRESULT,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.OutputResult)
+ })
+_sym_db.RegisterMessage(OutputResult)
+
+OutputRawRecord = _reflection.GeneratedProtocolMessageType('OutputRawRecord', (_message.Message,), {
+ 'DESCRIPTOR' : _OUTPUTRAWRECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.OutputRawRecord)
+ })
+_sym_db.RegisterMessage(OutputRawRecord)
+
+OutputRawResult = _reflection.GeneratedProtocolMessageType('OutputRawResult', (_message.Message,), {
+ 'DESCRIPTOR' : _OUTPUTRAWRESULT,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.OutputRawResult)
+ })
+_sym_db.RegisterMessage(OutputRawResult)
+
+MetricRecord = _reflection.GeneratedProtocolMessageType('MetricRecord', (_message.Message,), {
+ 'DESCRIPTOR' : _METRICRECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.MetricRecord)
+ })
+_sym_db.RegisterMessage(MetricRecord)
+
+MetricResult = _reflection.GeneratedProtocolMessageType('MetricResult', (_message.Message,), {
+ 'DESCRIPTOR' : _METRICRESULT,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.MetricResult)
+ })
+_sym_db.RegisterMessage(MetricResult)
+
+MetricOptions = _reflection.GeneratedProtocolMessageType('MetricOptions', (_message.Message,), {
+ 'DESCRIPTOR' : _METRICOPTIONS,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.MetricOptions)
+ })
+_sym_db.RegisterMessage(MetricOptions)
+
+MetricControl = _reflection.GeneratedProtocolMessageType('MetricControl', (_message.Message,), {
+ 'DESCRIPTOR' : _METRICCONTROL,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.MetricControl)
+ })
+_sym_db.RegisterMessage(MetricControl)
+
+MetricSummary = _reflection.GeneratedProtocolMessageType('MetricSummary', (_message.Message,), {
+ 'DESCRIPTOR' : _METRICSUMMARY,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.MetricSummary)
+ })
+_sym_db.RegisterMessage(MetricSummary)
+
+ConfigRecord = _reflection.GeneratedProtocolMessageType('ConfigRecord', (_message.Message,), {
+ 'DESCRIPTOR' : _CONFIGRECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ConfigRecord)
+ })
+_sym_db.RegisterMessage(ConfigRecord)
+
+ConfigItem = _reflection.GeneratedProtocolMessageType('ConfigItem', (_message.Message,), {
+ 'DESCRIPTOR' : _CONFIGITEM,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ConfigItem)
+ })
+_sym_db.RegisterMessage(ConfigItem)
+
+ConfigResult = _reflection.GeneratedProtocolMessageType('ConfigResult', (_message.Message,), {
+ 'DESCRIPTOR' : _CONFIGRESULT,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ConfigResult)
+ })
+_sym_db.RegisterMessage(ConfigResult)
+
+SummaryRecord = _reflection.GeneratedProtocolMessageType('SummaryRecord', (_message.Message,), {
+ 'DESCRIPTOR' : _SUMMARYRECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.SummaryRecord)
+ })
+_sym_db.RegisterMessage(SummaryRecord)
+
+SummaryItem = _reflection.GeneratedProtocolMessageType('SummaryItem', (_message.Message,), {
+ 'DESCRIPTOR' : _SUMMARYITEM,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.SummaryItem)
+ })
+_sym_db.RegisterMessage(SummaryItem)
+
+SummaryResult = _reflection.GeneratedProtocolMessageType('SummaryResult', (_message.Message,), {
+ 'DESCRIPTOR' : _SUMMARYRESULT,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.SummaryResult)
+ })
+_sym_db.RegisterMessage(SummaryResult)
+
+FilesRecord = _reflection.GeneratedProtocolMessageType('FilesRecord', (_message.Message,), {
+ 'DESCRIPTOR' : _FILESRECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.FilesRecord)
+ })
+_sym_db.RegisterMessage(FilesRecord)
+
+FilesItem = _reflection.GeneratedProtocolMessageType('FilesItem', (_message.Message,), {
+ 'DESCRIPTOR' : _FILESITEM,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.FilesItem)
+ })
+_sym_db.RegisterMessage(FilesItem)
+
+FilesResult = _reflection.GeneratedProtocolMessageType('FilesResult', (_message.Message,), {
+ 'DESCRIPTOR' : _FILESRESULT,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.FilesResult)
+ })
+_sym_db.RegisterMessage(FilesResult)
+
+StatsRecord = _reflection.GeneratedProtocolMessageType('StatsRecord', (_message.Message,), {
+ 'DESCRIPTOR' : _STATSRECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.StatsRecord)
+ })
+_sym_db.RegisterMessage(StatsRecord)
+
+StatsItem = _reflection.GeneratedProtocolMessageType('StatsItem', (_message.Message,), {
+ 'DESCRIPTOR' : _STATSITEM,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.StatsItem)
+ })
+_sym_db.RegisterMessage(StatsItem)
+
+ArtifactRecord = _reflection.GeneratedProtocolMessageType('ArtifactRecord', (_message.Message,), {
+ 'DESCRIPTOR' : _ARTIFACTRECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ArtifactRecord)
+ })
+_sym_db.RegisterMessage(ArtifactRecord)
+
+ArtifactManifest = _reflection.GeneratedProtocolMessageType('ArtifactManifest', (_message.Message,), {
+ 'DESCRIPTOR' : _ARTIFACTMANIFEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ArtifactManifest)
+ })
+_sym_db.RegisterMessage(ArtifactManifest)
+
+ArtifactManifestEntry = _reflection.GeneratedProtocolMessageType('ArtifactManifestEntry', (_message.Message,), {
+ 'DESCRIPTOR' : _ARTIFACTMANIFESTENTRY,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ArtifactManifestEntry)
+ })
+_sym_db.RegisterMessage(ArtifactManifestEntry)
+
+ExtraItem = _reflection.GeneratedProtocolMessageType('ExtraItem', (_message.Message,), {
+ 'DESCRIPTOR' : _EXTRAITEM,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ExtraItem)
+ })
+_sym_db.RegisterMessage(ExtraItem)
+
+StoragePolicyConfigItem = _reflection.GeneratedProtocolMessageType('StoragePolicyConfigItem', (_message.Message,), {
+ 'DESCRIPTOR' : _STORAGEPOLICYCONFIGITEM,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.StoragePolicyConfigItem)
+ })
+_sym_db.RegisterMessage(StoragePolicyConfigItem)
+
+ArtifactResult = _reflection.GeneratedProtocolMessageType('ArtifactResult', (_message.Message,), {
+ 'DESCRIPTOR' : _ARTIFACTRESULT,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ArtifactResult)
+ })
+_sym_db.RegisterMessage(ArtifactResult)
+
+LinkArtifactResult = _reflection.GeneratedProtocolMessageType('LinkArtifactResult', (_message.Message,), {
+ 'DESCRIPTOR' : _LINKARTIFACTRESULT,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.LinkArtifactResult)
+ })
+_sym_db.RegisterMessage(LinkArtifactResult)
+
+LinkArtifactRequest = _reflection.GeneratedProtocolMessageType('LinkArtifactRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _LINKARTIFACTREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.LinkArtifactRequest)
+ })
+_sym_db.RegisterMessage(LinkArtifactRequest)
+
+LinkArtifactResponse = _reflection.GeneratedProtocolMessageType('LinkArtifactResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _LINKARTIFACTRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.LinkArtifactResponse)
+ })
+_sym_db.RegisterMessage(LinkArtifactResponse)
+
+TBRecord = _reflection.GeneratedProtocolMessageType('TBRecord', (_message.Message,), {
+ 'DESCRIPTOR' : _TBRECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.TBRecord)
+ })
+_sym_db.RegisterMessage(TBRecord)
+
+TBResult = _reflection.GeneratedProtocolMessageType('TBResult', (_message.Message,), {
+ 'DESCRIPTOR' : _TBRESULT,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.TBResult)
+ })
+_sym_db.RegisterMessage(TBResult)
+
+AlertRecord = _reflection.GeneratedProtocolMessageType('AlertRecord', (_message.Message,), {
+ 'DESCRIPTOR' : _ALERTRECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.AlertRecord)
+ })
+_sym_db.RegisterMessage(AlertRecord)
+
+AlertResult = _reflection.GeneratedProtocolMessageType('AlertResult', (_message.Message,), {
+ 'DESCRIPTOR' : _ALERTRESULT,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.AlertResult)
+ })
+_sym_db.RegisterMessage(AlertResult)
+
+Request = _reflection.GeneratedProtocolMessageType('Request', (_message.Message,), {
+ 'DESCRIPTOR' : _REQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.Request)
+ })
+_sym_db.RegisterMessage(Request)
+
+Response = _reflection.GeneratedProtocolMessageType('Response', (_message.Message,), {
+ 'DESCRIPTOR' : _RESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.Response)
+ })
+_sym_db.RegisterMessage(Response)
+
+DeferRequest = _reflection.GeneratedProtocolMessageType('DeferRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _DEFERREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.DeferRequest)
+ })
+_sym_db.RegisterMessage(DeferRequest)
+
+PauseRequest = _reflection.GeneratedProtocolMessageType('PauseRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _PAUSEREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.PauseRequest)
+ })
+_sym_db.RegisterMessage(PauseRequest)
+
+PauseResponse = _reflection.GeneratedProtocolMessageType('PauseResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _PAUSERESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.PauseResponse)
+ })
+_sym_db.RegisterMessage(PauseResponse)
+
+ResumeRequest = _reflection.GeneratedProtocolMessageType('ResumeRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _RESUMEREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ResumeRequest)
+ })
+_sym_db.RegisterMessage(ResumeRequest)
+
+ResumeResponse = _reflection.GeneratedProtocolMessageType('ResumeResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _RESUMERESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ResumeResponse)
+ })
+_sym_db.RegisterMessage(ResumeResponse)
+
+LoginRequest = _reflection.GeneratedProtocolMessageType('LoginRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _LOGINREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.LoginRequest)
+ })
+_sym_db.RegisterMessage(LoginRequest)
+
+LoginResponse = _reflection.GeneratedProtocolMessageType('LoginResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _LOGINRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.LoginResponse)
+ })
+_sym_db.RegisterMessage(LoginResponse)
+
+GetSummaryRequest = _reflection.GeneratedProtocolMessageType('GetSummaryRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _GETSUMMARYREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.GetSummaryRequest)
+ })
+_sym_db.RegisterMessage(GetSummaryRequest)
+
+GetSummaryResponse = _reflection.GeneratedProtocolMessageType('GetSummaryResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _GETSUMMARYRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.GetSummaryResponse)
+ })
+_sym_db.RegisterMessage(GetSummaryResponse)
+
+GetSystemMetricsRequest = _reflection.GeneratedProtocolMessageType('GetSystemMetricsRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _GETSYSTEMMETRICSREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.GetSystemMetricsRequest)
+ })
+_sym_db.RegisterMessage(GetSystemMetricsRequest)
+
+SystemMetricSample = _reflection.GeneratedProtocolMessageType('SystemMetricSample', (_message.Message,), {
+ 'DESCRIPTOR' : _SYSTEMMETRICSAMPLE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.SystemMetricSample)
+ })
+_sym_db.RegisterMessage(SystemMetricSample)
+
+SystemMetricsBuffer = _reflection.GeneratedProtocolMessageType('SystemMetricsBuffer', (_message.Message,), {
+ 'DESCRIPTOR' : _SYSTEMMETRICSBUFFER,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.SystemMetricsBuffer)
+ })
+_sym_db.RegisterMessage(SystemMetricsBuffer)
+
+GetSystemMetricsResponse = _reflection.GeneratedProtocolMessageType('GetSystemMetricsResponse', (_message.Message,), {
+
+ 'SystemMetricsEntry' : _reflection.GeneratedProtocolMessageType('SystemMetricsEntry', (_message.Message,), {
+ 'DESCRIPTOR' : _GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.GetSystemMetricsResponse.SystemMetricsEntry)
+ })
+ ,
+ 'DESCRIPTOR' : _GETSYSTEMMETRICSRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.GetSystemMetricsResponse)
+ })
+_sym_db.RegisterMessage(GetSystemMetricsResponse)
+_sym_db.RegisterMessage(GetSystemMetricsResponse.SystemMetricsEntry)
+
+StatusRequest = _reflection.GeneratedProtocolMessageType('StatusRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _STATUSREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.StatusRequest)
+ })
+_sym_db.RegisterMessage(StatusRequest)
+
+StatusResponse = _reflection.GeneratedProtocolMessageType('StatusResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _STATUSRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.StatusResponse)
+ })
+_sym_db.RegisterMessage(StatusResponse)
+
+StopStatusRequest = _reflection.GeneratedProtocolMessageType('StopStatusRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _STOPSTATUSREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.StopStatusRequest)
+ })
+_sym_db.RegisterMessage(StopStatusRequest)
+
+StopStatusResponse = _reflection.GeneratedProtocolMessageType('StopStatusResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _STOPSTATUSRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.StopStatusResponse)
+ })
+_sym_db.RegisterMessage(StopStatusResponse)
+
+NetworkStatusRequest = _reflection.GeneratedProtocolMessageType('NetworkStatusRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _NETWORKSTATUSREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.NetworkStatusRequest)
+ })
+_sym_db.RegisterMessage(NetworkStatusRequest)
+
+NetworkStatusResponse = _reflection.GeneratedProtocolMessageType('NetworkStatusResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _NETWORKSTATUSRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.NetworkStatusResponse)
+ })
+_sym_db.RegisterMessage(NetworkStatusResponse)
+
+HttpResponse = _reflection.GeneratedProtocolMessageType('HttpResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _HTTPRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.HttpResponse)
+ })
+_sym_db.RegisterMessage(HttpResponse)
+
+InternalMessagesRequest = _reflection.GeneratedProtocolMessageType('InternalMessagesRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _INTERNALMESSAGESREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.InternalMessagesRequest)
+ })
+_sym_db.RegisterMessage(InternalMessagesRequest)
+
+InternalMessagesResponse = _reflection.GeneratedProtocolMessageType('InternalMessagesResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _INTERNALMESSAGESRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.InternalMessagesResponse)
+ })
+_sym_db.RegisterMessage(InternalMessagesResponse)
+
+InternalMessages = _reflection.GeneratedProtocolMessageType('InternalMessages', (_message.Message,), {
+ 'DESCRIPTOR' : _INTERNALMESSAGES,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.InternalMessages)
+ })
+_sym_db.RegisterMessage(InternalMessages)
+
+PollExitRequest = _reflection.GeneratedProtocolMessageType('PollExitRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _POLLEXITREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.PollExitRequest)
+ })
+_sym_db.RegisterMessage(PollExitRequest)
+
+PollExitResponse = _reflection.GeneratedProtocolMessageType('PollExitResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _POLLEXITRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.PollExitResponse)
+ })
+_sym_db.RegisterMessage(PollExitResponse)
+
+OperationStatsRequest = _reflection.GeneratedProtocolMessageType('OperationStatsRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _OPERATIONSTATSREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.OperationStatsRequest)
+ })
+_sym_db.RegisterMessage(OperationStatsRequest)
+
+OperationStatsResponse = _reflection.GeneratedProtocolMessageType('OperationStatsResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _OPERATIONSTATSRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.OperationStatsResponse)
+ })
+_sym_db.RegisterMessage(OperationStatsResponse)
+
+OperationStats = _reflection.GeneratedProtocolMessageType('OperationStats', (_message.Message,), {
+ 'DESCRIPTOR' : _OPERATIONSTATS,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.OperationStats)
+ })
+_sym_db.RegisterMessage(OperationStats)
+
+Operation = _reflection.GeneratedProtocolMessageType('Operation', (_message.Message,), {
+ 'DESCRIPTOR' : _OPERATION,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.Operation)
+ })
+_sym_db.RegisterMessage(Operation)
+
+SenderMarkRequest = _reflection.GeneratedProtocolMessageType('SenderMarkRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _SENDERMARKREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.SenderMarkRequest)
+ })
+_sym_db.RegisterMessage(SenderMarkRequest)
+
+SyncFinishRequest = _reflection.GeneratedProtocolMessageType('SyncFinishRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _SYNCFINISHREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.SyncFinishRequest)
+ })
+_sym_db.RegisterMessage(SyncFinishRequest)
+
+SyncResponse = _reflection.GeneratedProtocolMessageType('SyncResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _SYNCRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.SyncResponse)
+ })
+_sym_db.RegisterMessage(SyncResponse)
+
+SenderReadRequest = _reflection.GeneratedProtocolMessageType('SenderReadRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _SENDERREADREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.SenderReadRequest)
+ })
+_sym_db.RegisterMessage(SenderReadRequest)
+
+StatusReportRequest = _reflection.GeneratedProtocolMessageType('StatusReportRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _STATUSREPORTREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.StatusReportRequest)
+ })
+_sym_db.RegisterMessage(StatusReportRequest)
+
+SummaryRecordRequest = _reflection.GeneratedProtocolMessageType('SummaryRecordRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _SUMMARYRECORDREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.SummaryRecordRequest)
+ })
+_sym_db.RegisterMessage(SummaryRecordRequest)
+
+TelemetryRecordRequest = _reflection.GeneratedProtocolMessageType('TelemetryRecordRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _TELEMETRYRECORDREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.TelemetryRecordRequest)
+ })
+_sym_db.RegisterMessage(TelemetryRecordRequest)
+
+ServerInfoRequest = _reflection.GeneratedProtocolMessageType('ServerInfoRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERINFOREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerInfoRequest)
+ })
+_sym_db.RegisterMessage(ServerInfoRequest)
+
+ServerInfoResponse = _reflection.GeneratedProtocolMessageType('ServerInfoResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERINFORESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerInfoResponse)
+ })
+_sym_db.RegisterMessage(ServerInfoResponse)
+
+ServerMessages = _reflection.GeneratedProtocolMessageType('ServerMessages', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERMESSAGES,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerMessages)
+ })
+_sym_db.RegisterMessage(ServerMessages)
+
+ServerMessage = _reflection.GeneratedProtocolMessageType('ServerMessage', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERMESSAGE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerMessage)
+ })
+_sym_db.RegisterMessage(ServerMessage)
+
+FileCounts = _reflection.GeneratedProtocolMessageType('FileCounts', (_message.Message,), {
+ 'DESCRIPTOR' : _FILECOUNTS,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.FileCounts)
+ })
+_sym_db.RegisterMessage(FileCounts)
+
+FilePusherStats = _reflection.GeneratedProtocolMessageType('FilePusherStats', (_message.Message,), {
+ 'DESCRIPTOR' : _FILEPUSHERSTATS,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.FilePusherStats)
+ })
+_sym_db.RegisterMessage(FilePusherStats)
+
+FilesUploaded = _reflection.GeneratedProtocolMessageType('FilesUploaded', (_message.Message,), {
+ 'DESCRIPTOR' : _FILESUPLOADED,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.FilesUploaded)
+ })
+_sym_db.RegisterMessage(FilesUploaded)
+
+FileTransferInfoRequest = _reflection.GeneratedProtocolMessageType('FileTransferInfoRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _FILETRANSFERINFOREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.FileTransferInfoRequest)
+ })
+_sym_db.RegisterMessage(FileTransferInfoRequest)
+
+LocalInfo = _reflection.GeneratedProtocolMessageType('LocalInfo', (_message.Message,), {
+ 'DESCRIPTOR' : _LOCALINFO,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.LocalInfo)
+ })
+_sym_db.RegisterMessage(LocalInfo)
+
+ShutdownRequest = _reflection.GeneratedProtocolMessageType('ShutdownRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _SHUTDOWNREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ShutdownRequest)
+ })
+_sym_db.RegisterMessage(ShutdownRequest)
+
+ShutdownResponse = _reflection.GeneratedProtocolMessageType('ShutdownResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _SHUTDOWNRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ShutdownResponse)
+ })
+_sym_db.RegisterMessage(ShutdownResponse)
+
+AttachRequest = _reflection.GeneratedProtocolMessageType('AttachRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _ATTACHREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.AttachRequest)
+ })
+_sym_db.RegisterMessage(AttachRequest)
+
+AttachResponse = _reflection.GeneratedProtocolMessageType('AttachResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _ATTACHRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.AttachResponse)
+ })
+_sym_db.RegisterMessage(AttachResponse)
+
+TestInjectRequest = _reflection.GeneratedProtocolMessageType('TestInjectRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _TESTINJECTREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.TestInjectRequest)
+ })
+_sym_db.RegisterMessage(TestInjectRequest)
+
+TestInjectResponse = _reflection.GeneratedProtocolMessageType('TestInjectResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _TESTINJECTRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.TestInjectResponse)
+ })
+_sym_db.RegisterMessage(TestInjectResponse)
+
+HistoryAction = _reflection.GeneratedProtocolMessageType('HistoryAction', (_message.Message,), {
+ 'DESCRIPTOR' : _HISTORYACTION,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.HistoryAction)
+ })
+_sym_db.RegisterMessage(HistoryAction)
+
+PartialHistoryRequest = _reflection.GeneratedProtocolMessageType('PartialHistoryRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _PARTIALHISTORYREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.PartialHistoryRequest)
+ })
+_sym_db.RegisterMessage(PartialHistoryRequest)
+
+PartialHistoryResponse = _reflection.GeneratedProtocolMessageType('PartialHistoryResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _PARTIALHISTORYRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.PartialHistoryResponse)
+ })
+_sym_db.RegisterMessage(PartialHistoryResponse)
+
+SampledHistoryRequest = _reflection.GeneratedProtocolMessageType('SampledHistoryRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _SAMPLEDHISTORYREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.SampledHistoryRequest)
+ })
+_sym_db.RegisterMessage(SampledHistoryRequest)
+
+SampledHistoryItem = _reflection.GeneratedProtocolMessageType('SampledHistoryItem', (_message.Message,), {
+ 'DESCRIPTOR' : _SAMPLEDHISTORYITEM,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.SampledHistoryItem)
+ })
+_sym_db.RegisterMessage(SampledHistoryItem)
+
+SampledHistoryResponse = _reflection.GeneratedProtocolMessageType('SampledHistoryResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _SAMPLEDHISTORYRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.SampledHistoryResponse)
+ })
+_sym_db.RegisterMessage(SampledHistoryResponse)
+
+RunStatusRequest = _reflection.GeneratedProtocolMessageType('RunStatusRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _RUNSTATUSREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.RunStatusRequest)
+ })
+_sym_db.RegisterMessage(RunStatusRequest)
+
+RunStatusResponse = _reflection.GeneratedProtocolMessageType('RunStatusResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _RUNSTATUSRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.RunStatusResponse)
+ })
+_sym_db.RegisterMessage(RunStatusResponse)
+
+RunStartRequest = _reflection.GeneratedProtocolMessageType('RunStartRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _RUNSTARTREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.RunStartRequest)
+ })
+_sym_db.RegisterMessage(RunStartRequest)
+
+RunStartResponse = _reflection.GeneratedProtocolMessageType('RunStartResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _RUNSTARTRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.RunStartResponse)
+ })
+_sym_db.RegisterMessage(RunStartResponse)
+
+RunFinishWithoutExitRequest = _reflection.GeneratedProtocolMessageType('RunFinishWithoutExitRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _RUNFINISHWITHOUTEXITREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.RunFinishWithoutExitRequest)
+ })
+_sym_db.RegisterMessage(RunFinishWithoutExitRequest)
+
+RunFinishWithoutExitResponse = _reflection.GeneratedProtocolMessageType('RunFinishWithoutExitResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _RUNFINISHWITHOUTEXITRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.RunFinishWithoutExitResponse)
+ })
+_sym_db.RegisterMessage(RunFinishWithoutExitResponse)
+
+CheckVersionRequest = _reflection.GeneratedProtocolMessageType('CheckVersionRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _CHECKVERSIONREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.CheckVersionRequest)
+ })
+_sym_db.RegisterMessage(CheckVersionRequest)
+
+CheckVersionResponse = _reflection.GeneratedProtocolMessageType('CheckVersionResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _CHECKVERSIONRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.CheckVersionResponse)
+ })
+_sym_db.RegisterMessage(CheckVersionResponse)
+
+JobInfoRequest = _reflection.GeneratedProtocolMessageType('JobInfoRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _JOBINFOREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.JobInfoRequest)
+ })
+_sym_db.RegisterMessage(JobInfoRequest)
+
+JobInfoResponse = _reflection.GeneratedProtocolMessageType('JobInfoResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _JOBINFORESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.JobInfoResponse)
+ })
+_sym_db.RegisterMessage(JobInfoResponse)
+
+LogArtifactRequest = _reflection.GeneratedProtocolMessageType('LogArtifactRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _LOGARTIFACTREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.LogArtifactRequest)
+ })
+_sym_db.RegisterMessage(LogArtifactRequest)
+
+LogArtifactResponse = _reflection.GeneratedProtocolMessageType('LogArtifactResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _LOGARTIFACTRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.LogArtifactResponse)
+ })
+_sym_db.RegisterMessage(LogArtifactResponse)
+
+DownloadArtifactRequest = _reflection.GeneratedProtocolMessageType('DownloadArtifactRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _DOWNLOADARTIFACTREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.DownloadArtifactRequest)
+ })
+_sym_db.RegisterMessage(DownloadArtifactRequest)
+
+DownloadArtifactResponse = _reflection.GeneratedProtocolMessageType('DownloadArtifactResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _DOWNLOADARTIFACTRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.DownloadArtifactResponse)
+ })
+_sym_db.RegisterMessage(DownloadArtifactResponse)
+
+KeepaliveRequest = _reflection.GeneratedProtocolMessageType('KeepaliveRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _KEEPALIVEREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.KeepaliveRequest)
+ })
+_sym_db.RegisterMessage(KeepaliveRequest)
+
+KeepaliveResponse = _reflection.GeneratedProtocolMessageType('KeepaliveResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _KEEPALIVERESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.KeepaliveResponse)
+ })
+_sym_db.RegisterMessage(KeepaliveResponse)
+
+ArtifactInfo = _reflection.GeneratedProtocolMessageType('ArtifactInfo', (_message.Message,), {
+ 'DESCRIPTOR' : _ARTIFACTINFO,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ArtifactInfo)
+ })
+_sym_db.RegisterMessage(ArtifactInfo)
+
+GitInfo = _reflection.GeneratedProtocolMessageType('GitInfo', (_message.Message,), {
+ 'DESCRIPTOR' : _GITINFO,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.GitInfo)
+ })
+_sym_db.RegisterMessage(GitInfo)
+
+GitSource = _reflection.GeneratedProtocolMessageType('GitSource', (_message.Message,), {
+ 'DESCRIPTOR' : _GITSOURCE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.GitSource)
+ })
+_sym_db.RegisterMessage(GitSource)
+
+ImageSource = _reflection.GeneratedProtocolMessageType('ImageSource', (_message.Message,), {
+ 'DESCRIPTOR' : _IMAGESOURCE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ImageSource)
+ })
+_sym_db.RegisterMessage(ImageSource)
+
+Source = _reflection.GeneratedProtocolMessageType('Source', (_message.Message,), {
+ 'DESCRIPTOR' : _SOURCE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.Source)
+ })
+_sym_db.RegisterMessage(Source)
+
+JobSource = _reflection.GeneratedProtocolMessageType('JobSource', (_message.Message,), {
+ 'DESCRIPTOR' : _JOBSOURCE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.JobSource)
+ })
+_sym_db.RegisterMessage(JobSource)
+
+PartialJobArtifact = _reflection.GeneratedProtocolMessageType('PartialJobArtifact', (_message.Message,), {
+ 'DESCRIPTOR' : _PARTIALJOBARTIFACT,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.PartialJobArtifact)
+ })
+_sym_db.RegisterMessage(PartialJobArtifact)
+
+UseArtifactRecord = _reflection.GeneratedProtocolMessageType('UseArtifactRecord', (_message.Message,), {
+ 'DESCRIPTOR' : _USEARTIFACTRECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.UseArtifactRecord)
+ })
+_sym_db.RegisterMessage(UseArtifactRecord)
+
+UseArtifactResult = _reflection.GeneratedProtocolMessageType('UseArtifactResult', (_message.Message,), {
+ 'DESCRIPTOR' : _USEARTIFACTRESULT,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.UseArtifactResult)
+ })
+_sym_db.RegisterMessage(UseArtifactResult)
+
+CancelRequest = _reflection.GeneratedProtocolMessageType('CancelRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _CANCELREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.CancelRequest)
+ })
+_sym_db.RegisterMessage(CancelRequest)
+
+CancelResponse = _reflection.GeneratedProtocolMessageType('CancelResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _CANCELRESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.CancelResponse)
+ })
+_sym_db.RegisterMessage(CancelResponse)
+
+ProbeSystemInfoRequest = _reflection.GeneratedProtocolMessageType('ProbeSystemInfoRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _PROBESYSTEMINFOREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ProbeSystemInfoRequest)
+ })
+_sym_db.RegisterMessage(ProbeSystemInfoRequest)
+
+DiskInfo = _reflection.GeneratedProtocolMessageType('DiskInfo', (_message.Message,), {
+ 'DESCRIPTOR' : _DISKINFO,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.DiskInfo)
+ })
+_sym_db.RegisterMessage(DiskInfo)
+
+MemoryInfo = _reflection.GeneratedProtocolMessageType('MemoryInfo', (_message.Message,), {
+ 'DESCRIPTOR' : _MEMORYINFO,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.MemoryInfo)
+ })
+_sym_db.RegisterMessage(MemoryInfo)
+
+CpuInfo = _reflection.GeneratedProtocolMessageType('CpuInfo', (_message.Message,), {
+ 'DESCRIPTOR' : _CPUINFO,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.CpuInfo)
+ })
+_sym_db.RegisterMessage(CpuInfo)
+
+AppleInfo = _reflection.GeneratedProtocolMessageType('AppleInfo', (_message.Message,), {
+ 'DESCRIPTOR' : _APPLEINFO,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.AppleInfo)
+ })
+_sym_db.RegisterMessage(AppleInfo)
+
+GpuNvidiaInfo = _reflection.GeneratedProtocolMessageType('GpuNvidiaInfo', (_message.Message,), {
+ 'DESCRIPTOR' : _GPUNVIDIAINFO,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.GpuNvidiaInfo)
+ })
+_sym_db.RegisterMessage(GpuNvidiaInfo)
+
+GpuAmdInfo = _reflection.GeneratedProtocolMessageType('GpuAmdInfo', (_message.Message,), {
+ 'DESCRIPTOR' : _GPUAMDINFO,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.GpuAmdInfo)
+ })
+_sym_db.RegisterMessage(GpuAmdInfo)
+
+TrainiumInfo = _reflection.GeneratedProtocolMessageType('TrainiumInfo', (_message.Message,), {
+ 'DESCRIPTOR' : _TRAINIUMINFO,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.TrainiumInfo)
+ })
+_sym_db.RegisterMessage(TrainiumInfo)
+
+TPUInfo = _reflection.GeneratedProtocolMessageType('TPUInfo', (_message.Message,), {
+ 'DESCRIPTOR' : _TPUINFO,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.TPUInfo)
+ })
+_sym_db.RegisterMessage(TPUInfo)
+
+CoreWeaveInfo = _reflection.GeneratedProtocolMessageType('CoreWeaveInfo', (_message.Message,), {
+ 'DESCRIPTOR' : _COREWEAVEINFO,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.CoreWeaveInfo)
+ })
+_sym_db.RegisterMessage(CoreWeaveInfo)
+
+EnvironmentRecord = _reflection.GeneratedProtocolMessageType('EnvironmentRecord', (_message.Message,), {
+
+ 'DiskEntry' : _reflection.GeneratedProtocolMessageType('DiskEntry', (_message.Message,), {
+ 'DESCRIPTOR' : _ENVIRONMENTRECORD_DISKENTRY,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.EnvironmentRecord.DiskEntry)
+ })
+ ,
+
+ 'SlurmEntry' : _reflection.GeneratedProtocolMessageType('SlurmEntry', (_message.Message,), {
+ 'DESCRIPTOR' : _ENVIRONMENTRECORD_SLURMENTRY,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.EnvironmentRecord.SlurmEntry)
+ })
+ ,
+ 'DESCRIPTOR' : _ENVIRONMENTRECORD,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.EnvironmentRecord)
+ })
+_sym_db.RegisterMessage(EnvironmentRecord)
+_sym_db.RegisterMessage(EnvironmentRecord.DiskEntry)
+_sym_db.RegisterMessage(EnvironmentRecord.SlurmEntry)
+
+PythonPackagesRequest = _reflection.GeneratedProtocolMessageType('PythonPackagesRequest', (_message.Message,), {
+
+ 'PythonPackage' : _reflection.GeneratedProtocolMessageType('PythonPackage', (_message.Message,), {
+ 'DESCRIPTOR' : _PYTHONPACKAGESREQUEST_PYTHONPACKAGE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.PythonPackagesRequest.PythonPackage)
+ })
+ ,
+ 'DESCRIPTOR' : _PYTHONPACKAGESREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.PythonPackagesRequest)
+ })
+_sym_db.RegisterMessage(PythonPackagesRequest)
+_sym_db.RegisterMessage(PythonPackagesRequest.PythonPackage)
+
+JobInputPath = _reflection.GeneratedProtocolMessageType('JobInputPath', (_message.Message,), {
+ 'DESCRIPTOR' : _JOBINPUTPATH,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.JobInputPath)
+ })
+_sym_db.RegisterMessage(JobInputPath)
+
+JobInputSource = _reflection.GeneratedProtocolMessageType('JobInputSource', (_message.Message,), {
+
+ 'RunConfigSource' : _reflection.GeneratedProtocolMessageType('RunConfigSource', (_message.Message,), {
+ 'DESCRIPTOR' : _JOBINPUTSOURCE_RUNCONFIGSOURCE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.JobInputSource.RunConfigSource)
+ })
+ ,
+
+ 'ConfigFileSource' : _reflection.GeneratedProtocolMessageType('ConfigFileSource', (_message.Message,), {
+ 'DESCRIPTOR' : _JOBINPUTSOURCE_CONFIGFILESOURCE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.JobInputSource.ConfigFileSource)
+ })
+ ,
+ 'DESCRIPTOR' : _JOBINPUTSOURCE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.JobInputSource)
+ })
+_sym_db.RegisterMessage(JobInputSource)
+_sym_db.RegisterMessage(JobInputSource.RunConfigSource)
+_sym_db.RegisterMessage(JobInputSource.ConfigFileSource)
+
+JobInputRequest = _reflection.GeneratedProtocolMessageType('JobInputRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _JOBINPUTREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.JobInputRequest)
+ })
+_sym_db.RegisterMessage(JobInputRequest)
+
+ServerFeatureRequest = _reflection.GeneratedProtocolMessageType('ServerFeatureRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERFEATUREREQUEST,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerFeatureRequest)
+ })
+_sym_db.RegisterMessage(ServerFeatureRequest)
+
+ServerFeatureResponse = _reflection.GeneratedProtocolMessageType('ServerFeatureResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERFEATURERESPONSE,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerFeatureResponse)
+ })
+_sym_db.RegisterMessage(ServerFeatureResponse)
+
+ServerFeatureItem = _reflection.GeneratedProtocolMessageType('ServerFeatureItem', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERFEATUREITEM,
+ '__module__' : 'wandb.proto.wandb_internal_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerFeatureItem)
+ })
+_sym_db.RegisterMessage(ServerFeatureItem)
+
+if _descriptor._USE_C_DESCRIPTORS == False:
+
+ DESCRIPTOR._options = None
+ DESCRIPTOR._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY._options = None
+ _GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY._serialized_options = b'8\001'
+ _ENVIRONMENTRECORD_DISKENTRY._options = None
+ _ENVIRONMENTRECORD_DISKENTRY._serialized_options = b'8\001'
+ _ENVIRONMENTRECORD_SLURMENTRY._options = None
+ _ENVIRONMENTRECORD_SLURMENTRY._serialized_options = b'8\001'
+ _SERVERFEATURE._serialized_start=22471
+ _SERVERFEATURE._serialized_end=23034
+ _RECORD._serialized_start=209
+ _RECORD._serialized_end=1491
+ _CONTROL._serialized_start=1494
+ _CONTROL._serialized_end=1662
+ _RESULT._serialized_start=1665
+ _RESULT._serialized_end=2164
+ _FINALRECORD._serialized_start=2166
+ _FINALRECORD._serialized_end=2224
+ _VERSIONINFO._serialized_start=2226
+ _VERSIONINFO._serialized_end=2324
+ _HEADERRECORD._serialized_start=2326
+ _HEADERRECORD._serialized_end=2436
+ _FOOTERRECORD._serialized_start=2438
+ _FOOTERRECORD._serialized_end=2497
+ _BRANCHPOINT._serialized_start=2499
+ _BRANCHPOINT._serialized_end=2556
+ _RUNRECORD._serialized_start=2559
+ _RUNRECORD._serialized_end=3216
+ _GITREPORECORD._serialized_start=3218
+ _GITREPORECORD._serialized_end=3277
+ _RUNUPDATERESULT._serialized_start=3279
+ _RUNUPDATERESULT._serialized_end=3378
+ _ERRORINFO._serialized_start=3381
+ _ERRORINFO._serialized_end=3553
+ _ERRORINFO_ERRORCODE._serialized_start=3462
+ _ERRORINFO_ERRORCODE._serialized_end=3553
+ _RUNEXITRECORD._serialized_start=3555
+ _RUNEXITRECORD._serialized_end=3651
+ _RUNEXITRESULT._serialized_start=3653
+ _RUNEXITRESULT._serialized_end=3668
+ _RUNPREEMPTINGRECORD._serialized_start=3670
+ _RUNPREEMPTINGRECORD._serialized_end=3736
+ _RUNPREEMPTINGRESULT._serialized_start=3738
+ _RUNPREEMPTINGRESULT._serialized_end=3759
+ _SETTINGSRECORD._serialized_start=3761
+ _SETTINGSRECORD._serialized_end=3866
+ _SETTINGSITEM._serialized_start=3868
+ _SETTINGSITEM._serialized_end=3915
+ _HISTORYSTEP._serialized_start=3917
+ _HISTORYSTEP._serialized_end=3943
+ _HISTORYRECORD._serialized_start=3946
+ _HISTORYRECORD._serialized_end=4092
+ _HISTORYITEM._serialized_start=4094
+ _HISTORYITEM._serialized_end=4160
+ _HISTORYRESULT._serialized_start=4162
+ _HISTORYRESULT._serialized_end=4177
+ _OUTPUTRECORD._serialized_start=4180
+ _OUTPUTRECORD._serialized_end=4400
+ _OUTPUTRECORD_OUTPUTTYPE._serialized_start=4364
+ _OUTPUTRECORD_OUTPUTTYPE._serialized_end=4400
+ _OUTPUTRESULT._serialized_start=4402
+ _OUTPUTRESULT._serialized_end=4416
+ _OUTPUTRAWRECORD._serialized_start=4419
+ _OUTPUTRAWRECORD._serialized_end=4645
+ _OUTPUTRAWRECORD_OUTPUTTYPE._serialized_start=4364
+ _OUTPUTRAWRECORD_OUTPUTTYPE._serialized_end=4400
+ _OUTPUTRAWRESULT._serialized_start=4647
+ _OUTPUTRAWRESULT._serialized_end=4664
+ _METRICRECORD._serialized_start=4667
+ _METRICRECORD._serialized_end=5103
+ _METRICRECORD_METRICGOAL._serialized_start=5037
+ _METRICRECORD_METRICGOAL._serialized_end=5103
+ _METRICRESULT._serialized_start=5105
+ _METRICRESULT._serialized_end=5119
+ _METRICOPTIONS._serialized_start=5121
+ _METRICOPTIONS._serialized_end=5188
+ _METRICCONTROL._serialized_start=5190
+ _METRICCONTROL._serialized_end=5224
+ _METRICSUMMARY._serialized_start=5226
+ _METRICSUMMARY._serialized_end=5352
+ _CONFIGRECORD._serialized_start=5355
+ _CONFIGRECORD._serialized_end=5502
+ _CONFIGITEM._serialized_start=5504
+ _CONFIGITEM._serialized_end=5569
+ _CONFIGRESULT._serialized_start=5571
+ _CONFIGRESULT._serialized_end=5585
+ _SUMMARYRECORD._serialized_start=5588
+ _SUMMARYRECORD._serialized_end=5738
+ _SUMMARYITEM._serialized_start=5740
+ _SUMMARYITEM._serialized_end=5806
+ _SUMMARYRESULT._serialized_start=5808
+ _SUMMARYRESULT._serialized_end=5823
+ _FILESRECORD._serialized_start=5825
+ _FILESRECORD._serialized_end=5925
+ _FILESITEM._serialized_start=5928
+ _FILESITEM._serialized_end=6164
+ _FILESITEM_POLICYTYPE._serialized_start=6059
+ _FILESITEM_POLICYTYPE._serialized_end=6099
+ _FILESITEM_FILETYPE._serialized_start=6101
+ _FILESITEM_FILETYPE._serialized_end=6158
+ _FILESRESULT._serialized_start=6166
+ _FILESRESULT._serialized_end=6179
+ _STATSRECORD._serialized_start=6182
+ _STATSRECORD._serialized_end=6412
+ _STATSRECORD_STATSTYPE._serialized_start=6389
+ _STATSRECORD_STATSTYPE._serialized_end=6412
+ _STATSITEM._serialized_start=6414
+ _STATSITEM._serialized_end=6458
+ _ARTIFACTRECORD._serialized_start=6461
+ _ARTIFACTRECORD._serialized_end=6948
+ _ARTIFACTMANIFEST._serialized_start=6951
+ _ARTIFACTMANIFEST._serialized_end=7167
+ _ARTIFACTMANIFESTENTRY._serialized_start=7170
+ _ARTIFACTMANIFESTENTRY._serialized_end=7377
+ _EXTRAITEM._serialized_start=7379
+ _EXTRAITEM._serialized_end=7423
+ _STORAGEPOLICYCONFIGITEM._serialized_start=7425
+ _STORAGEPOLICYCONFIGITEM._serialized_end=7483
+ _ARTIFACTRESULT._serialized_start=7485
+ _ARTIFACTRESULT._serialized_end=7501
+ _LINKARTIFACTRESULT._serialized_start=7503
+ _LINKARTIFACTRESULT._serialized_end=7523
+ _LINKARTIFACTREQUEST._serialized_start=7526
+ _LINKARTIFACTREQUEST._serialized_end=7766
+ _LINKARTIFACTRESPONSE._serialized_start=7768
+ _LINKARTIFACTRESPONSE._serialized_end=7859
+ _TBRECORD._serialized_start=7861
+ _TBRECORD._serialized_end=7965
+ _TBRESULT._serialized_start=7967
+ _TBRESULT._serialized_end=7977
+ _ALERTRECORD._serialized_start=7979
+ _ALERTRECORD._serialized_end=8104
+ _ALERTRESULT._serialized_start=8106
+ _ALERTRESULT._serialized_end=8119
+ _REQUEST._serialized_start=8122
+ _REQUEST._serialized_end=10418
+ _RESPONSE._serialized_start=10421
+ _RESPONSE._serialized_end=12293
+ _DEFERREQUEST._serialized_start=12296
+ _DEFERREQUEST._serialized_end=12616
+ _DEFERREQUEST_DEFERSTATE._serialized_start=12369
+ _DEFERREQUEST_DEFERSTATE._serialized_end=12616
+ _PAUSEREQUEST._serialized_start=12618
+ _PAUSEREQUEST._serialized_end=12678
+ _PAUSERESPONSE._serialized_start=12680
+ _PAUSERESPONSE._serialized_end=12695
+ _RESUMEREQUEST._serialized_start=12697
+ _RESUMEREQUEST._serialized_end=12758
+ _RESUMERESPONSE._serialized_start=12760
+ _RESUMERESPONSE._serialized_end=12776
+ _LOGINREQUEST._serialized_start=12778
+ _LOGINREQUEST._serialized_end=12855
+ _LOGINRESPONSE._serialized_start=12857
+ _LOGINRESPONSE._serialized_end=12895
+ _GETSUMMARYREQUEST._serialized_start=12897
+ _GETSUMMARYREQUEST._serialized_end=12962
+ _GETSUMMARYRESPONSE._serialized_start=12964
+ _GETSUMMARYRESPONSE._serialized_end=13027
+ _GETSYSTEMMETRICSREQUEST._serialized_start=13029
+ _GETSYSTEMMETRICSREQUEST._serialized_end=13100
+ _SYSTEMMETRICSAMPLE._serialized_start=13102
+ _SYSTEMMETRICSAMPLE._serialized_end=13184
+ _SYSTEMMETRICSBUFFER._serialized_start=13186
+ _SYSTEMMETRICSBUFFER._serialized_end=13259
+ _GETSYSTEMMETRICSRESPONSE._serialized_start=13262
+ _GETSYSTEMMETRICSRESPONSE._serialized_end=13464
+ _GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY._serialized_start=13375
+ _GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY._serialized_end=13464
+ _STATUSREQUEST._serialized_start=13466
+ _STATUSREQUEST._serialized_end=13527
+ _STATUSRESPONSE._serialized_start=13529
+ _STATUSRESPONSE._serialized_end=13570
+ _STOPSTATUSREQUEST._serialized_start=13572
+ _STOPSTATUSREQUEST._serialized_end=13637
+ _STOPSTATUSRESPONSE._serialized_start=13639
+ _STOPSTATUSRESPONSE._serialized_end=13684
+ _NETWORKSTATUSREQUEST._serialized_start=13686
+ _NETWORKSTATUSREQUEST._serialized_end=13754
+ _NETWORKSTATUSRESPONSE._serialized_start=13756
+ _NETWORKSTATUSRESPONSE._serialized_end=13836
+ _HTTPRESPONSE._serialized_start=13838
+ _HTTPRESPONSE._serialized_end=13906
+ _INTERNALMESSAGESREQUEST._serialized_start=13908
+ _INTERNALMESSAGESREQUEST._serialized_end=13979
+ _INTERNALMESSAGESRESPONSE._serialized_start=13981
+ _INTERNALMESSAGESRESPONSE._serialized_end=14059
+ _INTERNALMESSAGES._serialized_start=14061
+ _INTERNALMESSAGES._serialized_end=14096
+ _POLLEXITREQUEST._serialized_start=14098
+ _POLLEXITREQUEST._serialized_end=14161
+ _POLLEXITRESPONSE._serialized_start=14164
+ _POLLEXITRESPONSE._serialized_end=14409
+ _OPERATIONSTATSREQUEST._serialized_start=14411
+ _OPERATIONSTATSREQUEST._serialized_end=14480
+ _OPERATIONSTATSRESPONSE._serialized_start=14482
+ _OPERATIONSTATSRESPONSE._serialized_end=14563
+ _OPERATIONSTATS._serialized_start=14565
+ _OPERATIONSTATS._serialized_end=14654
+ _OPERATION._serialized_start=14657
+ _OPERATION._serialized_end=14792
+ _SENDERMARKREQUEST._serialized_start=14794
+ _SENDERMARKREQUEST._serialized_end=14813
+ _SYNCFINISHREQUEST._serialized_start=14815
+ _SYNCFINISHREQUEST._serialized_end=14834
+ _SYNCRESPONSE._serialized_start=14836
+ _SYNCRESPONSE._serialized_end=14905
+ _SENDERREADREQUEST._serialized_start=14907
+ _SENDERREADREQUEST._serialized_end=14970
+ _STATUSREPORTREQUEST._serialized_start=14972
+ _STATUSREPORTREQUEST._serialized_end=15081
+ _SUMMARYRECORDREQUEST._serialized_start=15083
+ _SUMMARYRECORDREQUEST._serialized_end=15153
+ _TELEMETRYRECORDREQUEST._serialized_start=15155
+ _TELEMETRYRECORDREQUEST._serialized_end=15231
+ _SERVERINFOREQUEST._serialized_start=15233
+ _SERVERINFOREQUEST._serialized_end=15298
+ _SERVERINFORESPONSE._serialized_start=15300
+ _SERVERINFORESPONSE._serialized_end=15424
+ _SERVERMESSAGES._serialized_start=15426
+ _SERVERMESSAGES._serialized_end=15487
+ _SERVERMESSAGE._serialized_start=15489
+ _SERVERMESSAGE._serialized_end=15590
+ _FILECOUNTS._serialized_start=15592
+ _FILECOUNTS._serialized_end=15691
+ _FILEPUSHERSTATS._serialized_start=15693
+ _FILEPUSHERSTATS._serialized_end=15778
+ _FILESUPLOADED._serialized_start=15780
+ _FILESUPLOADED._serialized_end=15810
+ _FILETRANSFERINFOREQUEST._serialized_start=15813
+ _FILETRANSFERINFOREQUEST._serialized_end=16057
+ _FILETRANSFERINFOREQUEST_TRANSFERTYPE._serialized_start=16017
+ _FILETRANSFERINFOREQUEST_TRANSFERTYPE._serialized_end=16057
+ _LOCALINFO._serialized_start=16059
+ _LOCALINFO._serialized_end=16108
+ _SHUTDOWNREQUEST._serialized_start=16110
+ _SHUTDOWNREQUEST._serialized_end=16173
+ _SHUTDOWNRESPONSE._serialized_start=16175
+ _SHUTDOWNRESPONSE._serialized_end=16193
+ _ATTACHREQUEST._serialized_start=16195
+ _ATTACHREQUEST._serialized_end=16275
+ _ATTACHRESPONSE._serialized_start=16277
+ _ATTACHRESPONSE._serialized_end=16375
+ _TESTINJECTREQUEST._serialized_start=16378
+ _TESTINJECTREQUEST._serialized_end=16719
+ _TESTINJECTRESPONSE._serialized_start=16721
+ _TESTINJECTRESPONSE._serialized_end=16741
+ _HISTORYACTION._serialized_start=16743
+ _HISTORYACTION._serialized_end=16773
+ _PARTIALHISTORYREQUEST._serialized_start=16776
+ _PARTIALHISTORYREQUEST._serialized_end=16978
+ _PARTIALHISTORYRESPONSE._serialized_start=16980
+ _PARTIALHISTORYRESPONSE._serialized_end=17004
+ _SAMPLEDHISTORYREQUEST._serialized_start=17006
+ _SAMPLEDHISTORYREQUEST._serialized_end=17075
+ _SAMPLEDHISTORYITEM._serialized_start=17077
+ _SAMPLEDHISTORYITEM._serialized_end=17172
+ _SAMPLEDHISTORYRESPONSE._serialized_start=17174
+ _SAMPLEDHISTORYRESPONSE._serialized_end=17248
+ _RUNSTATUSREQUEST._serialized_start=17250
+ _RUNSTATUSREQUEST._serialized_end=17314
+ _RUNSTATUSRESPONSE._serialized_start=17316
+ _RUNSTATUSRESPONSE._serialized_end=17436
+ _RUNSTARTREQUEST._serialized_start=17438
+ _RUNSTARTREQUEST._serialized_end=17541
+ _RUNSTARTRESPONSE._serialized_start=17543
+ _RUNSTARTRESPONSE._serialized_end=17561
+ _RUNFINISHWITHOUTEXITREQUEST._serialized_start=17563
+ _RUNFINISHWITHOUTEXITREQUEST._serialized_end=17638
+ _RUNFINISHWITHOUTEXITRESPONSE._serialized_start=17640
+ _RUNFINISHWITHOUTEXITRESPONSE._serialized_end=17670
+ _CHECKVERSIONREQUEST._serialized_start=17672
+ _CHECKVERSIONREQUEST._serialized_end=17764
+ _CHECKVERSIONRESPONSE._serialized_start=17766
+ _CHECKVERSIONRESPONSE._serialized_end=17859
+ _JOBINFOREQUEST._serialized_start=17861
+ _JOBINFOREQUEST._serialized_end=17923
+ _JOBINFORESPONSE._serialized_start=17925
+ _JOBINFORESPONSE._serialized_end=17979
+ _LOGARTIFACTREQUEST._serialized_start=17982
+ _LOGARTIFACTREQUEST._serialized_end=18141
+ _LOGARTIFACTRESPONSE._serialized_start=18143
+ _LOGARTIFACTRESPONSE._serialized_end=18208
+ _DOWNLOADARTIFACTREQUEST._serialized_start=18211
+ _DOWNLOADARTIFACTREQUEST._serialized_end=18401
+ _DOWNLOADARTIFACTRESPONSE._serialized_start=18403
+ _DOWNLOADARTIFACTRESPONSE._serialized_end=18452
+ _KEEPALIVEREQUEST._serialized_start=18454
+ _KEEPALIVEREQUEST._serialized_end=18518
+ _KEEPALIVERESPONSE._serialized_start=18520
+ _KEEPALIVERESPONSE._serialized_end=18539
+ _ARTIFACTINFO._serialized_start=18541
+ _ARTIFACTINFO._serialized_end=18654
+ _GITINFO._serialized_start=18656
+ _GITINFO._serialized_end=18697
+ _GITSOURCE._serialized_start=18700
+ _GITSOURCE._serialized_end=18835
+ _IMAGESOURCE._serialized_start=18837
+ _IMAGESOURCE._serialized_end=18865
+ _SOURCE._serialized_start=18868
+ _SOURCE._serialized_end=19008
+ _JOBSOURCE._serialized_start=19010
+ _JOBSOURCE._serialized_end=19117
+ _PARTIALJOBARTIFACT._serialized_start=19119
+ _PARTIALJOBARTIFACT._serialized_end=19205
+ _USEARTIFACTRECORD._serialized_start=19208
+ _USEARTIFACTRECORD._serialized_end=19365
+ _USEARTIFACTRESULT._serialized_start=19367
+ _USEARTIFACTRESULT._serialized_end=19386
+ _CANCELREQUEST._serialized_start=19388
+ _CANCELREQUEST._serialized_end=19470
+ _CANCELRESPONSE._serialized_start=19472
+ _CANCELRESPONSE._serialized_end=19488
+ _PROBESYSTEMINFOREQUEST._serialized_start=19490
+ _PROBESYSTEMINFOREQUEST._serialized_end=19514
+ _DISKINFO._serialized_start=19516
+ _DISKINFO._serialized_end=19555
+ _MEMORYINFO._serialized_start=19557
+ _MEMORYINFO._serialized_end=19584
+ _CPUINFO._serialized_start=19586
+ _CPUINFO._serialized_end=19633
+ _APPLEINFO._serialized_start=19636
+ _APPLEINFO._serialized_end=19790
+ _GPUNVIDIAINFO._serialized_start=19792
+ _GPUNVIDIAINFO._serialized_end=19899
+ _GPUAMDINFO._serialized_start=19902
+ _GPUAMDINFO._serialized_end=20167
+ _TRAINIUMINFO._serialized_start=20169
+ _TRAINIUMINFO._serialized_end=20279
+ _TPUINFO._serialized_start=20281
+ _TPUINFO._serialized_end=20362
+ _COREWEAVEINFO._serialized_start=20364
+ _COREWEAVEINFO._serialized_end=20433
+ _ENVIRONMENTRECORD._serialized_start=20436
+ _ENVIRONMENTRECORD._serialized_end=21628
+ _ENVIRONMENTRECORD_DISKENTRY._serialized_start=21513
+ _ENVIRONMENTRECORD_DISKENTRY._serialized_end=21582
+ _ENVIRONMENTRECORD_SLURMENTRY._serialized_start=21584
+ _ENVIRONMENTRECORD_SLURMENTRY._serialized_end=21628
+ _PYTHONPACKAGESREQUEST._serialized_start=21631
+ _PYTHONPACKAGESREQUEST._serialized_end=21772
+ _PYTHONPACKAGESREQUEST_PYTHONPACKAGE._serialized_start=21726
+ _PYTHONPACKAGESREQUEST_PYTHONPACKAGE._serialized_end=21772
+ _JOBINPUTPATH._serialized_start=21774
+ _JOBINPUTPATH._serialized_end=21802
+ _JOBINPUTSOURCE._serialized_start=21805
+ _JOBINPUTSOURCE._serialized_end=22019
+ _JOBINPUTSOURCE_RUNCONFIGSOURCE._serialized_start=21958
+ _JOBINPUTSOURCE_RUNCONFIGSOURCE._serialized_end=21975
+ _JOBINPUTSOURCE_CONFIGFILESOURCE._serialized_start=21977
+ _JOBINPUTSOURCE_CONFIGFILESOURCE._serialized_end=22009
+ _JOBINPUTREQUEST._serialized_start=22022
+ _JOBINPUTREQUEST._serialized_end=22221
+ _SERVERFEATUREREQUEST._serialized_start=22223
+ _SERVERFEATUREREQUEST._serialized_end=22339
+ _SERVERFEATURERESPONSE._serialized_start=22341
+ _SERVERFEATURERESPONSE._serialized_end=22416
+ _SERVERFEATUREITEM._serialized_start=22418
+ _SERVERFEATUREITEM._serialized_end=22468
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/wandb_server_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/wandb_server_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..da81204ab24ea5c3c6729372fa215211839d9ae5
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/wandb_server_pb2.py
@@ -0,0 +1,209 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: wandb/proto/wandb_server.proto
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import message as _message
+from google.protobuf import reflection as _reflection
+from google.protobuf import symbol_database as _symbol_database
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2
+from wandb.proto import wandb_internal_pb2 as wandb_dot_proto_dot_wandb__internal__pb2
+from wandb.proto import wandb_settings_pb2 as wandb_dot_proto_dot_wandb__settings__pb2
+from wandb.proto import wandb_sync_pb2 as wandb_dot_proto_dot_wandb__sync__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1ewandb/proto/wandb_server.proto\x12\x0ewandb_internal\x1a\x1cwandb/proto/wandb_base.proto\x1a wandb/proto/wandb_internal.proto\x1a wandb/proto/wandb_settings.proto\x1a\x1cwandb/proto/wandb_sync.proto\"k\n\x19ServerAuthenticateRequest\x12\x0f\n\x07\x61pi_key\x18\x01 \x01(\t\x12\x10\n\x08\x62\x61se_url\x18\x02 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"w\n\x1aServerAuthenticateResponse\x12\x16\n\x0e\x64\x65\x66\x61ult_entity\x18\x01 \x01(\t\x12\x14\n\x0c\x65rror_status\x18\x02 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"D\n\x15ServerShutdownRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x18\n\x16ServerShutdownResponse\"B\n\x13ServerStatusRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x16\n\x14ServerStatusResponse\"r\n\x17ServerInformInitRequest\x12*\n\x08settings\x18\x01 \x01(\x0b\x32\x18.wandb_internal.Settings\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1a\n\x18ServerInformInitResponse\"H\n\x19ServerInformFinishRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1c\n\x1aServerInformFinishResponse\"H\n\x19ServerInformAttachRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"u\n\x1aServerInformAttachResponse\x12*\n\x08settings\x18\x01 \x01(\x0b\x32\x18.wandb_internal.Settings\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"H\n\x19ServerInformDetachRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1c\n\x1aServerInformDetachResponse\"]\n\x1bServerInformTeardownRequest\x12\x11\n\texit_code\x18\x01 \x01(\x05\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1e\n\x1cServerInformTeardownResponse\"\xee\x05\n\rServerRequest\x12\x12\n\nrequest_id\x18\n \x01(\t\x12\x30\n\x0erecord_publish\x18\x01 \x01(\x0b\x32\x16.wandb_internal.RecordH\x00\x12\x34\n\x12record_communicate\x18\x02 \x01(\x0b\x32\x16.wandb_internal.RecordH\x00\x12>\n\x0binform_init\x18\x03 \x01(\x0b\x32\'.wandb_internal.ServerInformInitRequestH\x00\x12\x42\n\rinform_finish\x18\x04 \x01(\x0b\x32).wandb_internal.ServerInformFinishRequestH\x00\x12\x42\n\rinform_attach\x18\x05 \x01(\x0b\x32).wandb_internal.ServerInformAttachRequestH\x00\x12\x42\n\rinform_detach\x18\x06 \x01(\x0b\x32).wandb_internal.ServerInformDetachRequestH\x00\x12\x46\n\x0finform_teardown\x18\x07 \x01(\x0b\x32+.wandb_internal.ServerInformTeardownRequestH\x00\x12\x41\n\x0c\x61uthenticate\x18\t \x01(\x0b\x32).wandb_internal.ServerAuthenticateRequestH\x00\x12:\n\tinit_sync\x18\x0b \x01(\x0b\x32%.wandb_internal.ServerInitSyncRequestH\x00\x12\x31\n\x04sync\x18\x0c \x01(\x0b\x32!.wandb_internal.ServerSyncRequestH\x00\x12>\n\x0bsync_status\x18\r \x01(\x0b\x32\'.wandb_internal.ServerSyncStatusRequestH\x00\x42\x15\n\x13server_request_typeJ\x04\x08\x08\x10\t\"\x98\x06\n\x0eServerResponse\x12\x12\n\nrequest_id\x18\n \x01(\t\x12\x34\n\x12result_communicate\x18\x02 \x01(\x0b\x32\x16.wandb_internal.ResultH\x00\x12H\n\x14inform_init_response\x18\x03 \x01(\x0b\x32(.wandb_internal.ServerInformInitResponseH\x00\x12L\n\x16inform_finish_response\x18\x04 \x01(\x0b\x32*.wandb_internal.ServerInformFinishResponseH\x00\x12L\n\x16inform_attach_response\x18\x05 \x01(\x0b\x32*.wandb_internal.ServerInformAttachResponseH\x00\x12L\n\x16inform_detach_response\x18\x06 \x01(\x0b\x32*.wandb_internal.ServerInformDetachResponseH\x00\x12P\n\x18inform_teardown_response\x18\x07 \x01(\x0b\x32,.wandb_internal.ServerInformTeardownResponseH\x00\x12K\n\x15\x61uthenticate_response\x18\t \x01(\x0b\x32*.wandb_internal.ServerAuthenticateResponseH\x00\x12\x44\n\x12init_sync_response\x18\x0b \x01(\x0b\x32&.wandb_internal.ServerInitSyncResponseH\x00\x12;\n\rsync_response\x18\x0c \x01(\x0b\x32\".wandb_internal.ServerSyncResponseH\x00\x12H\n\x14sync_status_response\x18\r \x01(\x0b\x32(.wandb_internal.ServerSyncStatusResponseH\x00\x42\x16\n\x14server_response_typeJ\x04\x08\x08\x10\tB\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+
+
+_SERVERAUTHENTICATEREQUEST = DESCRIPTOR.message_types_by_name['ServerAuthenticateRequest']
+_SERVERAUTHENTICATERESPONSE = DESCRIPTOR.message_types_by_name['ServerAuthenticateResponse']
+_SERVERSHUTDOWNREQUEST = DESCRIPTOR.message_types_by_name['ServerShutdownRequest']
+_SERVERSHUTDOWNRESPONSE = DESCRIPTOR.message_types_by_name['ServerShutdownResponse']
+_SERVERSTATUSREQUEST = DESCRIPTOR.message_types_by_name['ServerStatusRequest']
+_SERVERSTATUSRESPONSE = DESCRIPTOR.message_types_by_name['ServerStatusResponse']
+_SERVERINFORMINITREQUEST = DESCRIPTOR.message_types_by_name['ServerInformInitRequest']
+_SERVERINFORMINITRESPONSE = DESCRIPTOR.message_types_by_name['ServerInformInitResponse']
+_SERVERINFORMFINISHREQUEST = DESCRIPTOR.message_types_by_name['ServerInformFinishRequest']
+_SERVERINFORMFINISHRESPONSE = DESCRIPTOR.message_types_by_name['ServerInformFinishResponse']
+_SERVERINFORMATTACHREQUEST = DESCRIPTOR.message_types_by_name['ServerInformAttachRequest']
+_SERVERINFORMATTACHRESPONSE = DESCRIPTOR.message_types_by_name['ServerInformAttachResponse']
+_SERVERINFORMDETACHREQUEST = DESCRIPTOR.message_types_by_name['ServerInformDetachRequest']
+_SERVERINFORMDETACHRESPONSE = DESCRIPTOR.message_types_by_name['ServerInformDetachResponse']
+_SERVERINFORMTEARDOWNREQUEST = DESCRIPTOR.message_types_by_name['ServerInformTeardownRequest']
+_SERVERINFORMTEARDOWNRESPONSE = DESCRIPTOR.message_types_by_name['ServerInformTeardownResponse']
+_SERVERREQUEST = DESCRIPTOR.message_types_by_name['ServerRequest']
+_SERVERRESPONSE = DESCRIPTOR.message_types_by_name['ServerResponse']
+ServerAuthenticateRequest = _reflection.GeneratedProtocolMessageType('ServerAuthenticateRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERAUTHENTICATEREQUEST,
+ '__module__' : 'wandb.proto.wandb_server_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerAuthenticateRequest)
+ })
+_sym_db.RegisterMessage(ServerAuthenticateRequest)
+
+ServerAuthenticateResponse = _reflection.GeneratedProtocolMessageType('ServerAuthenticateResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERAUTHENTICATERESPONSE,
+ '__module__' : 'wandb.proto.wandb_server_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerAuthenticateResponse)
+ })
+_sym_db.RegisterMessage(ServerAuthenticateResponse)
+
+ServerShutdownRequest = _reflection.GeneratedProtocolMessageType('ServerShutdownRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERSHUTDOWNREQUEST,
+ '__module__' : 'wandb.proto.wandb_server_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerShutdownRequest)
+ })
+_sym_db.RegisterMessage(ServerShutdownRequest)
+
+ServerShutdownResponse = _reflection.GeneratedProtocolMessageType('ServerShutdownResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERSHUTDOWNRESPONSE,
+ '__module__' : 'wandb.proto.wandb_server_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerShutdownResponse)
+ })
+_sym_db.RegisterMessage(ServerShutdownResponse)
+
+ServerStatusRequest = _reflection.GeneratedProtocolMessageType('ServerStatusRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERSTATUSREQUEST,
+ '__module__' : 'wandb.proto.wandb_server_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerStatusRequest)
+ })
+_sym_db.RegisterMessage(ServerStatusRequest)
+
+ServerStatusResponse = _reflection.GeneratedProtocolMessageType('ServerStatusResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERSTATUSRESPONSE,
+ '__module__' : 'wandb.proto.wandb_server_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerStatusResponse)
+ })
+_sym_db.RegisterMessage(ServerStatusResponse)
+
+ServerInformInitRequest = _reflection.GeneratedProtocolMessageType('ServerInformInitRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERINFORMINITREQUEST,
+ '__module__' : 'wandb.proto.wandb_server_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformInitRequest)
+ })
+_sym_db.RegisterMessage(ServerInformInitRequest)
+
+ServerInformInitResponse = _reflection.GeneratedProtocolMessageType('ServerInformInitResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERINFORMINITRESPONSE,
+ '__module__' : 'wandb.proto.wandb_server_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformInitResponse)
+ })
+_sym_db.RegisterMessage(ServerInformInitResponse)
+
+ServerInformFinishRequest = _reflection.GeneratedProtocolMessageType('ServerInformFinishRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERINFORMFINISHREQUEST,
+ '__module__' : 'wandb.proto.wandb_server_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformFinishRequest)
+ })
+_sym_db.RegisterMessage(ServerInformFinishRequest)
+
+ServerInformFinishResponse = _reflection.GeneratedProtocolMessageType('ServerInformFinishResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERINFORMFINISHRESPONSE,
+ '__module__' : 'wandb.proto.wandb_server_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformFinishResponse)
+ })
+_sym_db.RegisterMessage(ServerInformFinishResponse)
+
+ServerInformAttachRequest = _reflection.GeneratedProtocolMessageType('ServerInformAttachRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERINFORMATTACHREQUEST,
+ '__module__' : 'wandb.proto.wandb_server_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformAttachRequest)
+ })
+_sym_db.RegisterMessage(ServerInformAttachRequest)
+
+ServerInformAttachResponse = _reflection.GeneratedProtocolMessageType('ServerInformAttachResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERINFORMATTACHRESPONSE,
+ '__module__' : 'wandb.proto.wandb_server_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformAttachResponse)
+ })
+_sym_db.RegisterMessage(ServerInformAttachResponse)
+
+ServerInformDetachRequest = _reflection.GeneratedProtocolMessageType('ServerInformDetachRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERINFORMDETACHREQUEST,
+ '__module__' : 'wandb.proto.wandb_server_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformDetachRequest)
+ })
+_sym_db.RegisterMessage(ServerInformDetachRequest)
+
+ServerInformDetachResponse = _reflection.GeneratedProtocolMessageType('ServerInformDetachResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERINFORMDETACHRESPONSE,
+ '__module__' : 'wandb.proto.wandb_server_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformDetachResponse)
+ })
+_sym_db.RegisterMessage(ServerInformDetachResponse)
+
+ServerInformTeardownRequest = _reflection.GeneratedProtocolMessageType('ServerInformTeardownRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERINFORMTEARDOWNREQUEST,
+ '__module__' : 'wandb.proto.wandb_server_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformTeardownRequest)
+ })
+_sym_db.RegisterMessage(ServerInformTeardownRequest)
+
+ServerInformTeardownResponse = _reflection.GeneratedProtocolMessageType('ServerInformTeardownResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERINFORMTEARDOWNRESPONSE,
+ '__module__' : 'wandb.proto.wandb_server_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerInformTeardownResponse)
+ })
+_sym_db.RegisterMessage(ServerInformTeardownResponse)
+
+ServerRequest = _reflection.GeneratedProtocolMessageType('ServerRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERREQUEST,
+ '__module__' : 'wandb.proto.wandb_server_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerRequest)
+ })
+_sym_db.RegisterMessage(ServerRequest)
+
+ServerResponse = _reflection.GeneratedProtocolMessageType('ServerResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERRESPONSE,
+ '__module__' : 'wandb.proto.wandb_server_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerResponse)
+ })
+_sym_db.RegisterMessage(ServerResponse)
+
+if _descriptor._USE_C_DESCRIPTORS == False:
+
+ DESCRIPTOR._options = None
+ DESCRIPTOR._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _SERVERAUTHENTICATEREQUEST._serialized_start=178
+ _SERVERAUTHENTICATEREQUEST._serialized_end=285
+ _SERVERAUTHENTICATERESPONSE._serialized_start=287
+ _SERVERAUTHENTICATERESPONSE._serialized_end=406
+ _SERVERSHUTDOWNREQUEST._serialized_start=408
+ _SERVERSHUTDOWNREQUEST._serialized_end=476
+ _SERVERSHUTDOWNRESPONSE._serialized_start=478
+ _SERVERSHUTDOWNRESPONSE._serialized_end=502
+ _SERVERSTATUSREQUEST._serialized_start=504
+ _SERVERSTATUSREQUEST._serialized_end=570
+ _SERVERSTATUSRESPONSE._serialized_start=572
+ _SERVERSTATUSRESPONSE._serialized_end=594
+ _SERVERINFORMINITREQUEST._serialized_start=596
+ _SERVERINFORMINITREQUEST._serialized_end=710
+ _SERVERINFORMINITRESPONSE._serialized_start=712
+ _SERVERINFORMINITRESPONSE._serialized_end=738
+ _SERVERINFORMFINISHREQUEST._serialized_start=740
+ _SERVERINFORMFINISHREQUEST._serialized_end=812
+ _SERVERINFORMFINISHRESPONSE._serialized_start=814
+ _SERVERINFORMFINISHRESPONSE._serialized_end=842
+ _SERVERINFORMATTACHREQUEST._serialized_start=844
+ _SERVERINFORMATTACHREQUEST._serialized_end=916
+ _SERVERINFORMATTACHRESPONSE._serialized_start=918
+ _SERVERINFORMATTACHRESPONSE._serialized_end=1035
+ _SERVERINFORMDETACHREQUEST._serialized_start=1037
+ _SERVERINFORMDETACHREQUEST._serialized_end=1109
+ _SERVERINFORMDETACHRESPONSE._serialized_start=1111
+ _SERVERINFORMDETACHRESPONSE._serialized_end=1139
+ _SERVERINFORMTEARDOWNREQUEST._serialized_start=1141
+ _SERVERINFORMTEARDOWNREQUEST._serialized_end=1234
+ _SERVERINFORMTEARDOWNRESPONSE._serialized_start=1236
+ _SERVERINFORMTEARDOWNRESPONSE._serialized_end=1266
+ _SERVERREQUEST._serialized_start=1269
+ _SERVERREQUEST._serialized_end=2019
+ _SERVERRESPONSE._serialized_start=2022
+ _SERVERRESPONSE._serialized_end=2814
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/wandb_settings_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/wandb_settings_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..9559c3e724388534702ae7ed4680751fa483eb59
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/wandb_settings_pb2.py
@@ -0,0 +1,122 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: wandb/proto/wandb_settings.proto
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import message as _message
+from google.protobuf import reflection as _reflection
+from google.protobuf import symbol_database as _symbol_database
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from google.protobuf import wrappers_pb2 as google_dot_protobuf_dot_wrappers__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n wandb/proto/wandb_settings.proto\x12\x0ewandb_internal\x1a\x1egoogle/protobuf/wrappers.proto\" \n\x0fListStringValue\x12\r\n\x05value\x18\x01 \x03(\t\"\x1d\n\x0cListIntValue\x12\r\n\x05value\x18\x01 \x03(\x05\"\x8a\x01\n\x17MapStringKeyStringValue\x12\x41\n\x05value\x18\x01 \x03(\x0b\x32\x32.wandb_internal.MapStringKeyStringValue.ValueEntry\x1a,\n\nValueEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xcb\x01\n#MapStringKeyMapStringKeyStringValue\x12M\n\x05value\x18\x01 \x03(\x0b\x32>.wandb_internal.MapStringKeyMapStringKeyStringValue.ValueEntry\x1aU\n\nValueEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x36\n\x05value\x18\x02 \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue:\x02\x38\x01\"\x9a\x01\n\x12OpenMetricsFilters\x12\x33\n\x08sequence\x18\x01 \x01(\x0b\x32\x1f.wandb_internal.ListStringValueH\x00\x12\x46\n\x07mapping\x18\x02 \x01(\x0b\x32\x33.wandb_internal.MapStringKeyMapStringKeyStringValueH\x00\x42\x07\n\x05value\"7\n\tRunMoment\x12\x0b\n\x03run\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x01\x12\x0e\n\x06metric\x18\x03 \x01(\t\"\xc2M\n\x08Settings\x12-\n\x07\x61pi_key\x18\x37 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12:\n\x13identity_token_file\x18\xaa\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x37\n\x10\x63redentials_file\x18\xab\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x39\n\x14insecure_disable_ssl\x18\xb9\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12,\n\x08_offline\x18\x1e \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12*\n\x06x_sync\x18\x1f \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x30\n\tsync_file\x18\x86\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x07_shared\x18\xa2\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12,\n\x06run_id\x18k \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12-\n\x07run_url\x18q \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12-\n\x07project\x18\x61 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x06\x65ntity\x18\x45 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x33\n\x0corganization\x18\xbc\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0cx_start_time\x18) \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12.\n\x08root_dir\x18i \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12-\n\x07log_dir\x18U \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0clog_internal\x18V \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0cignore_globs\x18N \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12.\n\x08\x62\x61se_url\x18\x39 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12=\n\x17x_file_stream_max_bytes\x18\xac\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x46\n\x1fx_file_stream_transmit_interval\x18\xaf\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x45\n\x14x_extra_http_headers\x18\x0e \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12=\n\x17x_file_stream_retry_max\x18\x93\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12K\n$x_file_stream_retry_wait_min_seconds\x18\x94\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12K\n$x_file_stream_retry_wait_max_seconds\x18\x95\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x43\n\x1dx_file_stream_timeout_seconds\x18\x0f \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x42\n\x1cx_file_stream_max_line_bytes\x18\xb2\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12?\n\x19x_file_transfer_retry_max\x18\x96\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12M\n&x_file_transfer_retry_wait_min_seconds\x18\x97\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12M\n&x_file_transfer_retry_wait_max_seconds\x18\x98\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x46\n\x1fx_file_transfer_timeout_seconds\x18\x99\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x39\n\x13x_graphql_retry_max\x18\x9a\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12G\n x_graphql_retry_wait_min_seconds\x18\x9b\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12G\n x_graphql_retry_wait_max_seconds\x18\x9c\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12@\n\x19x_graphql_timeout_seconds\x18\x9d\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x31\n\nhttp_proxy\x18\xa8\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0bhttps_proxy\x18\xa9\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12;\n\tx_proxies\x18\xc8\x01 \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12-\n\x07program\x18_ \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0fprogram_relpath\x18` \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x37\n\x10_code_path_local\x18\xa3\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x36\n\x0fprogram_abspath\x18\x9f\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x05_args\x18\x01 \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12)\n\x03_os\x18 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x06\x64ocker\x18\x43 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0cx_executable\x18\r \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12-\n\x07_python\x18\" \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x30\n\tcolab_url\x18\xa0\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12*\n\x04host\x18M \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x08username\x18\x8d\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12+\n\x05\x65mail\x18\x44 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x06resume\x18\x66 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x0bresume_from\x18\xa7\x01 \x01(\x0b\x32\x19.wandb_internal.RunMoment\x12-\n\tfork_from\x18\xa4\x01 \x01(\x0b\x32\x19.wandb_internal.RunMoment\x12\x38\n\x14\x64isable_job_creation\x18\x41 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x30\n\tsweep_url\x18\x83\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12;\n\x16x_disable_update_check\x18\xa5\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x32\n\x0ex_disable_meta\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12-\n\tsave_code\x18s \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\x0b\x64isable_git\x18? \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12;\n\x16x_disable_machine_info\x18\x9e\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x33\n\x0fx_disable_stats\x18\n \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x39\n\x13x_stats_buffer_size\x18\xa1\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12@\n\x19x_stats_sampling_interval\x18\xae\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x30\n\x0bx_stats_pid\x18* \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12<\n\x12x_stats_disk_paths\x18\x92\x01 \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12H\n\"x_stats_neuron_monitor_config_path\x18. \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12<\n\x15x_stats_dcgm_exporter\x18\xbb\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12O\n\x1ex_stats_open_metrics_endpoints\x18/ \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12H\n\x1cx_stats_open_metrics_filters\x18\x30 \x01(\x0b\x32\".wandb_internal.OpenMetricsFilters\x12S\n!x_stats_open_metrics_http_headers\x18\xb8\x01 \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12=\n\x16x_stats_gpu_device_ids\x18\xba\x01 \x01(\x0b\x32\x1c.wandb_internal.ListIntValue\x12\x37\n\x11x_stats_cpu_count\x18\xc2\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12?\n\x19x_stats_cpu_logical_count\x18\xc3\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x37\n\x11x_stats_gpu_count\x18\xc4\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x37\n\x10x_stats_gpu_type\x18\xc5\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12?\n\x1ax_stats_track_process_tree\x18\xc6\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12.\n\x07x_label\x18\xb5\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\tx_primary\x18\xb6\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12:\n\x15x_update_finish_state\x18\xb7\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12<\n\x17\x61llow_offline_artifacts\x18\xb1\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12-\n\x07\x63onsole\x18< \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x36\n\x11\x63onsole_multipart\x18\xa6\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x35\n\x10sync_tensorboard\x18\xb3\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x42\n\x1dx_server_side_derived_summary\x18\xbd\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x46\n!x_server_side_expand_glob_metrics\x18\xbe\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12;\n\x16x_skip_transaction_log\x18\xbf\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12J\n#x_stats_coreweave_metadata_base_url\x18\xc0\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12J\n#x_stats_coreweave_metadata_endpoint\x18\xc1\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x0b_aws_lambda\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x33\n\x0fx_cli_only_mode\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12*\n\x06_colab\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x34\n\x10x_disable_viewer\x18\x0b \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x39\n\x15x_flow_control_custom\x18\x10 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12;\n\x17x_flow_control_disabled\x18\x11 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12>\n\x18x_internal_check_process\x18\x12 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12,\n\x08_ipython\x18\x14 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12,\n\x08_jupyter\x18\x15 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x34\n\x0ex_jupyter_root\x18\x16 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12+\n\x07_kaggle\x18\x17 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12=\n\x18x_live_policy_rate_limit\x18\x18 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12<\n\x17x_live_policy_wait_time\x18\x19 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x30\n\x0bx_log_level\x18\x1a \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x35\n\x10x_network_buffer\x18\x1b \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12)\n\x05_noop\x18\x1c \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12-\n\t_notebook\x18\x1d \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\t_platform\x18! \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x38\n\x12x_runqueue_item_id\x18# \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x37\n\x13x_save_requirements\x18% \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x39\n\x13x_service_transport\x18& \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x34\n\x0ex_service_wait\x18\' \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x35\n\x0f_start_datetime\x18( \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x33\n\r_tmp_code_dir\x18\x31 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x08_windows\x18\x34 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x34\n\x10\x61llow_val_change\x18\x35 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\tanonymous\x18\x36 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12P\n\x1f\x61zure_account_url_to_access_key\x18\x38 \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12.\n\x08\x63ode_dir\x18: \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0c\x63onfig_paths\x18; \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12\x30\n\ndeployment\x18= \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x30\n\x0c\x64isable_code\x18> \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x31\n\rdisable_hints\x18@ \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12,\n\x08\x64isabled\x18\x42 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12)\n\x05\x66orce\x18G \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x30\n\ngit_commit\x18H \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x30\n\ngit_remote\x18I \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x34\n\x0egit_remote_url\x18J \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x08git_root\x18K \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x36\n\x11heartbeat_seconds\x18L \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x32\n\x0cinit_timeout\x18O \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12,\n\x08is_local\x18P \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x30\n\njob_source\x18Q \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x31\n\rlabel_disable\x18R \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12*\n\x06launch\x18S \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x38\n\x12launch_config_path\x18T \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12:\n\x14log_symlink_internal\x18W \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x36\n\x10log_symlink_user\x18X \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x08log_user\x18Y \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x33\n\rlogin_timeout\x18Z \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12*\n\x04mode\x18\\ \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x33\n\rnotebook_name\x18] \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x31\n\x0bproject_url\x18\x62 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12)\n\x05quiet\x18\x63 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12+\n\x07relogin\x18\x65 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x32\n\x0cresume_fname\x18g \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12+\n\x07resumed\x18h \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\trun_group\x18j \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0crun_job_type\x18l \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x08run_mode\x18m \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x08run_name\x18n \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\trun_notes\x18o \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x31\n\x08run_tags\x18p \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12\x35\n\x11sagemaker_disable\x18r \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x35\n\x0fsettings_system\x18t \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x38\n\x12settings_workspace\x18u \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x0bshow_colors\x18v \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12.\n\nshow_emoji\x18w \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\x0bshow_errors\x18x \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12-\n\tshow_info\x18y \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x31\n\rshow_warnings\x18z \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12*\n\x06silent\x18{ \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x32\n\x0cstart_method\x18| \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12*\n\x06strict\x18} \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x33\n\x0esummary_errors\x18~ \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x34\n\x0fsummary_timeout\x18\x7f \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x36\n\x10summary_warnings\x18\x80\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12/\n\x08sweep_id\x18\x81\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x37\n\x10sweep_param_path\x18\x82\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x07symlink\x18\x84\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\x08sync_dir\x18\x85\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12:\n\x13sync_symlink_latest\x18\x87\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12J\n%table_raise_on_max_row_limit_exceeded\x18\x8a\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\x08timespec\x18\x8b\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x07tmp_dir\x18\x8c\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x30\n\twandb_dir\x18\x8e\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0ex_jupyter_name\x18\x8f\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0ex_jupyter_path\x18\x90\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x08job_name\x18\x91\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValueJ\x04\x08\x03\x10\x04J\x04\x08\x06\x10\x07J\x04\x08\x08\x10\tJ\x04\x08\t\x10\nJ\x04\x08\x0c\x10\rJ\x04\x08\x13\x10\x14J\x04\x08$\x10%J\x04\x08+\x10,J\x04\x08,\x10-J\x04\x08-\x10.J\x04\x08\x32\x10\x33J\x04\x08\x33\x10\x34J\x04\x08\x46\x10GJ\x04\x08[\x10\\J\x04\x08^\x10_J\x04\x08\x64\x10\x65J\x06\x08\x88\x01\x10\x89\x01J\x06\x08\x89\x01\x10\x8a\x01J\x06\x08\xad\x01\x10\xae\x01J\x06\x08\xb0\x01\x10\xb1\x01J\x06\x08\xb4\x01\x10\xb5\x01\x42\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+
+
+_LISTSTRINGVALUE = DESCRIPTOR.message_types_by_name['ListStringValue']
+_LISTINTVALUE = DESCRIPTOR.message_types_by_name['ListIntValue']
+_MAPSTRINGKEYSTRINGVALUE = DESCRIPTOR.message_types_by_name['MapStringKeyStringValue']
+_MAPSTRINGKEYSTRINGVALUE_VALUEENTRY = _MAPSTRINGKEYSTRINGVALUE.nested_types_by_name['ValueEntry']
+_MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE = DESCRIPTOR.message_types_by_name['MapStringKeyMapStringKeyStringValue']
+_MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY = _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE.nested_types_by_name['ValueEntry']
+_OPENMETRICSFILTERS = DESCRIPTOR.message_types_by_name['OpenMetricsFilters']
+_RUNMOMENT = DESCRIPTOR.message_types_by_name['RunMoment']
+_SETTINGS = DESCRIPTOR.message_types_by_name['Settings']
+ListStringValue = _reflection.GeneratedProtocolMessageType('ListStringValue', (_message.Message,), {
+ 'DESCRIPTOR' : _LISTSTRINGVALUE,
+ '__module__' : 'wandb.proto.wandb_settings_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ListStringValue)
+ })
+_sym_db.RegisterMessage(ListStringValue)
+
+ListIntValue = _reflection.GeneratedProtocolMessageType('ListIntValue', (_message.Message,), {
+ 'DESCRIPTOR' : _LISTINTVALUE,
+ '__module__' : 'wandb.proto.wandb_settings_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ListIntValue)
+ })
+_sym_db.RegisterMessage(ListIntValue)
+
+MapStringKeyStringValue = _reflection.GeneratedProtocolMessageType('MapStringKeyStringValue', (_message.Message,), {
+
+ 'ValueEntry' : _reflection.GeneratedProtocolMessageType('ValueEntry', (_message.Message,), {
+ 'DESCRIPTOR' : _MAPSTRINGKEYSTRINGVALUE_VALUEENTRY,
+ '__module__' : 'wandb.proto.wandb_settings_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.MapStringKeyStringValue.ValueEntry)
+ })
+ ,
+ 'DESCRIPTOR' : _MAPSTRINGKEYSTRINGVALUE,
+ '__module__' : 'wandb.proto.wandb_settings_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.MapStringKeyStringValue)
+ })
+_sym_db.RegisterMessage(MapStringKeyStringValue)
+_sym_db.RegisterMessage(MapStringKeyStringValue.ValueEntry)
+
+MapStringKeyMapStringKeyStringValue = _reflection.GeneratedProtocolMessageType('MapStringKeyMapStringKeyStringValue', (_message.Message,), {
+
+ 'ValueEntry' : _reflection.GeneratedProtocolMessageType('ValueEntry', (_message.Message,), {
+ 'DESCRIPTOR' : _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY,
+ '__module__' : 'wandb.proto.wandb_settings_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.MapStringKeyMapStringKeyStringValue.ValueEntry)
+ })
+ ,
+ 'DESCRIPTOR' : _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE,
+ '__module__' : 'wandb.proto.wandb_settings_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.MapStringKeyMapStringKeyStringValue)
+ })
+_sym_db.RegisterMessage(MapStringKeyMapStringKeyStringValue)
+_sym_db.RegisterMessage(MapStringKeyMapStringKeyStringValue.ValueEntry)
+
+OpenMetricsFilters = _reflection.GeneratedProtocolMessageType('OpenMetricsFilters', (_message.Message,), {
+ 'DESCRIPTOR' : _OPENMETRICSFILTERS,
+ '__module__' : 'wandb.proto.wandb_settings_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.OpenMetricsFilters)
+ })
+_sym_db.RegisterMessage(OpenMetricsFilters)
+
+RunMoment = _reflection.GeneratedProtocolMessageType('RunMoment', (_message.Message,), {
+ 'DESCRIPTOR' : _RUNMOMENT,
+ '__module__' : 'wandb.proto.wandb_settings_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.RunMoment)
+ })
+_sym_db.RegisterMessage(RunMoment)
+
+Settings = _reflection.GeneratedProtocolMessageType('Settings', (_message.Message,), {
+ 'DESCRIPTOR' : _SETTINGS,
+ '__module__' : 'wandb.proto.wandb_settings_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.Settings)
+ })
+_sym_db.RegisterMessage(Settings)
+
+if _descriptor._USE_C_DESCRIPTORS == False:
+
+ DESCRIPTOR._options = None
+ DESCRIPTOR._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _MAPSTRINGKEYSTRINGVALUE_VALUEENTRY._options = None
+ _MAPSTRINGKEYSTRINGVALUE_VALUEENTRY._serialized_options = b'8\001'
+ _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY._options = None
+ _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY._serialized_options = b'8\001'
+ _LISTSTRINGVALUE._serialized_start=84
+ _LISTSTRINGVALUE._serialized_end=116
+ _LISTINTVALUE._serialized_start=118
+ _LISTINTVALUE._serialized_end=147
+ _MAPSTRINGKEYSTRINGVALUE._serialized_start=150
+ _MAPSTRINGKEYSTRINGVALUE._serialized_end=288
+ _MAPSTRINGKEYSTRINGVALUE_VALUEENTRY._serialized_start=244
+ _MAPSTRINGKEYSTRINGVALUE_VALUEENTRY._serialized_end=288
+ _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE._serialized_start=291
+ _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE._serialized_end=494
+ _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY._serialized_start=409
+ _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY._serialized_end=494
+ _OPENMETRICSFILTERS._serialized_start=497
+ _OPENMETRICSFILTERS._serialized_end=651
+ _RUNMOMENT._serialized_start=653
+ _RUNMOMENT._serialized_end=708
+ _SETTINGS._serialized_start=711
+ _SETTINGS._serialized_end=10633
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/wandb_sync_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/wandb_sync_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..6bedc80994d21be33a47a5652b8ae278df8a5cdd
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/wandb_sync_pb2.py
@@ -0,0 +1,100 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: wandb/proto/wandb_sync.proto
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import message as _message
+from google.protobuf import reflection as _reflection
+from google.protobuf import symbol_database as _symbol_database
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from wandb.proto import wandb_internal_pb2 as wandb_dot_proto_dot_wandb__internal__pb2
+from wandb.proto import wandb_settings_pb2 as wandb_dot_proto_dot_wandb__settings__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1cwandb/proto/wandb_sync.proto\x12\x0ewandb_internal\x1a wandb/proto/wandb_internal.proto\x1a wandb/proto/wandb_settings.proto\"Q\n\x15ServerInitSyncRequest\x12\x0c\n\x04path\x18\x01 \x03(\t\x12*\n\x08settings\x18\x02 \x01(\x0b\x32\x18.wandb_internal.Settings\"$\n\x16ServerInitSyncResponse\x12\n\n\x02id\x18\x01 \x01(\t\"4\n\x11ServerSyncRequest\x12\n\n\x02id\x18\x01 \x01(\t\x12\x13\n\x0bparallelism\x18\x02 \x01(\r\"I\n\x12ServerSyncResponse\x12\x33\n\x08messages\x18\x01 \x03(\x0b\x32!.wandb_internal.ServerSyncMessage\"%\n\x17ServerSyncStatusRequest\x12\n\n\x02id\x18\x01 \x01(\t\"\x82\x01\n\x18ServerSyncStatusResponse\x12-\n\x05stats\x18\x01 \x01(\x0b\x32\x1e.wandb_internal.OperationStats\x12\x37\n\x0cnew_messages\x18\x02 \x03(\x0b\x32!.wandb_internal.ServerSyncMessage\"\xaa\x01\n\x11ServerSyncMessage\x12<\n\x08severity\x18\x01 \x01(\x0e\x32*.wandb_internal.ServerSyncMessage.Severity\x12\x0f\n\x07\x63ontent\x18\x02 \x01(\t\"F\n\x08Severity\x12\x13\n\x0fSEVERITY_NOTSET\x10\x00\x12\x11\n\rSEVERITY_INFO\x10\x14\x12\x12\n\x0eSEVERITY_ERROR\x10(B\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+
+
+_SERVERINITSYNCREQUEST = DESCRIPTOR.message_types_by_name['ServerInitSyncRequest']
+_SERVERINITSYNCRESPONSE = DESCRIPTOR.message_types_by_name['ServerInitSyncResponse']
+_SERVERSYNCREQUEST = DESCRIPTOR.message_types_by_name['ServerSyncRequest']
+_SERVERSYNCRESPONSE = DESCRIPTOR.message_types_by_name['ServerSyncResponse']
+_SERVERSYNCSTATUSREQUEST = DESCRIPTOR.message_types_by_name['ServerSyncStatusRequest']
+_SERVERSYNCSTATUSRESPONSE = DESCRIPTOR.message_types_by_name['ServerSyncStatusResponse']
+_SERVERSYNCMESSAGE = DESCRIPTOR.message_types_by_name['ServerSyncMessage']
+_SERVERSYNCMESSAGE_SEVERITY = _SERVERSYNCMESSAGE.enum_types_by_name['Severity']
+ServerInitSyncRequest = _reflection.GeneratedProtocolMessageType('ServerInitSyncRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERINITSYNCREQUEST,
+ '__module__' : 'wandb.proto.wandb_sync_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerInitSyncRequest)
+ })
+_sym_db.RegisterMessage(ServerInitSyncRequest)
+
+ServerInitSyncResponse = _reflection.GeneratedProtocolMessageType('ServerInitSyncResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERINITSYNCRESPONSE,
+ '__module__' : 'wandb.proto.wandb_sync_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerInitSyncResponse)
+ })
+_sym_db.RegisterMessage(ServerInitSyncResponse)
+
+ServerSyncRequest = _reflection.GeneratedProtocolMessageType('ServerSyncRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERSYNCREQUEST,
+ '__module__' : 'wandb.proto.wandb_sync_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerSyncRequest)
+ })
+_sym_db.RegisterMessage(ServerSyncRequest)
+
+ServerSyncResponse = _reflection.GeneratedProtocolMessageType('ServerSyncResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERSYNCRESPONSE,
+ '__module__' : 'wandb.proto.wandb_sync_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerSyncResponse)
+ })
+_sym_db.RegisterMessage(ServerSyncResponse)
+
+ServerSyncStatusRequest = _reflection.GeneratedProtocolMessageType('ServerSyncStatusRequest', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERSYNCSTATUSREQUEST,
+ '__module__' : 'wandb.proto.wandb_sync_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerSyncStatusRequest)
+ })
+_sym_db.RegisterMessage(ServerSyncStatusRequest)
+
+ServerSyncStatusResponse = _reflection.GeneratedProtocolMessageType('ServerSyncStatusResponse', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERSYNCSTATUSRESPONSE,
+ '__module__' : 'wandb.proto.wandb_sync_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerSyncStatusResponse)
+ })
+_sym_db.RegisterMessage(ServerSyncStatusResponse)
+
+ServerSyncMessage = _reflection.GeneratedProtocolMessageType('ServerSyncMessage', (_message.Message,), {
+ 'DESCRIPTOR' : _SERVERSYNCMESSAGE,
+ '__module__' : 'wandb.proto.wandb_sync_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.ServerSyncMessage)
+ })
+_sym_db.RegisterMessage(ServerSyncMessage)
+
+if _descriptor._USE_C_DESCRIPTORS == False:
+
+ DESCRIPTOR._options = None
+ DESCRIPTOR._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _SERVERINITSYNCREQUEST._serialized_start=116
+ _SERVERINITSYNCREQUEST._serialized_end=197
+ _SERVERINITSYNCRESPONSE._serialized_start=199
+ _SERVERINITSYNCRESPONSE._serialized_end=235
+ _SERVERSYNCREQUEST._serialized_start=237
+ _SERVERSYNCREQUEST._serialized_end=289
+ _SERVERSYNCRESPONSE._serialized_start=291
+ _SERVERSYNCRESPONSE._serialized_end=364
+ _SERVERSYNCSTATUSREQUEST._serialized_start=366
+ _SERVERSYNCSTATUSREQUEST._serialized_end=403
+ _SERVERSYNCSTATUSRESPONSE._serialized_start=406
+ _SERVERSYNCSTATUSRESPONSE._serialized_end=536
+ _SERVERSYNCMESSAGE._serialized_start=539
+ _SERVERSYNCMESSAGE._serialized_end=709
+ _SERVERSYNCMESSAGE_SEVERITY._serialized_start=639
+ _SERVERSYNCMESSAGE_SEVERITY._serialized_end=709
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/wandb_telemetry_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/wandb_telemetry_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..766fbb092ac04113643a107a54d18b76c39bdd22
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v3/wandb_telemetry_pb2.py
@@ -0,0 +1,106 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: wandb/proto/wandb_telemetry.proto
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import message as _message
+from google.protobuf import reflection as _reflection
+from google.protobuf import symbol_database as _symbol_database
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n!wandb/proto/wandb_telemetry.proto\x12\x0ewandb_internal\x1a\x1cwandb/proto/wandb_base.proto\"\xdb\x03\n\x0fTelemetryRecord\x12-\n\x0cimports_init\x18\x01 \x01(\x0b\x32\x17.wandb_internal.Imports\x12/\n\x0eimports_finish\x18\x02 \x01(\x0b\x32\x17.wandb_internal.Imports\x12(\n\x07\x66\x65\x61ture\x18\x03 \x01(\x0b\x32\x17.wandb_internal.Feature\x12\x16\n\x0epython_version\x18\x04 \x01(\t\x12\x13\n\x0b\x63li_version\x18\x05 \x01(\t\x12\x1b\n\x13huggingface_version\x18\x06 \x01(\t\x12 \n\x03\x65nv\x18\x08 \x01(\x0b\x32\x13.wandb_internal.Env\x12%\n\x05label\x18\t \x01(\x0b\x32\x16.wandb_internal.Labels\x12.\n\ndeprecated\x18\n \x01(\x0b\x32\x1a.wandb_internal.Deprecated\x12&\n\x06issues\x18\x0b \x01(\x0b\x32\x16.wandb_internal.Issues\x12\x14\n\x0c\x63ore_version\x18\x0c \x01(\t\x12\x10\n\x08platform\x18\r \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x11\n\x0fTelemetryResult\"\xa8\x0e\n\x07Imports\x12\r\n\x05torch\x18\x01 \x01(\x08\x12\r\n\x05keras\x18\x02 \x01(\x08\x12\x12\n\ntensorflow\x18\x03 \x01(\x08\x12\x0e\n\x06\x66\x61stai\x18\x04 \x01(\x08\x12\x0f\n\x07sklearn\x18\x05 \x01(\x08\x12\x0f\n\x07xgboost\x18\x06 \x01(\x08\x12\x10\n\x08\x63\x61tboost\x18\x07 \x01(\x08\x12\x10\n\x08lightgbm\x18\x08 \x01(\x08\x12\x19\n\x11pytorch_lightning\x18\t \x01(\x08\x12\x0e\n\x06ignite\x18\n \x01(\x08\x12\x14\n\x0ctransformers\x18\x0b \x01(\x08\x12\x0b\n\x03jax\x18\x0c \x01(\x08\x12\x10\n\x08metaflow\x18\r \x01(\x08\x12\x10\n\x08\x61llennlp\x18\x0e \x01(\x08\x12\x11\n\tautogluon\x18\x0f \x01(\x08\x12\x11\n\tautokeras\x18\x10 \x01(\x08\x12\x10\n\x08\x63\x61talyst\x18\x12 \x01(\x08\x12\x10\n\x08\x64\x65\x65pchem\x18\x15 \x01(\x08\x12\x0f\n\x07\x64\x65\x65pctr\x18\x16 \x01(\x08\x12\x0f\n\x07pycaret\x18\x1c \x01(\x08\x12\x14\n\x0cpytorchvideo\x18\x1d \x01(\x08\x12\x0b\n\x03ray\x18\x1e \x01(\x08\x12\x1a\n\x12simpletransformers\x18\x1f \x01(\x08\x12\x0e\n\x06skorch\x18 \x01(\x08\x12\r\n\x05spacy\x18! \x01(\x08\x12\r\n\x05\x66lash\x18\" \x01(\x08\x12\x0e\n\x06optuna\x18# \x01(\x08\x12\x0f\n\x07recbole\x18$ \x01(\x08\x12\x0c\n\x04mmcv\x18% \x01(\x08\x12\r\n\x05mmdet\x18& \x01(\x08\x12\x11\n\ttorchdrug\x18\' \x01(\x08\x12\x11\n\ttorchtext\x18( \x01(\x08\x12\x13\n\x0btorchvision\x18) \x01(\x08\x12\r\n\x05\x65legy\x18* \x01(\x08\x12\x12\n\ndetectron2\x18+ \x01(\x08\x12\r\n\x05\x66lair\x18, \x01(\x08\x12\x0c\n\x04\x66lax\x18- \x01(\x08\x12\x0c\n\x04syft\x18. \x01(\x08\x12\x0b\n\x03TTS\x18/ \x01(\x08\x12\r\n\x05monai\x18\x30 \x01(\x08\x12\x17\n\x0fhuggingface_hub\x18\x31 \x01(\x08\x12\r\n\x05hydra\x18\x32 \x01(\x08\x12\x10\n\x08\x64\x61tasets\x18\x33 \x01(\x08\x12\x0e\n\x06sacred\x18\x34 \x01(\x08\x12\x0e\n\x06joblib\x18\x35 \x01(\x08\x12\x0c\n\x04\x64\x61sk\x18\x36 \x01(\x08\x12\x11\n\tpaddleocr\x18\x38 \x01(\x08\x12\r\n\x05ppdet\x18\x39 \x01(\x08\x12\x11\n\tpaddleseg\x18: \x01(\x08\x12\x11\n\tpaddlenlp\x18; \x01(\x08\x12\r\n\x05mmseg\x18< \x01(\x08\x12\r\n\x05mmocr\x18= \x01(\x08\x12\r\n\x05mmcls\x18> \x01(\x08\x12\x0c\n\x04timm\x18? \x01(\x08\x12\x0f\n\x07\x66\x61irseq\x18@ \x01(\x08\x12\x12\n\ndeepchecks\x18\x41 \x01(\x08\x12\x10\n\x08\x63omposer\x18\x42 \x01(\x08\x12\x10\n\x08sparseml\x18\x43 \x01(\x08\x12\x10\n\x08\x61nomalib\x18\x44 \x01(\x08\x12\r\n\x05zenml\x18\x45 \x01(\x08\x12\x12\n\ncolossalai\x18\x46 \x01(\x08\x12\x12\n\naccelerate\x18G \x01(\x08\x12\x0e\n\x06merlin\x18H \x01(\x08\x12\x0f\n\x07nanodet\x18I \x01(\x08\x12#\n\x1bsegmentation_models_pytorch\x18J \x01(\x08\x12\x1d\n\x15sentence_transformers\x18K \x01(\x08\x12\x0b\n\x03\x64gl\x18L \x01(\x08\x12\x17\n\x0ftorch_geometric\x18M \x01(\x08\x12\x0c\n\x04jina\x18N \x01(\x08\x12\x0e\n\x06kornia\x18O \x01(\x08\x12\x16\n\x0e\x61lbumentations\x18P \x01(\x08\x12\x10\n\x08keras_cv\x18Q \x01(\x08\x12\x10\n\x08mmengine\x18R \x01(\x08\x12\x11\n\tdiffusers\x18S \x01(\x08\x12\x0b\n\x03trl\x18T \x01(\x08\x12\x0c\n\x04trlx\x18U \x01(\x08\x12\x11\n\tlangchain\x18V \x01(\x08\x12\x13\n\x0bllama_index\x18W \x01(\x08\x12\x15\n\rstability_sdk\x18X \x01(\x08\x12\x0f\n\x07prefect\x18Y \x01(\x08\x12\x13\n\x0bprefect_ray\x18Z \x01(\x08\x12\x10\n\x08pinecone\x18[ \x01(\x08\x12\x10\n\x08\x63hromadb\x18\\ \x01(\x08\x12\x10\n\x08weaviate\x18] \x01(\x08\x12\x13\n\x0bpromptlayer\x18^ \x01(\x08\x12\x0e\n\x06openai\x18_ \x01(\x08\x12\x0e\n\x06\x63ohere\x18` \x01(\x08\x12\x11\n\tanthropic\x18\x61 \x01(\x08\x12\x0c\n\x04peft\x18\x62 \x01(\x08\x12\x0f\n\x07optimum\x18\x63 \x01(\x08\x12\x10\n\x08\x65valuate\x18\x64 \x01(\x08\x12\x10\n\x08langflow\x18\x65 \x01(\x08\x12\x12\n\nkeras_core\x18\x66 \x01(\x08\x12\x18\n\x10lightning_fabric\x18g \x01(\x08\x12\x1c\n\x14\x63urated_transformers\x18h \x01(\x08\x12\x0e\n\x06orjson\x18i \x01(\x08\x12\x11\n\tlightning\x18j \x01(\x08\x12\x0c\n\x04\x64spy\x18k \x01(\x08J\x04\x08\x11\x10\x12J\x04\x08\x13\x10\x14J\x04\x08\x14\x10\x15J\x04\x08\x17\x10\x18J\x04\x08\x18\x10\x19J\x04\x08\x19\x10\x1aJ\x04\x08\x1a\x10\x1bJ\x04\x08\x1b\x10\x1cJ\x04\x08\x37\x10\x38\"\xac\r\n\x07\x46\x65\x61ture\x12\r\n\x05watch\x18\x01 \x01(\x08\x12\x0e\n\x06\x66inish\x18\x02 \x01(\x08\x12\x0c\n\x04save\x18\x03 \x01(\x08\x12\x0f\n\x07offline\x18\x04 \x01(\x08\x12\x0f\n\x07resumed\x18\x05 \x01(\x08\x12\x0c\n\x04grpc\x18\x06 \x01(\x08\x12\x0e\n\x06metric\x18\x07 \x01(\x08\x12\r\n\x05keras\x18\x08 \x01(\x08\x12\x11\n\tsagemaker\x18\t \x01(\x08\x12\x1c\n\x14\x61rtifact_incremental\x18\n \x01(\x08\x12\x10\n\x08metaflow\x18\x0b \x01(\x08\x12\x0f\n\x07prodigy\x18\x0c \x01(\x08\x12\x15\n\rset_init_name\x18\r \x01(\x08\x12\x13\n\x0bset_init_id\x18\x0e \x01(\x08\x12\x15\n\rset_init_tags\x18\x0f \x01(\x08\x12\x17\n\x0fset_init_config\x18\x10 \x01(\x08\x12\x14\n\x0cset_run_name\x18\x11 \x01(\x08\x12\x14\n\x0cset_run_tags\x18\x12 \x01(\x08\x12\x17\n\x0fset_config_item\x18\x13 \x01(\x08\x12\x0e\n\x06launch\x18\x14 \x01(\x08\x12\x1c\n\x14torch_profiler_trace\x18\x15 \x01(\x08\x12\x0b\n\x03sb3\x18\x16 \x01(\x08\x12\x17\n\x0finit_return_run\x18\x18 \x01(\x08\x12\x1f\n\x17lightgbm_wandb_callback\x18\x19 \x01(\x08\x12\x1c\n\x14lightgbm_log_summary\x18\x1a \x01(\x08\x12\x1f\n\x17\x63\x61tboost_wandb_callback\x18\x1b \x01(\x08\x12\x1c\n\x14\x63\x61tboost_log_summary\x18\x1c \x01(\x08\x12\x17\n\x0ftensorboard_log\x18\x1d \x01(\x08\x12\x16\n\x0e\x65stimator_hook\x18\x1e \x01(\x08\x12\x1e\n\x16xgboost_wandb_callback\x18\x1f \x01(\x08\x12\"\n\x1axgboost_old_wandb_callback\x18 \x01(\x08\x12\x0e\n\x06\x61ttach\x18! \x01(\x08\x12\x19\n\x11tensorboard_patch\x18\" \x01(\x08\x12\x18\n\x10tensorboard_sync\x18# \x01(\x08\x12\x15\n\rkfp_wandb_log\x18$ \x01(\x08\x12\x1b\n\x13maybe_run_overwrite\x18% \x01(\x08\x12\x1c\n\x14keras_metrics_logger\x18& \x01(\x08\x12\x1e\n\x16keras_model_checkpoint\x18\' \x01(\x08\x12!\n\x19keras_wandb_eval_callback\x18( \x01(\x08\x12\x1d\n\x15\x66low_control_overflow\x18) \x01(\x08\x12\x0c\n\x04sync\x18* \x01(\x08\x12\x1d\n\x15\x66low_control_disabled\x18+ \x01(\x08\x12\x1b\n\x13\x66low_control_custom\x18, \x01(\x08\x12\x14\n\x0copen_metrics\x18. \x01(\x08\x12\x1a\n\x12ultralytics_yolov8\x18/ \x01(\x08\x12\x17\n\x0fimporter_mlflow\x18\x30 \x01(\x08\x12\x15\n\rsync_tfevents\x18\x31 \x01(\x08\x12\x15\n\rasync_uploads\x18\x32 \x01(\x08\x12\x16\n\x0eopenai_autolog\x18\x33 \x01(\x08\x12\x18\n\x10langchain_tracer\x18\x34 \x01(\x08\x12\x16\n\x0e\x63ohere_autolog\x18\x35 \x01(\x08\x12\x1b\n\x13hf_pipeline_autolog\x18\x36 \x01(\x08\x12\r\n\x05lib_c\x18\x38 \x01(\x08\x12\x0f\n\x07lib_cpp\x18\x39 \x01(\x08\x12\x19\n\x11openai_finetuning\x18: \x01(\x08\x12\x19\n\x11\x64iffusers_autolog\x18; \x01(\x08\x12\x1f\n\x17lightning_fabric_logger\x18< \x01(\x08\x12\x14\n\x0cset_step_log\x18= \x01(\x08\x12\x13\n\x0bset_summary\x18> \x01(\x08\x12\x16\n\x0emetric_summary\x18? \x01(\x08\x12\x13\n\x0bmetric_goal\x18@ \x01(\x08\x12\x15\n\rmetric_hidden\x18\x41 \x01(\x08\x12\x18\n\x10metric_step_sync\x18\x42 \x01(\x08\x12\x13\n\x0bshared_mode\x18\x43 \x01(\x08\x12#\n\x1bserver_side_derived_summary\x18\x44 \x01(\x08\x12\x1b\n\x13user_provided_label\x18\x45 \x01(\x08\x12\x1e\n\x16\x64\x63gm_profiling_enabled\x18\x46 \x01(\x08\x12\x11\n\tfork_mode\x18G \x01(\x08\x12\x13\n\x0brewind_mode\x18H \x01(\x08\x12\x15\n\rdspy_callback\x18I \x01(\x08J\x04\x08\x17\x10\x18J\x04\x08-\x10.J\x04\x08\x37\x10\x38\"\xc9\x01\n\x03\x45nv\x12\x0f\n\x07jupyter\x18\x01 \x01(\x08\x12\x0e\n\x06kaggle\x18\x02 \x01(\x08\x12\x0f\n\x07windows\x18\x03 \x01(\x08\x12\x0e\n\x06m1_gpu\x18\x04 \x01(\x08\x12\x10\n\x08trainium\x18\n \x01(\x08\x12\x0b\n\x03pex\x18\x0b \x01(\x08\x12\r\n\x05\x63olab\x18\x0c \x01(\x08\x12\x0f\n\x07ipython\x18\r \x01(\x08\x12\x12\n\naws_lambda\x18\x0e \x01(\x08\x12\x0f\n\x07\x61md_gpu\x18\x0f \x01(\x08J\x04\x08\x05\x10\x06J\x04\x08\x06\x10\x07J\x04\x08\x07\x10\x08J\x04\x08\x08\x10\tJ\x04\x08\t\x10\n\"H\n\x06Labels\x12\x13\n\x0b\x63ode_string\x18\x01 \x01(\t\x12\x13\n\x0brepo_string\x18\x02 \x01(\t\x12\x14\n\x0c\x63ode_version\x18\x03 \x01(\t\"\xc2\x06\n\nDeprecated\x12!\n\x19keras_callback__data_type\x18\x01 \x01(\x08\x12\r\n\x05plots\x18\x05 \x01(\x08\x12!\n\x19init__config_include_keys\x18\x07 \x01(\x08\x12!\n\x19init__config_exclude_keys\x18\x08 \x01(\x08\x12\"\n\x1akeras_callback__save_model\x18\t \x01(\x08\x12\x18\n\x10langchain_tracer\x18\n \x01(\x08\x12\x1a\n\x12\x61rtifact__get_path\x18\x0b \x01(\x08\x12#\n\x1b\x61rtifactmanifestentry__name\x18\x0c \x01(\x08\x12\x1e\n\x16\x61pi__artifact_versions\x18\r \x01(\x08\x12(\n artifact_collection__change_type\x18\x0e \x01(\x08\x12\x1f\n\x17run__define_metric_copy\x18\x0f \x01(\x08\x12\x14\n\x0crun_disabled\x18\x10 \x01(\x08\x12\x16\n\x0ekeras_callback\x18\x11 \x01(\x08\x12$\n\x1crun__define_metric_best_goal\x18\x12 \x01(\x08\x12\x19\n\x11run__finish_quiet\x18\x13 \x01(\x08\x12\x18\n\x10run__reinit_bool\x18\x14 \x01(\x08\x12\x14\n\x0crun__get_url\x18\x15 \x01(\x08\x12\x19\n\x11run__project_name\x18\x16 \x01(\x08\x12\x1c\n\x14run__get_project_url\x18\x17 \x01(\x08\x12\x1a\n\x12run__get_sweep_url\x18\x18 \x01(\x08\x12 \n\x18run__use_artifact_use_as\x18\x19 \x01(\x08\x12\x18\n\x10\x61rtifact__use_as\x18\x1a \x01(\x08\x12\x1d\n\x15\x61rtifact__init_use_as\x18\x1b \x01(\x08\x12\"\n\x1a\x62\x65ta__workflows__log_model\x18\x1c \x01(\x08\x12\"\n\x1a\x62\x65ta__workflows__use_model\x18\x1d \x01(\x08\x12#\n\x1b\x62\x65ta__workflows__link_model\x18\x1e \x01(\x08J\x04\x08\x02\x10\x03J\x04\x08\x03\x10\x04J\x04\x08\x04\x10\x05J\x04\x08\x06\x10\x07\"|\n\x06Issues\x12%\n\x1dsettings__validation_warnings\x18\x01 \x01(\x08\x12!\n\x19settings__unexpected_args\x18\x02 \x01(\x08\x12(\n settings__preprocessing_warnings\x18\x03 \x01(\x08\x42\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+
+
+_TELEMETRYRECORD = DESCRIPTOR.message_types_by_name['TelemetryRecord']
+_TELEMETRYRESULT = DESCRIPTOR.message_types_by_name['TelemetryResult']
+_IMPORTS = DESCRIPTOR.message_types_by_name['Imports']
+_FEATURE = DESCRIPTOR.message_types_by_name['Feature']
+_ENV = DESCRIPTOR.message_types_by_name['Env']
+_LABELS = DESCRIPTOR.message_types_by_name['Labels']
+_DEPRECATED = DESCRIPTOR.message_types_by_name['Deprecated']
+_ISSUES = DESCRIPTOR.message_types_by_name['Issues']
+TelemetryRecord = _reflection.GeneratedProtocolMessageType('TelemetryRecord', (_message.Message,), {
+ 'DESCRIPTOR' : _TELEMETRYRECORD,
+ '__module__' : 'wandb.proto.wandb_telemetry_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.TelemetryRecord)
+ })
+_sym_db.RegisterMessage(TelemetryRecord)
+
+TelemetryResult = _reflection.GeneratedProtocolMessageType('TelemetryResult', (_message.Message,), {
+ 'DESCRIPTOR' : _TELEMETRYRESULT,
+ '__module__' : 'wandb.proto.wandb_telemetry_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.TelemetryResult)
+ })
+_sym_db.RegisterMessage(TelemetryResult)
+
+Imports = _reflection.GeneratedProtocolMessageType('Imports', (_message.Message,), {
+ 'DESCRIPTOR' : _IMPORTS,
+ '__module__' : 'wandb.proto.wandb_telemetry_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.Imports)
+ })
+_sym_db.RegisterMessage(Imports)
+
+Feature = _reflection.GeneratedProtocolMessageType('Feature', (_message.Message,), {
+ 'DESCRIPTOR' : _FEATURE,
+ '__module__' : 'wandb.proto.wandb_telemetry_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.Feature)
+ })
+_sym_db.RegisterMessage(Feature)
+
+Env = _reflection.GeneratedProtocolMessageType('Env', (_message.Message,), {
+ 'DESCRIPTOR' : _ENV,
+ '__module__' : 'wandb.proto.wandb_telemetry_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.Env)
+ })
+_sym_db.RegisterMessage(Env)
+
+Labels = _reflection.GeneratedProtocolMessageType('Labels', (_message.Message,), {
+ 'DESCRIPTOR' : _LABELS,
+ '__module__' : 'wandb.proto.wandb_telemetry_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.Labels)
+ })
+_sym_db.RegisterMessage(Labels)
+
+Deprecated = _reflection.GeneratedProtocolMessageType('Deprecated', (_message.Message,), {
+ 'DESCRIPTOR' : _DEPRECATED,
+ '__module__' : 'wandb.proto.wandb_telemetry_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.Deprecated)
+ })
+_sym_db.RegisterMessage(Deprecated)
+
+Issues = _reflection.GeneratedProtocolMessageType('Issues', (_message.Message,), {
+ 'DESCRIPTOR' : _ISSUES,
+ '__module__' : 'wandb.proto.wandb_telemetry_pb2'
+ # @@protoc_insertion_point(class_scope:wandb_internal.Issues)
+ })
+_sym_db.RegisterMessage(Issues)
+
+if _descriptor._USE_C_DESCRIPTORS == False:
+
+ DESCRIPTOR._options = None
+ DESCRIPTOR._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _TELEMETRYRECORD._serialized_start=84
+ _TELEMETRYRECORD._serialized_end=559
+ _TELEMETRYRESULT._serialized_start=561
+ _TELEMETRYRESULT._serialized_end=578
+ _IMPORTS._serialized_start=581
+ _IMPORTS._serialized_end=2413
+ _FEATURE._serialized_start=2416
+ _FEATURE._serialized_end=4124
+ _ENV._serialized_start=4127
+ _ENV._serialized_end=4328
+ _LABELS._serialized_start=4330
+ _LABELS._serialized_end=4402
+ _DEPRECATED._serialized_start=4405
+ _DEPRECATED._serialized_end=5239
+ _ISSUES._serialized_start=5241
+ _ISSUES._serialized_end=5365
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/wandb_api_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/wandb_api_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..43687353a25d180e48a76100389f48805d0b7d52
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/wandb_api_pb2.py
@@ -0,0 +1,37 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: wandb/proto/wandb_api.proto
+"""Generated protocol buffer code."""
+from google.protobuf.internal import builder as _builder
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1bwandb/proto/wandb_api.proto\x12\x0ewandb_internal\x1a\x1cwandb/proto/wandb_base.proto\"]\n\nApiRequest\x12\x44\n\x10read_run_history\x18\x01 \x01(\x0b\x32(.wandb_internal.ReadRunHistoryApiRequestH\x00\x42\t\n\x07request\"`\n\x0b\x41piResponse\x12\x45\n\x10read_run_history\x18\x01 \x01(\x0b\x32).wandb_internal.ReadRunHistoryApiResponseH\x00\x42\n\n\x08response\"\xaa\x01\n\x18ReadRunHistoryApiRequest\x12\x0e\n\x06\x65ntity\x18\x01 \x01(\t\x12\x0f\n\x07project\x18\x02 \x01(\t\x12\x0e\n\x06run_id\x18\x03 \x01(\t\x12\x0c\n\x04keys\x18\x04 \x03(\t\x12\x10\n\x08min_step\x18\x05 \x01(\x03\x12\x10\n\x08max_step\x18\x06 \x01(\x03\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"d\n\x19ReadRunHistoryApiResponse\x12\x30\n\x0chistory_rows\x18\x01 \x03(\x0b\x32\x1a.wandb_internal.HistoryRow\x12\x15\n\rerror_message\x18\x02 \x01(\t\"G\n\nHistoryRow\x12\x39\n\rhistory_items\x18\x01 \x03(\x0b\x32\".wandb_internal.ParquetHistoryItem\"5\n\x12ParquetHistoryItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\tB\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_api_pb2', globals())
+if _descriptor._USE_C_DESCRIPTORS == False:
+
+ DESCRIPTOR._options = None
+ DESCRIPTOR._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _APIREQUEST._serialized_start=77
+ _APIREQUEST._serialized_end=170
+ _APIRESPONSE._serialized_start=172
+ _APIRESPONSE._serialized_end=268
+ _READRUNHISTORYAPIREQUEST._serialized_start=271
+ _READRUNHISTORYAPIREQUEST._serialized_end=441
+ _READRUNHISTORYAPIRESPONSE._serialized_start=443
+ _READRUNHISTORYAPIRESPONSE._serialized_end=543
+ _HISTORYROW._serialized_start=545
+ _HISTORYROW._serialized_end=616
+ _PARQUETHISTORYITEM._serialized_start=618
+ _PARQUETHISTORYITEM._serialized_end=671
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/wandb_base_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/wandb_base_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1df6042049011a6f2b2277569e2d6f011979a90
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/wandb_base_pb2.py
@@ -0,0 +1,30 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: wandb/proto/wandb_base.proto
+"""Generated protocol buffer code."""
+from google.protobuf.internal import builder as _builder
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1cwandb/proto/wandb_base.proto\x12\x0ewandb_internal\"6\n\x0b_RecordInfo\x12\x11\n\tstream_id\x18\x01 \x01(\t\x12\x14\n\x0c_tracelog_id\x18\x64 \x01(\t\"!\n\x0c_RequestInfo\x12\x11\n\tstream_id\x18\x01 \x01(\t\"#\n\x0b_ResultInfo\x12\x14\n\x0c_tracelog_id\x18\x64 \x01(\tB\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_base_pb2', globals())
+if _descriptor._USE_C_DESCRIPTORS == False:
+
+ DESCRIPTOR._options = None
+ DESCRIPTOR._serialized_options = b'Z\031core/pkg/service_go_proto'
+ __RECORDINFO._serialized_start=48
+ __RECORDINFO._serialized_end=102
+ __REQUESTINFO._serialized_start=104
+ __REQUESTINFO._serialized_end=137
+ __RESULTINFO._serialized_start=139
+ __RESULTINFO._serialized_end=174
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/wandb_internal_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/wandb_internal_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..15b4a039db436b611995da6406c24074a6fc0ba7
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/wandb_internal_pb2.py
@@ -0,0 +1,385 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: wandb/proto/wandb_internal.proto
+"""Generated protocol buffer code."""
+from google.protobuf.internal import builder as _builder
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
+from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
+from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2
+from wandb.proto import wandb_telemetry_pb2 as wandb_dot_proto_dot_wandb__telemetry__pb2
+from wandb.proto import wandb_api_pb2 as wandb_dot_proto_dot_wandb__api__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n wandb/proto/wandb_internal.proto\x12\x0ewandb_internal\x1a\x1bgoogle/protobuf/empty.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1cwandb/proto/wandb_base.proto\x1a!wandb/proto/wandb_telemetry.proto\x1a\x1bwandb/proto/wandb_api.proto\"\x82\n\n\x06Record\x12\x0b\n\x03num\x18\x01 \x01(\x03\x12\x30\n\x07history\x18\x02 \x01(\x0b\x32\x1d.wandb_internal.HistoryRecordH\x00\x12\x30\n\x07summary\x18\x03 \x01(\x0b\x32\x1d.wandb_internal.SummaryRecordH\x00\x12.\n\x06output\x18\x04 \x01(\x0b\x32\x1c.wandb_internal.OutputRecordH\x00\x12.\n\x06\x63onfig\x18\x05 \x01(\x0b\x32\x1c.wandb_internal.ConfigRecordH\x00\x12,\n\x05\x66iles\x18\x06 \x01(\x0b\x32\x1b.wandb_internal.FilesRecordH\x00\x12,\n\x05stats\x18\x07 \x01(\x0b\x32\x1b.wandb_internal.StatsRecordH\x00\x12\x32\n\x08\x61rtifact\x18\x08 \x01(\x0b\x32\x1e.wandb_internal.ArtifactRecordH\x00\x12,\n\x08tbrecord\x18\t \x01(\x0b\x32\x18.wandb_internal.TBRecordH\x00\x12,\n\x05\x61lert\x18\n \x01(\x0b\x32\x1b.wandb_internal.AlertRecordH\x00\x12\x34\n\ttelemetry\x18\x0b \x01(\x0b\x32\x1f.wandb_internal.TelemetryRecordH\x00\x12.\n\x06metric\x18\x0c \x01(\x0b\x32\x1c.wandb_internal.MetricRecordH\x00\x12\x35\n\noutput_raw\x18\r \x01(\x0b\x32\x1f.wandb_internal.OutputRawRecordH\x00\x12(\n\x03run\x18\x11 \x01(\x0b\x32\x19.wandb_internal.RunRecordH\x00\x12-\n\x04\x65xit\x18\x12 \x01(\x0b\x32\x1d.wandb_internal.RunExitRecordH\x00\x12,\n\x05\x66inal\x18\x14 \x01(\x0b\x32\x1b.wandb_internal.FinalRecordH\x00\x12.\n\x06header\x18\x15 \x01(\x0b\x32\x1c.wandb_internal.HeaderRecordH\x00\x12.\n\x06\x66ooter\x18\x16 \x01(\x0b\x32\x1c.wandb_internal.FooterRecordH\x00\x12\x39\n\npreempting\x18\x17 \x01(\x0b\x32#.wandb_internal.RunPreemptingRecordH\x00\x12\x34\n\x12noop_link_artifact\x18\x18 \x01(\x0b\x32\x16.google.protobuf.EmptyH\x00\x12\x39\n\x0cuse_artifact\x18\x19 \x01(\x0b\x32!.wandb_internal.UseArtifactRecordH\x00\x12\x38\n\x0b\x65nvironment\x18\x1a \x01(\x0b\x32!.wandb_internal.EnvironmentRecordH\x00\x12*\n\x07request\x18\x64 \x01(\x0b\x32\x17.wandb_internal.RequestH\x00\x12\x31\n\x0b\x61pi_request\x18\x65 \x01(\x0b\x32\x1a.wandb_internal.ApiRequestH\x00\x12(\n\x07\x63ontrol\x18\x10 \x01(\x0b\x32\x17.wandb_internal.Control\x12\x0c\n\x04uuid\x18\x13 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfoB\r\n\x0brecord_type\"\xa8\x01\n\x07\x43ontrol\x12\x10\n\x08req_resp\x18\x01 \x01(\x08\x12\r\n\x05local\x18\x02 \x01(\x08\x12\x10\n\x08relay_id\x18\x03 \x01(\t\x12\x14\n\x0cmailbox_slot\x18\x04 \x01(\t\x12\x13\n\x0b\x61lways_send\x18\x05 \x01(\x08\x12\x14\n\x0c\x66low_control\x18\x06 \x01(\x08\x12\x12\n\nend_offset\x18\x07 \x01(\x03\x12\x15\n\rconnection_id\x18\x08 \x01(\t\"\xf3\x03\n\x06Result\x12\x35\n\nrun_result\x18\x11 \x01(\x0b\x32\x1f.wandb_internal.RunUpdateResultH\x00\x12\x34\n\x0b\x65xit_result\x18\x12 \x01(\x0b\x32\x1d.wandb_internal.RunExitResultH\x00\x12\x33\n\nlog_result\x18\x14 \x01(\x0b\x32\x1d.wandb_internal.HistoryResultH\x00\x12\x37\n\x0esummary_result\x18\x15 \x01(\x0b\x32\x1d.wandb_internal.SummaryResultH\x00\x12\x35\n\routput_result\x18\x16 \x01(\x0b\x32\x1c.wandb_internal.OutputResultH\x00\x12\x35\n\rconfig_result\x18\x17 \x01(\x0b\x32\x1c.wandb_internal.ConfigResultH\x00\x12,\n\x08response\x18\x64 \x01(\x0b\x32\x18.wandb_internal.ResponseH\x00\x12(\n\x07\x63ontrol\x18\x10 \x01(\x0b\x32\x17.wandb_internal.Control\x12\x0c\n\x04uuid\x18\x18 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._ResultInfoB\r\n\x0bresult_type\":\n\x0b\x46inalRecord\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"b\n\x0bVersionInfo\x12\x10\n\x08producer\x18\x01 \x01(\t\x12\x14\n\x0cmin_consumer\x18\x02 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"n\n\x0cHeaderRecord\x12\x31\n\x0cversion_info\x18\x01 \x01(\x0b\x32\x1b.wandb_internal.VersionInfo\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\";\n\x0c\x46ooterRecord\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"9\n\x0b\x42ranchPoint\x12\x0b\n\x03run\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x01\x12\x0e\n\x06metric\x18\x03 \x01(\t\"\x91\x05\n\tRunRecord\x12\x0e\n\x06run_id\x18\x01 \x01(\t\x12\x0e\n\x06\x65ntity\x18\x02 \x01(\t\x12\x0f\n\x07project\x18\x03 \x01(\t\x12,\n\x06\x63onfig\x18\x04 \x01(\x0b\x32\x1c.wandb_internal.ConfigRecord\x12.\n\x07summary\x18\x05 \x01(\x0b\x32\x1d.wandb_internal.SummaryRecord\x12\x11\n\trun_group\x18\x06 \x01(\t\x12\x10\n\x08job_type\x18\x07 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x08 \x01(\t\x12\r\n\x05notes\x18\t \x01(\t\x12\x0c\n\x04tags\x18\n \x03(\t\x12\x30\n\x08settings\x18\x0b \x01(\x0b\x32\x1e.wandb_internal.SettingsRecord\x12\x10\n\x08sweep_id\x18\x0c \x01(\t\x12\x0c\n\x04host\x18\r \x01(\t\x12\x15\n\rstarting_step\x18\x0e \x01(\x03\x12\x12\n\nstorage_id\x18\x10 \x01(\t\x12.\n\nstart_time\x18\x11 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07resumed\x18\x12 \x01(\x08\x12\x32\n\ttelemetry\x18\x13 \x01(\x0b\x32\x1f.wandb_internal.TelemetryRecord\x12\x0f\n\x07runtime\x18\x14 \x01(\x05\x12*\n\x03git\x18\x15 \x01(\x0b\x32\x1d.wandb_internal.GitRepoRecord\x12\x0e\n\x06\x66orked\x18\x16 \x01(\x08\x12\x31\n\x0c\x62ranch_point\x18\x17 \x01(\x0b\x32\x1b.wandb_internal.BranchPoint\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\";\n\rGitRepoRecord\x12\x1a\n\nremote_url\x18\x01 \x01(\tR\x06remote\x12\x0e\n\x06\x63ommit\x18\x02 \x01(\t\"c\n\x0fRunUpdateResult\x12&\n\x03run\x18\x01 \x01(\x0b\x32\x19.wandb_internal.RunRecord\x12(\n\x05\x65rror\x18\x02 \x01(\x0b\x32\x19.wandb_internal.ErrorInfo\"\xac\x01\n\tErrorInfo\x12\x0f\n\x07message\x18\x01 \x01(\t\x12\x31\n\x04\x63ode\x18\x02 \x01(\x0e\x32#.wandb_internal.ErrorInfo.ErrorCode\"[\n\tErrorCode\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x11\n\rCOMMUNICATION\x10\x01\x12\x12\n\x0e\x41UTHENTICATION\x10\x02\x12\t\n\x05USAGE\x10\x03\x12\x0f\n\x0bUNSUPPORTED\x10\x04\"`\n\rRunExitRecord\x12\x11\n\texit_code\x18\x01 \x01(\x05\x12\x0f\n\x07runtime\x18\x02 \x01(\x05\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x0f\n\rRunExitResult\"B\n\x13RunPreemptingRecord\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x15\n\x13RunPreemptingResult\"i\n\x0eSettingsRecord\x12*\n\x04item\x18\x01 \x03(\x0b\x32\x1c.wandb_internal.SettingsItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"/\n\x0cSettingsItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\x1a\n\x0bHistoryStep\x12\x0b\n\x03num\x18\x01 \x01(\x03\"\x92\x01\n\rHistoryRecord\x12)\n\x04item\x18\x01 \x03(\x0b\x32\x1b.wandb_internal.HistoryItem\x12)\n\x04step\x18\x02 \x01(\x0b\x32\x1b.wandb_internal.HistoryStep\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"B\n\x0bHistoryItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nnested_key\x18\x02 \x03(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\x0f\n\rHistoryResult\"\xdc\x01\n\x0cOutputRecord\x12<\n\x0boutput_type\x18\x01 \x01(\x0e\x32\'.wandb_internal.OutputRecord.OutputType\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0c\n\x04line\x18\x03 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"$\n\nOutputType\x12\n\n\x06STDERR\x10\x00\x12\n\n\x06STDOUT\x10\x01\"\x0e\n\x0cOutputResult\"\xe2\x01\n\x0fOutputRawRecord\x12?\n\x0boutput_type\x18\x01 \x01(\x0e\x32*.wandb_internal.OutputRawRecord.OutputType\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0c\n\x04line\x18\x03 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"$\n\nOutputType\x12\n\n\x06STDERR\x10\x00\x12\n\n\x06STDOUT\x10\x01\"\x11\n\x0fOutputRawResult\"\xb4\x03\n\x0cMetricRecord\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x11\n\tglob_name\x18\x02 \x01(\t\x12\x13\n\x0bstep_metric\x18\x04 \x01(\t\x12\x19\n\x11step_metric_index\x18\x05 \x01(\x05\x12.\n\x07options\x18\x06 \x01(\x0b\x32\x1d.wandb_internal.MetricOptions\x12.\n\x07summary\x18\x07 \x01(\x0b\x32\x1d.wandb_internal.MetricSummary\x12\x35\n\x04goal\x18\x08 \x01(\x0e\x32\'.wandb_internal.MetricRecord.MetricGoal\x12/\n\x08_control\x18\t \x01(\x0b\x32\x1d.wandb_internal.MetricControl\x12\x1a\n\x12\x65xpanded_from_glob\x18\n \x01(\x08\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"B\n\nMetricGoal\x12\x0e\n\nGOAL_UNSET\x10\x00\x12\x11\n\rGOAL_MINIMIZE\x10\x01\x12\x11\n\rGOAL_MAXIMIZE\x10\x02\"\x0e\n\x0cMetricResult\"C\n\rMetricOptions\x12\x11\n\tstep_sync\x18\x01 \x01(\x08\x12\x0e\n\x06hidden\x18\x02 \x01(\x08\x12\x0f\n\x07\x64\x65\x66ined\x18\x03 \x01(\x08\"\"\n\rMetricControl\x12\x11\n\toverwrite\x18\x01 \x01(\x08\"~\n\rMetricSummary\x12\x0b\n\x03min\x18\x01 \x01(\x08\x12\x0b\n\x03max\x18\x02 \x01(\x08\x12\x0c\n\x04mean\x18\x03 \x01(\x08\x12\x0c\n\x04\x62\x65st\x18\x04 \x01(\x08\x12\x0c\n\x04last\x18\x05 \x01(\x08\x12\x0c\n\x04none\x18\x06 \x01(\x08\x12\x0c\n\x04\x63opy\x18\x07 \x01(\x08\x12\r\n\x05\x66irst\x18\x08 \x01(\x08\"\x93\x01\n\x0c\x43onfigRecord\x12*\n\x06update\x18\x01 \x03(\x0b\x32\x1a.wandb_internal.ConfigItem\x12*\n\x06remove\x18\x02 \x03(\x0b\x32\x1a.wandb_internal.ConfigItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"A\n\nConfigItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nnested_key\x18\x02 \x03(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\x0e\n\x0c\x43onfigResult\"\x96\x01\n\rSummaryRecord\x12+\n\x06update\x18\x01 \x03(\x0b\x32\x1b.wandb_internal.SummaryItem\x12+\n\x06remove\x18\x02 \x03(\x0b\x32\x1b.wandb_internal.SummaryItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"B\n\x0bSummaryItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nnested_key\x18\x02 \x03(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\x0f\n\rSummaryResult\"d\n\x0b\x46ilesRecord\x12(\n\x05\x66iles\x18\x01 \x03(\x0b\x32\x19.wandb_internal.FilesItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\xec\x01\n\tFilesItem\x12\x0c\n\x04path\x18\x01 \x01(\t\x12\x34\n\x06policy\x18\x02 \x01(\x0e\x32$.wandb_internal.FilesItem.PolicyType\x12\x30\n\x04type\x18\x03 \x01(\x0e\x32\".wandb_internal.FilesItem.FileType\"(\n\nPolicyType\x12\x07\n\x03NOW\x10\x00\x12\x07\n\x03\x45ND\x10\x01\x12\x08\n\x04LIVE\x10\x02\"9\n\x08\x46ileType\x12\t\n\x05OTHER\x10\x00\x12\t\n\x05WANDB\x10\x01\x12\t\n\x05MEDIA\x10\x02\x12\x0c\n\x08\x41RTIFACT\x10\x03J\x04\x08\x10\x10\x11\"\r\n\x0b\x46ilesResult\"\xe6\x01\n\x0bStatsRecord\x12\x39\n\nstats_type\x18\x01 \x01(\x0e\x32%.wandb_internal.StatsRecord.StatsType\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\'\n\x04item\x18\x03 \x03(\x0b\x32\x19.wandb_internal.StatsItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x17\n\tStatsType\x12\n\n\x06SYSTEM\x10\x00\",\n\tStatsItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\xe7\x03\n\x0e\x41rtifactRecord\x12\x0e\n\x06run_id\x18\x01 \x01(\t\x12\x0f\n\x07project\x18\x02 \x01(\t\x12\x0e\n\x06\x65ntity\x18\x03 \x01(\t\x12\x0c\n\x04type\x18\x04 \x01(\t\x12\x0c\n\x04name\x18\x05 \x01(\t\x12\x0e\n\x06\x64igest\x18\x06 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x07 \x01(\t\x12\x10\n\x08metadata\x18\x08 \x01(\t\x12\x14\n\x0cuser_created\x18\t \x01(\x08\x12\x18\n\x10use_after_commit\x18\n \x01(\x08\x12\x0f\n\x07\x61liases\x18\x0b \x03(\t\x12\x32\n\x08manifest\x18\x0c \x01(\x0b\x32 .wandb_internal.ArtifactManifest\x12\x16\n\x0e\x64istributed_id\x18\r \x01(\t\x12\x10\n\x08\x66inalize\x18\x0e \x01(\x08\x12\x11\n\tclient_id\x18\x0f \x01(\t\x12\x1a\n\x12sequence_client_id\x18\x10 \x01(\t\x12\x0f\n\x07\x62\x61se_id\x18\x11 \x01(\t\x12\x1c\n\x14ttl_duration_seconds\x18\x12 \x01(\x03\x12\x0c\n\x04tags\x18\x13 \x03(\t\x12\x19\n\x11incremental_beta1\x18\x64 \x01(\x08\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\xd8\x01\n\x10\x41rtifactManifest\x12\x0f\n\x07version\x18\x01 \x01(\x05\x12\x16\n\x0estorage_policy\x18\x02 \x01(\t\x12\x46\n\x15storage_policy_config\x18\x03 \x03(\x0b\x32\'.wandb_internal.StoragePolicyConfigItem\x12\x37\n\x08\x63ontents\x18\x04 \x03(\x0b\x32%.wandb_internal.ArtifactManifestEntry\x12\x1a\n\x12manifest_file_path\x18\x05 \x01(\t\"\xcf\x01\n\x15\x41rtifactManifestEntry\x12\x0c\n\x04path\x18\x01 \x01(\t\x12\x0e\n\x06\x64igest\x18\x02 \x01(\t\x12\x0b\n\x03ref\x18\x03 \x01(\t\x12\x0c\n\x04size\x18\x04 \x01(\x03\x12\x10\n\x08mimetype\x18\x05 \x01(\t\x12\x12\n\nlocal_path\x18\x06 \x01(\t\x12\x19\n\x11\x62irth_artifact_id\x18\x07 \x01(\t\x12\x12\n\nskip_cache\x18\x08 \x01(\x08\x12(\n\x05\x65xtra\x18\x10 \x03(\x0b\x32\x19.wandb_internal.ExtraItem\",\n\tExtraItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x02 \x01(\t\":\n\x17StoragePolicyConfigItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x02 \x01(\t\"\x10\n\x0e\x41rtifactResult\"\x14\n\x12LinkArtifactResult\"\xf0\x01\n\x13LinkArtifactRequest\x12\x11\n\tclient_id\x18\x01 \x01(\t\x12\x11\n\tserver_id\x18\x02 \x01(\t\x12\x16\n\x0eportfolio_name\x18\x03 \x01(\t\x12\x18\n\x10portfolio_entity\x18\x04 \x01(\t\x12\x19\n\x11portfolio_project\x18\x05 \x01(\t\x12\x19\n\x11portfolio_aliases\x18\x06 \x03(\t\x12\x1e\n\x16portfolio_organization\x18\x07 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"[\n\x14LinkArtifactResponse\x12\x15\n\rerror_message\x18\x01 \x01(\t\x12\x1a\n\rversion_index\x18\x02 \x01(\x05H\x00\x88\x01\x01\x42\x10\n\x0e_version_index\"h\n\x08TBRecord\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\x12\x0f\n\x07log_dir\x18\x01 \x01(\t\x12\x10\n\x08root_dir\x18\x03 \x01(\t\x12\x0c\n\x04save\x18\x02 \x01(\x08\"\n\n\x08TBResult\"}\n\x0b\x41lertRecord\x12\r\n\x05title\x18\x01 \x01(\t\x12\x0c\n\x04text\x18\x02 \x01(\t\x12\r\n\x05level\x18\x03 \x01(\t\x12\x15\n\rwait_duration\x18\x04 \x01(\x03\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\r\n\x0b\x41lertResult\"\xf8\x11\n\x07Request\x12\x38\n\x0bstop_status\x18\x01 \x01(\x0b\x32!.wandb_internal.StopStatusRequestH\x00\x12>\n\x0enetwork_status\x18\x02 \x01(\x0b\x32$.wandb_internal.NetworkStatusRequestH\x00\x12-\n\x05\x64\x65\x66\x65r\x18\x03 \x01(\x0b\x32\x1c.wandb_internal.DeferRequestH\x00\x12\x38\n\x0bget_summary\x18\x04 \x01(\x0b\x32!.wandb_internal.GetSummaryRequestH\x00\x12-\n\x05login\x18\x05 \x01(\x0b\x32\x1c.wandb_internal.LoginRequestH\x00\x12-\n\x05pause\x18\x06 \x01(\x0b\x32\x1c.wandb_internal.PauseRequestH\x00\x12/\n\x06resume\x18\x07 \x01(\x0b\x32\x1d.wandb_internal.ResumeRequestH\x00\x12\x34\n\tpoll_exit\x18\x08 \x01(\x0b\x32\x1f.wandb_internal.PollExitRequestH\x00\x12@\n\x0fsampled_history\x18\t \x01(\x0b\x32%.wandb_internal.SampledHistoryRequestH\x00\x12@\n\x0fpartial_history\x18\n \x01(\x0b\x32%.wandb_internal.PartialHistoryRequestH\x00\x12\x34\n\trun_start\x18\x0b \x01(\x0b\x32\x1f.wandb_internal.RunStartRequestH\x00\x12<\n\rcheck_version\x18\x0c \x01(\x0b\x32#.wandb_internal.CheckVersionRequestH\x00\x12:\n\x0clog_artifact\x18\r \x01(\x0b\x32\".wandb_internal.LogArtifactRequestH\x00\x12\x44\n\x11\x64ownload_artifact\x18\x0e \x01(\x0b\x32\'.wandb_internal.DownloadArtifactRequestH\x00\x12\x35\n\tkeepalive\x18\x11 \x01(\x0b\x32 .wandb_internal.KeepaliveRequestH\x00\x12>\n\x0eserver_feature\x18\x12 \x01(\x0b\x32$.wandb_internal.ServerFeatureRequestH\x00\x12\x36\n\nrun_status\x18\x14 \x01(\x0b\x32 .wandb_internal.RunStatusRequestH\x00\x12/\n\x06\x63\x61ncel\x18\x15 \x01(\x0b\x32\x1d.wandb_internal.CancelRequestH\x00\x12\x44\n\x11internal_messages\x18\x17 \x01(\x0b\x32\'.wandb_internal.InternalMessagesRequestH\x00\x12@\n\x0fpython_packages\x18\x18 \x01(\x0b\x32%.wandb_internal.PythonPackagesRequestH\x00\x12\x33\n\x08shutdown\x18@ \x01(\x0b\x32\x1f.wandb_internal.ShutdownRequestH\x00\x12/\n\x06\x61ttach\x18\x41 \x01(\x0b\x32\x1d.wandb_internal.AttachRequestH\x00\x12/\n\x06status\x18\x42 \x01(\x0b\x32\x1d.wandb_internal.StatusRequestH\x00\x12\x38\n\x0bserver_info\x18\x43 \x01(\x0b\x32!.wandb_internal.ServerInfoRequestH\x00\x12\x38\n\x0bsender_mark\x18\x44 \x01(\x0b\x32!.wandb_internal.SenderMarkRequestH\x00\x12\x38\n\x0bsender_read\x18\x45 \x01(\x0b\x32!.wandb_internal.SenderReadRequestH\x00\x12<\n\rstatus_report\x18\x46 \x01(\x0b\x32#.wandb_internal.StatusReportRequestH\x00\x12>\n\x0esummary_record\x18G \x01(\x0b\x32$.wandb_internal.SummaryRecordRequestH\x00\x12\x42\n\x10telemetry_record\x18H \x01(\x0b\x32&.wandb_internal.TelemetryRecordRequestH\x00\x12\x32\n\x08job_info\x18I \x01(\x0b\x32\x1e.wandb_internal.JobInfoRequestH\x00\x12\x45\n\x12get_system_metrics\x18J \x01(\x0b\x32\'.wandb_internal.GetSystemMetricsRequestH\x00\x12\x34\n\tjob_input\x18M \x01(\x0b\x32\x1f.wandb_internal.JobInputRequestH\x00\x12<\n\rlink_artifact\x18N \x01(\x0b\x32#.wandb_internal.LinkArtifactRequestH\x00\x12N\n\x17run_finish_without_exit\x18O \x01(\x0b\x32+.wandb_internal.RunFinishWithoutExitRequestH\x00\x12\x38\n\x0bsync_finish\x18Q \x01(\x0b\x32!.wandb_internal.SyncFinishRequestH\x00\x12;\n\noperations\x18R \x01(\x0b\x32%.wandb_internal.OperationStatsRequestH\x00\x12\x43\n\x11probe_system_info\x18S \x01(\x0b\x32&.wandb_internal.ProbeSystemInfoRequestH\x00\x12\x39\n\x0btest_inject\x18\xe8\x07 \x01(\x0b\x32!.wandb_internal.TestInjectRequestH\x00\x42\x0e\n\x0crequest_typeJ\x04\x08\x16\x10\x17J\x04\x08K\x10LJ\x04\x08L\x10MJ\x04\x08P\x10Q\"\xd0\x0e\n\x08Response\x12?\n\x12keepalive_response\x18\x12 \x01(\x0b\x32!.wandb_internal.KeepaliveResponseH\x00\x12\x42\n\x14stop_status_response\x18\x13 \x01(\x0b\x32\".wandb_internal.StopStatusResponseH\x00\x12H\n\x17network_status_response\x18\x14 \x01(\x0b\x32%.wandb_internal.NetworkStatusResponseH\x00\x12\x37\n\x0elogin_response\x18\x18 \x01(\x0b\x32\x1d.wandb_internal.LoginResponseH\x00\x12\x42\n\x14get_summary_response\x18\x19 \x01(\x0b\x32\".wandb_internal.GetSummaryResponseH\x00\x12>\n\x12poll_exit_response\x18\x1a \x01(\x0b\x32 .wandb_internal.PollExitResponseH\x00\x12J\n\x18sampled_history_response\x18\x1b \x01(\x0b\x32&.wandb_internal.SampledHistoryResponseH\x00\x12>\n\x12run_start_response\x18\x1c \x01(\x0b\x32 .wandb_internal.RunStartResponseH\x00\x12\x46\n\x16\x63heck_version_response\x18\x1d \x01(\x0b\x32$.wandb_internal.CheckVersionResponseH\x00\x12\x44\n\x15log_artifact_response\x18\x1e \x01(\x0b\x32#.wandb_internal.LogArtifactResponseH\x00\x12N\n\x1a\x64ownload_artifact_response\x18\x1f \x01(\x0b\x32(.wandb_internal.DownloadArtifactResponseH\x00\x12H\n\x17server_feature_response\x18 \x01(\x0b\x32%.wandb_internal.ServerFeatureResponseH\x00\x12@\n\x13run_status_response\x18# \x01(\x0b\x32!.wandb_internal.RunStatusResponseH\x00\x12\x39\n\x0f\x63\x61ncel_response\x18$ \x01(\x0b\x32\x1e.wandb_internal.CancelResponseH\x00\x12N\n\x1ainternal_messages_response\x18% \x01(\x0b\x32(.wandb_internal.InternalMessagesResponseH\x00\x12=\n\x11shutdown_response\x18@ \x01(\x0b\x32 .wandb_internal.ShutdownResponseH\x00\x12\x39\n\x0f\x61ttach_response\x18\x41 \x01(\x0b\x32\x1e.wandb_internal.AttachResponseH\x00\x12\x39\n\x0fstatus_response\x18\x42 \x01(\x0b\x32\x1e.wandb_internal.StatusResponseH\x00\x12\x42\n\x14server_info_response\x18\x43 \x01(\x0b\x32\".wandb_internal.ServerInfoResponseH\x00\x12<\n\x11job_info_response\x18\x44 \x01(\x0b\x32\x1f.wandb_internal.JobInfoResponseH\x00\x12O\n\x1bget_system_metrics_response\x18\x45 \x01(\x0b\x32(.wandb_internal.GetSystemMetricsResponseH\x00\x12\x46\n\x16link_artifact_response\x18G \x01(\x0b\x32$.wandb_internal.LinkArtifactResponseH\x00\x12\x35\n\rsync_response\x18\x46 \x01(\x0b\x32\x1c.wandb_internal.SyncResponseH\x00\x12X\n run_finish_without_exit_response\x18H \x01(\x0b\x32,.wandb_internal.RunFinishWithoutExitResponseH\x00\x12\x45\n\x13operations_response\x18J \x01(\x0b\x32&.wandb_internal.OperationStatsResponseH\x00\x12\x33\n\x0c\x61pi_response\x18T \x01(\x0b\x32\x1b.wandb_internal.ApiResponseH\x00\x12\x43\n\x14test_inject_response\x18\xe8\x07 \x01(\x0b\x32\".wandb_internal.TestInjectResponseH\x00\x42\x0f\n\rresponse_typeJ\x04\x08I\x10J\"\xc0\x02\n\x0c\x44\x65\x66\x65rRequest\x12\x36\n\x05state\x18\x01 \x01(\x0e\x32\'.wandb_internal.DeferRequest.DeferState\"\xf7\x01\n\nDeferState\x12\t\n\x05\x42\x45GIN\x10\x00\x12\r\n\tFLUSH_RUN\x10\x01\x12\x0f\n\x0b\x46LUSH_STATS\x10\x02\x12\x19\n\x15\x46LUSH_PARTIAL_HISTORY\x10\x03\x12\x0c\n\x08\x46LUSH_TB\x10\x04\x12\r\n\tFLUSH_SUM\x10\x05\x12\x13\n\x0f\x46LUSH_DEBOUNCER\x10\x06\x12\x10\n\x0c\x46LUSH_OUTPUT\x10\x07\x12\r\n\tFLUSH_JOB\x10\x08\x12\r\n\tFLUSH_DIR\x10\t\x12\x0c\n\x08\x46LUSH_FP\x10\n\x12\x0b\n\x07JOIN_FP\x10\x0b\x12\x0c\n\x08\x46LUSH_FS\x10\x0c\x12\x0f\n\x0b\x46LUSH_FINAL\x10\r\x12\x07\n\x03\x45ND\x10\x0e\"<\n\x0cPauseRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x0f\n\rPauseResponse\"=\n\rResumeRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x10\n\x0eResumeResponse\"M\n\x0cLoginRequest\x12\x0f\n\x07\x61pi_key\x18\x01 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"&\n\rLoginResponse\x12\x15\n\ractive_entity\x18\x01 \x01(\t\"A\n\x11GetSummaryRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"?\n\x12GetSummaryResponse\x12)\n\x04item\x18\x01 \x03(\x0b\x32\x1b.wandb_internal.SummaryItem\"G\n\x17GetSystemMetricsRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"R\n\x12SystemMetricSample\x12-\n\ttimestamp\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\r\n\x05value\x18\x02 \x01(\x02\"I\n\x13SystemMetricsBuffer\x12\x32\n\x06record\x18\x01 \x03(\x0b\x32\".wandb_internal.SystemMetricSample\"\xca\x01\n\x18GetSystemMetricsResponse\x12S\n\x0esystem_metrics\x18\x01 \x03(\x0b\x32;.wandb_internal.GetSystemMetricsResponse.SystemMetricsEntry\x1aY\n\x12SystemMetricsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x32\n\x05value\x18\x02 \x01(\x0b\x32#.wandb_internal.SystemMetricsBuffer:\x02\x38\x01\"=\n\rStatusRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\")\n\x0eStatusResponse\x12\x17\n\x0frun_should_stop\x18\x01 \x01(\x08\"A\n\x11StopStatusRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"-\n\x12StopStatusResponse\x12\x17\n\x0frun_should_stop\x18\x01 \x01(\x08\"D\n\x14NetworkStatusRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"P\n\x15NetworkStatusResponse\x12\x37\n\x11network_responses\x18\x01 \x03(\x0b\x32\x1c.wandb_internal.HttpResponse\"D\n\x0cHttpResponse\x12\x18\n\x10http_status_code\x18\x01 \x01(\x05\x12\x1a\n\x12http_response_text\x18\x02 \x01(\t\"G\n\x17InternalMessagesRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"N\n\x18InternalMessagesResponse\x12\x32\n\x08messages\x18\x01 \x01(\x0b\x32 .wandb_internal.InternalMessages\"#\n\x10InternalMessages\x12\x0f\n\x07warning\x18\x01 \x03(\t\"?\n\x0fPollExitRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\xf5\x01\n\x10PollExitResponse\x12\x0c\n\x04\x64one\x18\x01 \x01(\x08\x12\x32\n\x0b\x65xit_result\x18\x02 \x01(\x0b\x32\x1d.wandb_internal.RunExitResult\x12\x35\n\x0cpusher_stats\x18\x03 \x01(\x0b\x32\x1f.wandb_internal.FilePusherStats\x12/\n\x0b\x66ile_counts\x18\x04 \x01(\x0b\x32\x1a.wandb_internal.FileCounts\x12\x37\n\x0foperation_stats\x18\x05 \x01(\x0b\x32\x1e.wandb_internal.OperationStats\"E\n\x15OperationStatsRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"Q\n\x16OperationStatsResponse\x12\x37\n\x0foperation_stats\x18\x01 \x01(\x0b\x32\x1e.wandb_internal.OperationStats\"Y\n\x0eOperationStats\x12-\n\noperations\x18\x01 \x03(\x0b\x32\x19.wandb_internal.Operation\x12\x18\n\x10total_operations\x18\x02 \x01(\x03\"\x87\x01\n\tOperation\x12\x0c\n\x04\x64\x65sc\x18\x01 \x01(\t\x12\x17\n\x0fruntime_seconds\x18\x02 \x01(\x01\x12\x10\n\x08progress\x18\x03 \x01(\t\x12\x14\n\x0c\x65rror_status\x18\x04 \x01(\t\x12+\n\x08subtasks\x18\x05 \x03(\x0b\x32\x19.wandb_internal.Operation\"\x13\n\x11SenderMarkRequest\"\x13\n\x11SyncFinishRequest\"E\n\x0cSyncResponse\x12\x0b\n\x03url\x18\x01 \x01(\t\x12(\n\x05\x65rror\x18\x02 \x01(\x0b\x32\x19.wandb_internal.ErrorInfo\"?\n\x11SenderReadRequest\x12\x14\n\x0cstart_offset\x18\x01 \x01(\x03\x12\x14\n\x0c\x66inal_offset\x18\x02 \x01(\x03\"m\n\x13StatusReportRequest\x12\x12\n\nrecord_num\x18\x01 \x01(\x03\x12\x13\n\x0bsent_offset\x18\x02 \x01(\x03\x12-\n\tsync_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"F\n\x14SummaryRecordRequest\x12.\n\x07summary\x18\x01 \x01(\x0b\x32\x1d.wandb_internal.SummaryRecord\"L\n\x16TelemetryRecordRequest\x12\x32\n\ttelemetry\x18\x01 \x01(\x0b\x32\x1f.wandb_internal.TelemetryRecord\"A\n\x11ServerInfoRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"|\n\x12ServerInfoResponse\x12-\n\nlocal_info\x18\x01 \x01(\x0b\x32\x19.wandb_internal.LocalInfo\x12\x37\n\x0fserver_messages\x18\x02 \x01(\x0b\x32\x1e.wandb_internal.ServerMessages\"=\n\x0eServerMessages\x12+\n\x04item\x18\x01 \x03(\x0b\x32\x1d.wandb_internal.ServerMessage\"e\n\rServerMessage\x12\x12\n\nplain_text\x18\x01 \x01(\t\x12\x10\n\x08utf_text\x18\x02 \x01(\t\x12\x11\n\thtml_text\x18\x03 \x01(\t\x12\x0c\n\x04type\x18\x04 \x01(\t\x12\r\n\x05level\x18\x05 \x01(\x05\"c\n\nFileCounts\x12\x13\n\x0bwandb_count\x18\x01 \x01(\x05\x12\x13\n\x0bmedia_count\x18\x02 \x01(\x05\x12\x16\n\x0e\x61rtifact_count\x18\x03 \x01(\x05\x12\x13\n\x0bother_count\x18\x04 \x01(\x05\"U\n\x0f\x46ilePusherStats\x12\x16\n\x0euploaded_bytes\x18\x01 \x01(\x03\x12\x13\n\x0btotal_bytes\x18\x02 \x01(\x03\x12\x15\n\rdeduped_bytes\x18\x03 \x01(\x03\"\x1e\n\rFilesUploaded\x12\r\n\x05\x66iles\x18\x01 \x03(\t\"\xf4\x01\n\x17\x46ileTransferInfoRequest\x12\x42\n\x04type\x18\x01 \x01(\x0e\x32\x34.wandb_internal.FileTransferInfoRequest.TransferType\x12\x0c\n\x04path\x18\x02 \x01(\t\x12\x0b\n\x03url\x18\x03 \x01(\t\x12\x0c\n\x04size\x18\x04 \x01(\x03\x12\x11\n\tprocessed\x18\x05 \x01(\x03\x12/\n\x0b\x66ile_counts\x18\x06 \x01(\x0b\x32\x1a.wandb_internal.FileCounts\"(\n\x0cTransferType\x12\n\n\x06Upload\x10\x00\x12\x0c\n\x08\x44ownload\x10\x01\"1\n\tLocalInfo\x12\x0f\n\x07version\x18\x01 \x01(\t\x12\x13\n\x0bout_of_date\x18\x02 \x01(\x08\"?\n\x0fShutdownRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x12\n\x10ShutdownResponse\"P\n\rAttachRequest\x12\x11\n\tattach_id\x18\x14 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"b\n\x0e\x41ttachResponse\x12&\n\x03run\x18\x01 \x01(\x0b\x32\x19.wandb_internal.RunRecord\x12(\n\x05\x65rror\x18\x02 \x01(\x0b\x32\x19.wandb_internal.ErrorInfo\"\xd5\x02\n\x11TestInjectRequest\x12\x13\n\x0bhandler_exc\x18\x01 \x01(\x08\x12\x14\n\x0chandler_exit\x18\x02 \x01(\x08\x12\x15\n\rhandler_abort\x18\x03 \x01(\x08\x12\x12\n\nsender_exc\x18\x04 \x01(\x08\x12\x13\n\x0bsender_exit\x18\x05 \x01(\x08\x12\x14\n\x0csender_abort\x18\x06 \x01(\x08\x12\x0f\n\x07req_exc\x18\x07 \x01(\x08\x12\x10\n\x08req_exit\x18\x08 \x01(\x08\x12\x11\n\treq_abort\x18\t \x01(\x08\x12\x10\n\x08resp_exc\x18\n \x01(\x08\x12\x11\n\tresp_exit\x18\x0b \x01(\x08\x12\x12\n\nresp_abort\x18\x0c \x01(\x08\x12\x10\n\x08msg_drop\x18\r \x01(\x08\x12\x10\n\x08msg_hang\x18\x0e \x01(\x08\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x14\n\x12TestInjectResponse\"\x1e\n\rHistoryAction\x12\r\n\x05\x66lush\x18\x01 \x01(\x08\"\xca\x01\n\x15PartialHistoryRequest\x12)\n\x04item\x18\x01 \x03(\x0b\x32\x1b.wandb_internal.HistoryItem\x12)\n\x04step\x18\x02 \x01(\x0b\x32\x1b.wandb_internal.HistoryStep\x12-\n\x06\x61\x63tion\x18\x03 \x01(\x0b\x32\x1d.wandb_internal.HistoryAction\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x18\n\x16PartialHistoryResponse\"E\n\x15SampledHistoryRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"_\n\x12SampledHistoryItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nnested_key\x18\x02 \x03(\t\x12\x14\n\x0cvalues_float\x18\x03 \x03(\x02\x12\x12\n\nvalues_int\x18\x04 \x03(\x03\"J\n\x16SampledHistoryResponse\x12\x30\n\x04item\x18\x01 \x03(\x0b\x32\".wandb_internal.SampledHistoryItem\"@\n\x10RunStatusRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"x\n\x11RunStatusResponse\x12\x18\n\x10sync_items_total\x18\x01 \x01(\x03\x12\x1a\n\x12sync_items_pending\x18\x02 \x01(\x03\x12-\n\tsync_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"g\n\x0fRunStartRequest\x12&\n\x03run\x18\x01 \x01(\x0b\x32\x19.wandb_internal.RunRecord\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x12\n\x10RunStartResponse\"K\n\x1bRunFinishWithoutExitRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x1e\n\x1cRunFinishWithoutExitResponse\"\\\n\x13\x43heckVersionRequest\x12\x17\n\x0f\x63urrent_version\x18\x01 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"]\n\x14\x43heckVersionResponse\x12\x17\n\x0fupgrade_message\x18\x01 \x01(\t\x12\x14\n\x0cyank_message\x18\x02 \x01(\t\x12\x16\n\x0e\x64\x65lete_message\x18\x03 \x01(\t\">\n\x0eJobInfoRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"6\n\x0fJobInfoResponse\x12\x12\n\nsequenceId\x18\x01 \x01(\t\x12\x0f\n\x07version\x18\x02 \x01(\t\"\x9f\x01\n\x12LogArtifactRequest\x12\x30\n\x08\x61rtifact\x18\x01 \x01(\x0b\x32\x1e.wandb_internal.ArtifactRecord\x12\x14\n\x0chistory_step\x18\x02 \x01(\x03\x12\x13\n\x0bstaging_dir\x18\x03 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"A\n\x13LogArtifactResponse\x12\x13\n\x0b\x61rtifact_id\x18\x01 \x01(\t\x12\x15\n\rerror_message\x18\x02 \x01(\t\"\xbe\x01\n\x17\x44ownloadArtifactRequest\x12\x13\n\x0b\x61rtifact_id\x18\x01 \x01(\t\x12\x15\n\rdownload_root\x18\x02 \x01(\t\x12 \n\x18\x61llow_missing_references\x18\x04 \x01(\x08\x12\x12\n\nskip_cache\x18\x05 \x01(\x08\x12\x13\n\x0bpath_prefix\x18\x06 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"1\n\x18\x44ownloadArtifactResponse\x12\x15\n\rerror_message\x18\x01 \x01(\t\"@\n\x10KeepaliveRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x13\n\x11KeepaliveResponse\"q\n\x0c\x41rtifactInfo\x12\x10\n\x08\x61rtifact\x18\x01 \x01(\t\x12\x12\n\nentrypoint\x18\x02 \x03(\t\x12\x10\n\x08notebook\x18\x03 \x01(\x08\x12\x15\n\rbuild_context\x18\x04 \x01(\t\x12\x12\n\ndockerfile\x18\x05 \x01(\t\")\n\x07GitInfo\x12\x0e\n\x06remote\x18\x01 \x01(\t\x12\x0e\n\x06\x63ommit\x18\x02 \x01(\t\"\x87\x01\n\tGitSource\x12)\n\x08git_info\x18\x01 \x01(\x0b\x32\x17.wandb_internal.GitInfo\x12\x12\n\nentrypoint\x18\x02 \x03(\t\x12\x10\n\x08notebook\x18\x03 \x01(\x08\x12\x15\n\rbuild_context\x18\x04 \x01(\t\x12\x12\n\ndockerfile\x18\x05 \x01(\t\"\x1c\n\x0bImageSource\x12\r\n\x05image\x18\x01 \x01(\t\"\x8c\x01\n\x06Source\x12&\n\x03git\x18\x01 \x01(\x0b\x32\x19.wandb_internal.GitSource\x12.\n\x08\x61rtifact\x18\x02 \x01(\x0b\x32\x1c.wandb_internal.ArtifactInfo\x12*\n\x05image\x18\x03 \x01(\x0b\x32\x1b.wandb_internal.ImageSource\"k\n\tJobSource\x12\x10\n\x08_version\x18\x01 \x01(\t\x12\x13\n\x0bsource_type\x18\x02 \x01(\t\x12&\n\x06source\x18\x03 \x01(\x0b\x32\x16.wandb_internal.Source\x12\x0f\n\x07runtime\x18\x04 \x01(\t\"V\n\x12PartialJobArtifact\x12\x10\n\x08job_name\x18\x01 \x01(\t\x12.\n\x0bsource_info\x18\x02 \x01(\x0b\x32\x19.wandb_internal.JobSource\"\x9d\x01\n\x11UseArtifactRecord\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0c\n\x04type\x18\x02 \x01(\t\x12\x0c\n\x04name\x18\x03 \x01(\t\x12\x33\n\x07partial\x18\x04 \x01(\x0b\x32\".wandb_internal.PartialJobArtifact\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x13\n\x11UseArtifactResult\"R\n\rCancelRequest\x12\x13\n\x0b\x63\x61ncel_slot\x18\x01 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x10\n\x0e\x43\x61ncelResponse\"\x18\n\x16ProbeSystemInfoRequest\"\'\n\x08\x44iskInfo\x12\r\n\x05total\x18\x01 \x01(\x04\x12\x0c\n\x04used\x18\x02 \x01(\x04\"\x1b\n\nMemoryInfo\x12\r\n\x05total\x18\x01 \x01(\x04\"/\n\x07\x43puInfo\x12\r\n\x05\x63ount\x18\x01 \x01(\r\x12\x15\n\rcount_logical\x18\x02 \x01(\r\"\x9a\x01\n\tAppleInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\necpu_cores\x18\x02 \x01(\r\x12\x12\n\npcpu_cores\x18\x03 \x01(\r\x12\x11\n\tgpu_cores\x18\x04 \x01(\r\x12\x11\n\tmemory_gb\x18\x05 \x01(\r\x12\x18\n\x10swap_total_bytes\x18\x06 \x01(\x04\x12\x17\n\x0fram_total_bytes\x18\x07 \x01(\x04\"k\n\rGpuNvidiaInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0cmemory_total\x18\x02 \x01(\x04\x12\x12\n\ncuda_cores\x18\x03 \x01(\r\x12\x14\n\x0c\x61rchitecture\x18\x04 \x01(\t\x12\x0c\n\x04uuid\x18\x05 \x01(\t\"\x89\x02\n\nGpuAmdInfo\x12\n\n\x02id\x18\x01 \x01(\t\x12\x11\n\tunique_id\x18\x02 \x01(\t\x12\x15\n\rvbios_version\x18\x03 \x01(\t\x12\x19\n\x11performance_level\x18\x04 \x01(\t\x12\x15\n\rgpu_overdrive\x18\x05 \x01(\t\x12\x1c\n\x14gpu_memory_overdrive\x18\x06 \x01(\t\x12\x11\n\tmax_power\x18\x07 \x01(\t\x12\x0e\n\x06series\x18\x08 \x01(\t\x12\r\n\x05model\x18\t \x01(\t\x12\x0e\n\x06vendor\x18\n \x01(\t\x12\x0b\n\x03sku\x18\x0b \x01(\t\x12\x12\n\nsclk_range\x18\x0c \x01(\t\x12\x12\n\nmclk_range\x18\r \x01(\t\"n\n\x0cTrainiumInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06vendor\x18\x02 \x01(\t\x12\x1b\n\x13neuron_device_count\x18\x03 \x01(\r\x12#\n\x1bneuroncore_per_device_count\x18\x04 \x01(\r\"Q\n\x07TPUInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07hbm_gib\x18\x02 \x01(\r\x12\x18\n\x10\x64\x65vices_per_chip\x18\x03 \x01(\r\x12\r\n\x05\x63ount\x18\x04 \x01(\r\"E\n\rCoreWeaveInfo\x12\x14\n\x0c\x63luster_name\x18\x01 \x01(\t\x12\x0e\n\x06org_id\x18\x02 \x01(\t\x12\x0e\n\x06region\x18\x03 \x01(\t\"\xa8\t\n\x11\x45nvironmentRecord\x12\n\n\x02os\x18\x01 \x01(\t\x12\x0e\n\x06python\x18\x02 \x01(\t\x12\x39\n\nstarted_at\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.TimestampR\tstartedAt\x12\x0e\n\x06\x64ocker\x18\x04 \x01(\t\x12\x0c\n\x04\x61rgs\x18\x05 \x03(\t\x12\x0f\n\x07program\x18\x06 \x01(\t\x12\x1b\n\tcode_path\x18\x07 \x01(\tR\x08\x63odePath\x12&\n\x0f\x63ode_path_local\x18\x08 \x01(\tR\rcodePathLocal\x12*\n\x03git\x18\t \x01(\x0b\x32\x1d.wandb_internal.GitRepoRecord\x12\r\n\x05\x65mail\x18\n \x01(\t\x12\x0c\n\x04root\x18\x0b \x01(\t\x12\x0c\n\x04host\x18\x0c \x01(\t\x12\x10\n\x08username\x18\r \x01(\t\x12\x12\n\nexecutable\x18\x0e \x01(\t\x12\r\n\x05\x63olab\x18\x0f \x01(\t\x12\x1c\n\tcpu_count\x18\x10 \x01(\rR\tcpu_count\x12,\n\x11\x63pu_count_logical\x18\x11 \x01(\rR\x11\x63pu_count_logical\x12\x15\n\x08gpu_type\x18\x12 \x01(\tR\x03gpu\x12\x1c\n\tgpu_count\x18\x13 \x01(\rR\tgpu_count\x12\x39\n\x04\x64isk\x18\x14 \x03(\x0b\x32+.wandb_internal.EnvironmentRecord.DiskEntry\x12*\n\x06memory\x18\x15 \x01(\x0b\x32\x1a.wandb_internal.MemoryInfo\x12$\n\x03\x63pu\x18\x16 \x01(\x0b\x32\x17.wandb_internal.CpuInfo\x12(\n\x05\x61pple\x18\x17 \x01(\x0b\x32\x19.wandb_internal.AppleInfo\x12=\n\ngpu_nvidia\x18\x18 \x03(\x0b\x32\x1d.wandb_internal.GpuNvidiaInfoR\ngpu_nvidia\x12\x14\n\x0c\x63uda_version\x18\x19 \x01(\t\x12\x34\n\x07gpu_amd\x18\x1a \x03(\x0b\x32\x1a.wandb_internal.GpuAmdInfoR\x07gpu_amd\x12;\n\x05slurm\x18\x1b \x03(\x0b\x32,.wandb_internal.EnvironmentRecord.SlurmEntry\x12.\n\x08trainium\x18\x1c \x01(\x0b\x32\x1c.wandb_internal.TrainiumInfo\x12$\n\x03tpu\x18\x1d \x01(\x0b\x32\x17.wandb_internal.TPUInfo\x12\x30\n\tcoreweave\x18\x1e \x01(\x0b\x32\x1d.wandb_internal.CoreWeaveInfo\x12\x12\n\twriter_id\x18\xc7\x01 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\x1a\x45\n\tDiskEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\'\n\x05value\x18\x02 \x01(\x0b\x32\x18.wandb_internal.DiskInfo:\x02\x38\x01\x1a,\n\nSlurmEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x8d\x01\n\x15PythonPackagesRequest\x12\x44\n\x07package\x18\x01 \x03(\x0b\x32\x33.wandb_internal.PythonPackagesRequest.PythonPackage\x1a.\n\rPythonPackage\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07version\x18\x02 \x01(\t\"\x1c\n\x0cJobInputPath\x12\x0c\n\x04path\x18\x01 \x03(\t\"\xd6\x01\n\x0eJobInputSource\x12\x44\n\nrun_config\x18\x01 \x01(\x0b\x32..wandb_internal.JobInputSource.RunConfigSourceH\x00\x12?\n\x04\x66ile\x18\x02 \x01(\x0b\x32/.wandb_internal.JobInputSource.ConfigFileSourceH\x00\x1a\x11\n\x0fRunConfigSource\x1a \n\x10\x43onfigFileSource\x12\x0c\n\x04path\x18\x01 \x01(\tB\x08\n\x06source\"\xc7\x01\n\x0fJobInputRequest\x12\x34\n\x0cinput_source\x18\x01 \x01(\x0b\x32\x1e.wandb_internal.JobInputSource\x12\x33\n\rinclude_paths\x18\x02 \x03(\x0b\x32\x1c.wandb_internal.JobInputPath\x12\x33\n\rexclude_paths\x18\x03 \x03(\x0b\x32\x1c.wandb_internal.JobInputPath\x12\x14\n\x0cinput_schema\x18\x04 \x01(\t\"t\n\x14ServerFeatureRequest\x12.\n\x07\x66\x65\x61ture\x18\x01 \x01(\x0e\x32\x1d.wandb_internal.ServerFeature\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"K\n\x15ServerFeatureResponse\x12\x32\n\x07\x66\x65\x61ture\x18\x01 \x01(\x0b\x32!.wandb_internal.ServerFeatureItem\"2\n\x11ServerFeatureItem\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07\x65nabled\x18\x02 \x01(\x08*\xb3\x04\n\rServerFeature\x12\x13\n\x0fLARGE_FILENAMES\x10\x00\x12\x11\n\rARTIFACT_TAGS\x10\x01\x12\x0e\n\nCLIENT_IDS\x10\x02\x12\x1c\n\x18\x41RTIFACT_REGISTRY_SEARCH\x10\x03\x12\x1b\n\x17STRUCTURED_CONSOLE_LOGS\x10\x04\x12(\n$ARTIFACT_COLLECTION_MEMBERSHIP_FILES\x10\x05\x12\x38\n4ARTIFACT_COLLECTION_MEMBERSHIP_FILE_DOWNLOAD_HANDLER\x10\x06\x12\x34\n0USE_ARTIFACT_WITH_ENTITY_AND_PROJECT_INFORMATION\x10\x07\x12\x1f\n\x1b\x45XPAND_DEFINED_METRIC_GLOBS\x10\x08\x12\x1f\n\x1b\x41UTOMATION_EVENT_RUN_METRIC\x10\t\x12&\n\"AUTOMATION_EVENT_RUN_METRIC_CHANGE\x10\n\x12\x1b\n\x17\x41UTOMATION_ACTION_NO_OP\x10\x0b\x12/\n+INCLUDE_ARTIFACT_TYPES_IN_REGISTRY_CREATION\x10\x0c\x12*\n&PROJECT_ARTIFACT_COLLECTION_MEMBERSHIP\x10\r\x12\x31\n-ARTIFACT_MEMBERSHIP_IN_LINK_ARTIFACT_RESPONSE\x10\x0e\x42\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_internal_pb2', globals())
+if _descriptor._USE_C_DESCRIPTORS == False:
+
+ DESCRIPTOR._options = None
+ DESCRIPTOR._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY._options = None
+ _GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY._serialized_options = b'8\001'
+ _ENVIRONMENTRECORD_DISKENTRY._options = None
+ _ENVIRONMENTRECORD_DISKENTRY._serialized_options = b'8\001'
+ _ENVIRONMENTRECORD_SLURMENTRY._options = None
+ _ENVIRONMENTRECORD_SLURMENTRY._serialized_options = b'8\001'
+ _SERVERFEATURE._serialized_start=22471
+ _SERVERFEATURE._serialized_end=23034
+ _RECORD._serialized_start=209
+ _RECORD._serialized_end=1491
+ _CONTROL._serialized_start=1494
+ _CONTROL._serialized_end=1662
+ _RESULT._serialized_start=1665
+ _RESULT._serialized_end=2164
+ _FINALRECORD._serialized_start=2166
+ _FINALRECORD._serialized_end=2224
+ _VERSIONINFO._serialized_start=2226
+ _VERSIONINFO._serialized_end=2324
+ _HEADERRECORD._serialized_start=2326
+ _HEADERRECORD._serialized_end=2436
+ _FOOTERRECORD._serialized_start=2438
+ _FOOTERRECORD._serialized_end=2497
+ _BRANCHPOINT._serialized_start=2499
+ _BRANCHPOINT._serialized_end=2556
+ _RUNRECORD._serialized_start=2559
+ _RUNRECORD._serialized_end=3216
+ _GITREPORECORD._serialized_start=3218
+ _GITREPORECORD._serialized_end=3277
+ _RUNUPDATERESULT._serialized_start=3279
+ _RUNUPDATERESULT._serialized_end=3378
+ _ERRORINFO._serialized_start=3381
+ _ERRORINFO._serialized_end=3553
+ _ERRORINFO_ERRORCODE._serialized_start=3462
+ _ERRORINFO_ERRORCODE._serialized_end=3553
+ _RUNEXITRECORD._serialized_start=3555
+ _RUNEXITRECORD._serialized_end=3651
+ _RUNEXITRESULT._serialized_start=3653
+ _RUNEXITRESULT._serialized_end=3668
+ _RUNPREEMPTINGRECORD._serialized_start=3670
+ _RUNPREEMPTINGRECORD._serialized_end=3736
+ _RUNPREEMPTINGRESULT._serialized_start=3738
+ _RUNPREEMPTINGRESULT._serialized_end=3759
+ _SETTINGSRECORD._serialized_start=3761
+ _SETTINGSRECORD._serialized_end=3866
+ _SETTINGSITEM._serialized_start=3868
+ _SETTINGSITEM._serialized_end=3915
+ _HISTORYSTEP._serialized_start=3917
+ _HISTORYSTEP._serialized_end=3943
+ _HISTORYRECORD._serialized_start=3946
+ _HISTORYRECORD._serialized_end=4092
+ _HISTORYITEM._serialized_start=4094
+ _HISTORYITEM._serialized_end=4160
+ _HISTORYRESULT._serialized_start=4162
+ _HISTORYRESULT._serialized_end=4177
+ _OUTPUTRECORD._serialized_start=4180
+ _OUTPUTRECORD._serialized_end=4400
+ _OUTPUTRECORD_OUTPUTTYPE._serialized_start=4364
+ _OUTPUTRECORD_OUTPUTTYPE._serialized_end=4400
+ _OUTPUTRESULT._serialized_start=4402
+ _OUTPUTRESULT._serialized_end=4416
+ _OUTPUTRAWRECORD._serialized_start=4419
+ _OUTPUTRAWRECORD._serialized_end=4645
+ _OUTPUTRAWRECORD_OUTPUTTYPE._serialized_start=4364
+ _OUTPUTRAWRECORD_OUTPUTTYPE._serialized_end=4400
+ _OUTPUTRAWRESULT._serialized_start=4647
+ _OUTPUTRAWRESULT._serialized_end=4664
+ _METRICRECORD._serialized_start=4667
+ _METRICRECORD._serialized_end=5103
+ _METRICRECORD_METRICGOAL._serialized_start=5037
+ _METRICRECORD_METRICGOAL._serialized_end=5103
+ _METRICRESULT._serialized_start=5105
+ _METRICRESULT._serialized_end=5119
+ _METRICOPTIONS._serialized_start=5121
+ _METRICOPTIONS._serialized_end=5188
+ _METRICCONTROL._serialized_start=5190
+ _METRICCONTROL._serialized_end=5224
+ _METRICSUMMARY._serialized_start=5226
+ _METRICSUMMARY._serialized_end=5352
+ _CONFIGRECORD._serialized_start=5355
+ _CONFIGRECORD._serialized_end=5502
+ _CONFIGITEM._serialized_start=5504
+ _CONFIGITEM._serialized_end=5569
+ _CONFIGRESULT._serialized_start=5571
+ _CONFIGRESULT._serialized_end=5585
+ _SUMMARYRECORD._serialized_start=5588
+ _SUMMARYRECORD._serialized_end=5738
+ _SUMMARYITEM._serialized_start=5740
+ _SUMMARYITEM._serialized_end=5806
+ _SUMMARYRESULT._serialized_start=5808
+ _SUMMARYRESULT._serialized_end=5823
+ _FILESRECORD._serialized_start=5825
+ _FILESRECORD._serialized_end=5925
+ _FILESITEM._serialized_start=5928
+ _FILESITEM._serialized_end=6164
+ _FILESITEM_POLICYTYPE._serialized_start=6059
+ _FILESITEM_POLICYTYPE._serialized_end=6099
+ _FILESITEM_FILETYPE._serialized_start=6101
+ _FILESITEM_FILETYPE._serialized_end=6158
+ _FILESRESULT._serialized_start=6166
+ _FILESRESULT._serialized_end=6179
+ _STATSRECORD._serialized_start=6182
+ _STATSRECORD._serialized_end=6412
+ _STATSRECORD_STATSTYPE._serialized_start=6389
+ _STATSRECORD_STATSTYPE._serialized_end=6412
+ _STATSITEM._serialized_start=6414
+ _STATSITEM._serialized_end=6458
+ _ARTIFACTRECORD._serialized_start=6461
+ _ARTIFACTRECORD._serialized_end=6948
+ _ARTIFACTMANIFEST._serialized_start=6951
+ _ARTIFACTMANIFEST._serialized_end=7167
+ _ARTIFACTMANIFESTENTRY._serialized_start=7170
+ _ARTIFACTMANIFESTENTRY._serialized_end=7377
+ _EXTRAITEM._serialized_start=7379
+ _EXTRAITEM._serialized_end=7423
+ _STORAGEPOLICYCONFIGITEM._serialized_start=7425
+ _STORAGEPOLICYCONFIGITEM._serialized_end=7483
+ _ARTIFACTRESULT._serialized_start=7485
+ _ARTIFACTRESULT._serialized_end=7501
+ _LINKARTIFACTRESULT._serialized_start=7503
+ _LINKARTIFACTRESULT._serialized_end=7523
+ _LINKARTIFACTREQUEST._serialized_start=7526
+ _LINKARTIFACTREQUEST._serialized_end=7766
+ _LINKARTIFACTRESPONSE._serialized_start=7768
+ _LINKARTIFACTRESPONSE._serialized_end=7859
+ _TBRECORD._serialized_start=7861
+ _TBRECORD._serialized_end=7965
+ _TBRESULT._serialized_start=7967
+ _TBRESULT._serialized_end=7977
+ _ALERTRECORD._serialized_start=7979
+ _ALERTRECORD._serialized_end=8104
+ _ALERTRESULT._serialized_start=8106
+ _ALERTRESULT._serialized_end=8119
+ _REQUEST._serialized_start=8122
+ _REQUEST._serialized_end=10418
+ _RESPONSE._serialized_start=10421
+ _RESPONSE._serialized_end=12293
+ _DEFERREQUEST._serialized_start=12296
+ _DEFERREQUEST._serialized_end=12616
+ _DEFERREQUEST_DEFERSTATE._serialized_start=12369
+ _DEFERREQUEST_DEFERSTATE._serialized_end=12616
+ _PAUSEREQUEST._serialized_start=12618
+ _PAUSEREQUEST._serialized_end=12678
+ _PAUSERESPONSE._serialized_start=12680
+ _PAUSERESPONSE._serialized_end=12695
+ _RESUMEREQUEST._serialized_start=12697
+ _RESUMEREQUEST._serialized_end=12758
+ _RESUMERESPONSE._serialized_start=12760
+ _RESUMERESPONSE._serialized_end=12776
+ _LOGINREQUEST._serialized_start=12778
+ _LOGINREQUEST._serialized_end=12855
+ _LOGINRESPONSE._serialized_start=12857
+ _LOGINRESPONSE._serialized_end=12895
+ _GETSUMMARYREQUEST._serialized_start=12897
+ _GETSUMMARYREQUEST._serialized_end=12962
+ _GETSUMMARYRESPONSE._serialized_start=12964
+ _GETSUMMARYRESPONSE._serialized_end=13027
+ _GETSYSTEMMETRICSREQUEST._serialized_start=13029
+ _GETSYSTEMMETRICSREQUEST._serialized_end=13100
+ _SYSTEMMETRICSAMPLE._serialized_start=13102
+ _SYSTEMMETRICSAMPLE._serialized_end=13184
+ _SYSTEMMETRICSBUFFER._serialized_start=13186
+ _SYSTEMMETRICSBUFFER._serialized_end=13259
+ _GETSYSTEMMETRICSRESPONSE._serialized_start=13262
+ _GETSYSTEMMETRICSRESPONSE._serialized_end=13464
+ _GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY._serialized_start=13375
+ _GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY._serialized_end=13464
+ _STATUSREQUEST._serialized_start=13466
+ _STATUSREQUEST._serialized_end=13527
+ _STATUSRESPONSE._serialized_start=13529
+ _STATUSRESPONSE._serialized_end=13570
+ _STOPSTATUSREQUEST._serialized_start=13572
+ _STOPSTATUSREQUEST._serialized_end=13637
+ _STOPSTATUSRESPONSE._serialized_start=13639
+ _STOPSTATUSRESPONSE._serialized_end=13684
+ _NETWORKSTATUSREQUEST._serialized_start=13686
+ _NETWORKSTATUSREQUEST._serialized_end=13754
+ _NETWORKSTATUSRESPONSE._serialized_start=13756
+ _NETWORKSTATUSRESPONSE._serialized_end=13836
+ _HTTPRESPONSE._serialized_start=13838
+ _HTTPRESPONSE._serialized_end=13906
+ _INTERNALMESSAGESREQUEST._serialized_start=13908
+ _INTERNALMESSAGESREQUEST._serialized_end=13979
+ _INTERNALMESSAGESRESPONSE._serialized_start=13981
+ _INTERNALMESSAGESRESPONSE._serialized_end=14059
+ _INTERNALMESSAGES._serialized_start=14061
+ _INTERNALMESSAGES._serialized_end=14096
+ _POLLEXITREQUEST._serialized_start=14098
+ _POLLEXITREQUEST._serialized_end=14161
+ _POLLEXITRESPONSE._serialized_start=14164
+ _POLLEXITRESPONSE._serialized_end=14409
+ _OPERATIONSTATSREQUEST._serialized_start=14411
+ _OPERATIONSTATSREQUEST._serialized_end=14480
+ _OPERATIONSTATSRESPONSE._serialized_start=14482
+ _OPERATIONSTATSRESPONSE._serialized_end=14563
+ _OPERATIONSTATS._serialized_start=14565
+ _OPERATIONSTATS._serialized_end=14654
+ _OPERATION._serialized_start=14657
+ _OPERATION._serialized_end=14792
+ _SENDERMARKREQUEST._serialized_start=14794
+ _SENDERMARKREQUEST._serialized_end=14813
+ _SYNCFINISHREQUEST._serialized_start=14815
+ _SYNCFINISHREQUEST._serialized_end=14834
+ _SYNCRESPONSE._serialized_start=14836
+ _SYNCRESPONSE._serialized_end=14905
+ _SENDERREADREQUEST._serialized_start=14907
+ _SENDERREADREQUEST._serialized_end=14970
+ _STATUSREPORTREQUEST._serialized_start=14972
+ _STATUSREPORTREQUEST._serialized_end=15081
+ _SUMMARYRECORDREQUEST._serialized_start=15083
+ _SUMMARYRECORDREQUEST._serialized_end=15153
+ _TELEMETRYRECORDREQUEST._serialized_start=15155
+ _TELEMETRYRECORDREQUEST._serialized_end=15231
+ _SERVERINFOREQUEST._serialized_start=15233
+ _SERVERINFOREQUEST._serialized_end=15298
+ _SERVERINFORESPONSE._serialized_start=15300
+ _SERVERINFORESPONSE._serialized_end=15424
+ _SERVERMESSAGES._serialized_start=15426
+ _SERVERMESSAGES._serialized_end=15487
+ _SERVERMESSAGE._serialized_start=15489
+ _SERVERMESSAGE._serialized_end=15590
+ _FILECOUNTS._serialized_start=15592
+ _FILECOUNTS._serialized_end=15691
+ _FILEPUSHERSTATS._serialized_start=15693
+ _FILEPUSHERSTATS._serialized_end=15778
+ _FILESUPLOADED._serialized_start=15780
+ _FILESUPLOADED._serialized_end=15810
+ _FILETRANSFERINFOREQUEST._serialized_start=15813
+ _FILETRANSFERINFOREQUEST._serialized_end=16057
+ _FILETRANSFERINFOREQUEST_TRANSFERTYPE._serialized_start=16017
+ _FILETRANSFERINFOREQUEST_TRANSFERTYPE._serialized_end=16057
+ _LOCALINFO._serialized_start=16059
+ _LOCALINFO._serialized_end=16108
+ _SHUTDOWNREQUEST._serialized_start=16110
+ _SHUTDOWNREQUEST._serialized_end=16173
+ _SHUTDOWNRESPONSE._serialized_start=16175
+ _SHUTDOWNRESPONSE._serialized_end=16193
+ _ATTACHREQUEST._serialized_start=16195
+ _ATTACHREQUEST._serialized_end=16275
+ _ATTACHRESPONSE._serialized_start=16277
+ _ATTACHRESPONSE._serialized_end=16375
+ _TESTINJECTREQUEST._serialized_start=16378
+ _TESTINJECTREQUEST._serialized_end=16719
+ _TESTINJECTRESPONSE._serialized_start=16721
+ _TESTINJECTRESPONSE._serialized_end=16741
+ _HISTORYACTION._serialized_start=16743
+ _HISTORYACTION._serialized_end=16773
+ _PARTIALHISTORYREQUEST._serialized_start=16776
+ _PARTIALHISTORYREQUEST._serialized_end=16978
+ _PARTIALHISTORYRESPONSE._serialized_start=16980
+ _PARTIALHISTORYRESPONSE._serialized_end=17004
+ _SAMPLEDHISTORYREQUEST._serialized_start=17006
+ _SAMPLEDHISTORYREQUEST._serialized_end=17075
+ _SAMPLEDHISTORYITEM._serialized_start=17077
+ _SAMPLEDHISTORYITEM._serialized_end=17172
+ _SAMPLEDHISTORYRESPONSE._serialized_start=17174
+ _SAMPLEDHISTORYRESPONSE._serialized_end=17248
+ _RUNSTATUSREQUEST._serialized_start=17250
+ _RUNSTATUSREQUEST._serialized_end=17314
+ _RUNSTATUSRESPONSE._serialized_start=17316
+ _RUNSTATUSRESPONSE._serialized_end=17436
+ _RUNSTARTREQUEST._serialized_start=17438
+ _RUNSTARTREQUEST._serialized_end=17541
+ _RUNSTARTRESPONSE._serialized_start=17543
+ _RUNSTARTRESPONSE._serialized_end=17561
+ _RUNFINISHWITHOUTEXITREQUEST._serialized_start=17563
+ _RUNFINISHWITHOUTEXITREQUEST._serialized_end=17638
+ _RUNFINISHWITHOUTEXITRESPONSE._serialized_start=17640
+ _RUNFINISHWITHOUTEXITRESPONSE._serialized_end=17670
+ _CHECKVERSIONREQUEST._serialized_start=17672
+ _CHECKVERSIONREQUEST._serialized_end=17764
+ _CHECKVERSIONRESPONSE._serialized_start=17766
+ _CHECKVERSIONRESPONSE._serialized_end=17859
+ _JOBINFOREQUEST._serialized_start=17861
+ _JOBINFOREQUEST._serialized_end=17923
+ _JOBINFORESPONSE._serialized_start=17925
+ _JOBINFORESPONSE._serialized_end=17979
+ _LOGARTIFACTREQUEST._serialized_start=17982
+ _LOGARTIFACTREQUEST._serialized_end=18141
+ _LOGARTIFACTRESPONSE._serialized_start=18143
+ _LOGARTIFACTRESPONSE._serialized_end=18208
+ _DOWNLOADARTIFACTREQUEST._serialized_start=18211
+ _DOWNLOADARTIFACTREQUEST._serialized_end=18401
+ _DOWNLOADARTIFACTRESPONSE._serialized_start=18403
+ _DOWNLOADARTIFACTRESPONSE._serialized_end=18452
+ _KEEPALIVEREQUEST._serialized_start=18454
+ _KEEPALIVEREQUEST._serialized_end=18518
+ _KEEPALIVERESPONSE._serialized_start=18520
+ _KEEPALIVERESPONSE._serialized_end=18539
+ _ARTIFACTINFO._serialized_start=18541
+ _ARTIFACTINFO._serialized_end=18654
+ _GITINFO._serialized_start=18656
+ _GITINFO._serialized_end=18697
+ _GITSOURCE._serialized_start=18700
+ _GITSOURCE._serialized_end=18835
+ _IMAGESOURCE._serialized_start=18837
+ _IMAGESOURCE._serialized_end=18865
+ _SOURCE._serialized_start=18868
+ _SOURCE._serialized_end=19008
+ _JOBSOURCE._serialized_start=19010
+ _JOBSOURCE._serialized_end=19117
+ _PARTIALJOBARTIFACT._serialized_start=19119
+ _PARTIALJOBARTIFACT._serialized_end=19205
+ _USEARTIFACTRECORD._serialized_start=19208
+ _USEARTIFACTRECORD._serialized_end=19365
+ _USEARTIFACTRESULT._serialized_start=19367
+ _USEARTIFACTRESULT._serialized_end=19386
+ _CANCELREQUEST._serialized_start=19388
+ _CANCELREQUEST._serialized_end=19470
+ _CANCELRESPONSE._serialized_start=19472
+ _CANCELRESPONSE._serialized_end=19488
+ _PROBESYSTEMINFOREQUEST._serialized_start=19490
+ _PROBESYSTEMINFOREQUEST._serialized_end=19514
+ _DISKINFO._serialized_start=19516
+ _DISKINFO._serialized_end=19555
+ _MEMORYINFO._serialized_start=19557
+ _MEMORYINFO._serialized_end=19584
+ _CPUINFO._serialized_start=19586
+ _CPUINFO._serialized_end=19633
+ _APPLEINFO._serialized_start=19636
+ _APPLEINFO._serialized_end=19790
+ _GPUNVIDIAINFO._serialized_start=19792
+ _GPUNVIDIAINFO._serialized_end=19899
+ _GPUAMDINFO._serialized_start=19902
+ _GPUAMDINFO._serialized_end=20167
+ _TRAINIUMINFO._serialized_start=20169
+ _TRAINIUMINFO._serialized_end=20279
+ _TPUINFO._serialized_start=20281
+ _TPUINFO._serialized_end=20362
+ _COREWEAVEINFO._serialized_start=20364
+ _COREWEAVEINFO._serialized_end=20433
+ _ENVIRONMENTRECORD._serialized_start=20436
+ _ENVIRONMENTRECORD._serialized_end=21628
+ _ENVIRONMENTRECORD_DISKENTRY._serialized_start=21513
+ _ENVIRONMENTRECORD_DISKENTRY._serialized_end=21582
+ _ENVIRONMENTRECORD_SLURMENTRY._serialized_start=21584
+ _ENVIRONMENTRECORD_SLURMENTRY._serialized_end=21628
+ _PYTHONPACKAGESREQUEST._serialized_start=21631
+ _PYTHONPACKAGESREQUEST._serialized_end=21772
+ _PYTHONPACKAGESREQUEST_PYTHONPACKAGE._serialized_start=21726
+ _PYTHONPACKAGESREQUEST_PYTHONPACKAGE._serialized_end=21772
+ _JOBINPUTPATH._serialized_start=21774
+ _JOBINPUTPATH._serialized_end=21802
+ _JOBINPUTSOURCE._serialized_start=21805
+ _JOBINPUTSOURCE._serialized_end=22019
+ _JOBINPUTSOURCE_RUNCONFIGSOURCE._serialized_start=21958
+ _JOBINPUTSOURCE_RUNCONFIGSOURCE._serialized_end=21975
+ _JOBINPUTSOURCE_CONFIGFILESOURCE._serialized_start=21977
+ _JOBINPUTSOURCE_CONFIGFILESOURCE._serialized_end=22009
+ _JOBINPUTREQUEST._serialized_start=22022
+ _JOBINPUTREQUEST._serialized_end=22221
+ _SERVERFEATUREREQUEST._serialized_start=22223
+ _SERVERFEATUREREQUEST._serialized_end=22339
+ _SERVERFEATURERESPONSE._serialized_start=22341
+ _SERVERFEATURERESPONSE._serialized_end=22416
+ _SERVERFEATUREITEM._serialized_start=22418
+ _SERVERFEATUREITEM._serialized_end=22468
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/wandb_server_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/wandb_server_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..53d1c66ef493c96a8618f78fdb22da9b9ad155d9
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/wandb_server_pb2.py
@@ -0,0 +1,64 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: wandb/proto/wandb_server.proto
+"""Generated protocol buffer code."""
+from google.protobuf.internal import builder as _builder
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2
+from wandb.proto import wandb_internal_pb2 as wandb_dot_proto_dot_wandb__internal__pb2
+from wandb.proto import wandb_settings_pb2 as wandb_dot_proto_dot_wandb__settings__pb2
+from wandb.proto import wandb_sync_pb2 as wandb_dot_proto_dot_wandb__sync__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1ewandb/proto/wandb_server.proto\x12\x0ewandb_internal\x1a\x1cwandb/proto/wandb_base.proto\x1a wandb/proto/wandb_internal.proto\x1a wandb/proto/wandb_settings.proto\x1a\x1cwandb/proto/wandb_sync.proto\"k\n\x19ServerAuthenticateRequest\x12\x0f\n\x07\x61pi_key\x18\x01 \x01(\t\x12\x10\n\x08\x62\x61se_url\x18\x02 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"w\n\x1aServerAuthenticateResponse\x12\x16\n\x0e\x64\x65\x66\x61ult_entity\x18\x01 \x01(\t\x12\x14\n\x0c\x65rror_status\x18\x02 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"D\n\x15ServerShutdownRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x18\n\x16ServerShutdownResponse\"B\n\x13ServerStatusRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x16\n\x14ServerStatusResponse\"r\n\x17ServerInformInitRequest\x12*\n\x08settings\x18\x01 \x01(\x0b\x32\x18.wandb_internal.Settings\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1a\n\x18ServerInformInitResponse\"H\n\x19ServerInformFinishRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1c\n\x1aServerInformFinishResponse\"H\n\x19ServerInformAttachRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"u\n\x1aServerInformAttachResponse\x12*\n\x08settings\x18\x01 \x01(\x0b\x32\x18.wandb_internal.Settings\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"H\n\x19ServerInformDetachRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1c\n\x1aServerInformDetachResponse\"]\n\x1bServerInformTeardownRequest\x12\x11\n\texit_code\x18\x01 \x01(\x05\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1e\n\x1cServerInformTeardownResponse\"\xee\x05\n\rServerRequest\x12\x12\n\nrequest_id\x18\n \x01(\t\x12\x30\n\x0erecord_publish\x18\x01 \x01(\x0b\x32\x16.wandb_internal.RecordH\x00\x12\x34\n\x12record_communicate\x18\x02 \x01(\x0b\x32\x16.wandb_internal.RecordH\x00\x12>\n\x0binform_init\x18\x03 \x01(\x0b\x32\'.wandb_internal.ServerInformInitRequestH\x00\x12\x42\n\rinform_finish\x18\x04 \x01(\x0b\x32).wandb_internal.ServerInformFinishRequestH\x00\x12\x42\n\rinform_attach\x18\x05 \x01(\x0b\x32).wandb_internal.ServerInformAttachRequestH\x00\x12\x42\n\rinform_detach\x18\x06 \x01(\x0b\x32).wandb_internal.ServerInformDetachRequestH\x00\x12\x46\n\x0finform_teardown\x18\x07 \x01(\x0b\x32+.wandb_internal.ServerInformTeardownRequestH\x00\x12\x41\n\x0c\x61uthenticate\x18\t \x01(\x0b\x32).wandb_internal.ServerAuthenticateRequestH\x00\x12:\n\tinit_sync\x18\x0b \x01(\x0b\x32%.wandb_internal.ServerInitSyncRequestH\x00\x12\x31\n\x04sync\x18\x0c \x01(\x0b\x32!.wandb_internal.ServerSyncRequestH\x00\x12>\n\x0bsync_status\x18\r \x01(\x0b\x32\'.wandb_internal.ServerSyncStatusRequestH\x00\x42\x15\n\x13server_request_typeJ\x04\x08\x08\x10\t\"\x98\x06\n\x0eServerResponse\x12\x12\n\nrequest_id\x18\n \x01(\t\x12\x34\n\x12result_communicate\x18\x02 \x01(\x0b\x32\x16.wandb_internal.ResultH\x00\x12H\n\x14inform_init_response\x18\x03 \x01(\x0b\x32(.wandb_internal.ServerInformInitResponseH\x00\x12L\n\x16inform_finish_response\x18\x04 \x01(\x0b\x32*.wandb_internal.ServerInformFinishResponseH\x00\x12L\n\x16inform_attach_response\x18\x05 \x01(\x0b\x32*.wandb_internal.ServerInformAttachResponseH\x00\x12L\n\x16inform_detach_response\x18\x06 \x01(\x0b\x32*.wandb_internal.ServerInformDetachResponseH\x00\x12P\n\x18inform_teardown_response\x18\x07 \x01(\x0b\x32,.wandb_internal.ServerInformTeardownResponseH\x00\x12K\n\x15\x61uthenticate_response\x18\t \x01(\x0b\x32*.wandb_internal.ServerAuthenticateResponseH\x00\x12\x44\n\x12init_sync_response\x18\x0b \x01(\x0b\x32&.wandb_internal.ServerInitSyncResponseH\x00\x12;\n\rsync_response\x18\x0c \x01(\x0b\x32\".wandb_internal.ServerSyncResponseH\x00\x12H\n\x14sync_status_response\x18\r \x01(\x0b\x32(.wandb_internal.ServerSyncStatusResponseH\x00\x42\x16\n\x14server_response_typeJ\x04\x08\x08\x10\tB\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_server_pb2', globals())
+if _descriptor._USE_C_DESCRIPTORS == False:
+
+ DESCRIPTOR._options = None
+ DESCRIPTOR._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _SERVERAUTHENTICATEREQUEST._serialized_start=178
+ _SERVERAUTHENTICATEREQUEST._serialized_end=285
+ _SERVERAUTHENTICATERESPONSE._serialized_start=287
+ _SERVERAUTHENTICATERESPONSE._serialized_end=406
+ _SERVERSHUTDOWNREQUEST._serialized_start=408
+ _SERVERSHUTDOWNREQUEST._serialized_end=476
+ _SERVERSHUTDOWNRESPONSE._serialized_start=478
+ _SERVERSHUTDOWNRESPONSE._serialized_end=502
+ _SERVERSTATUSREQUEST._serialized_start=504
+ _SERVERSTATUSREQUEST._serialized_end=570
+ _SERVERSTATUSRESPONSE._serialized_start=572
+ _SERVERSTATUSRESPONSE._serialized_end=594
+ _SERVERINFORMINITREQUEST._serialized_start=596
+ _SERVERINFORMINITREQUEST._serialized_end=710
+ _SERVERINFORMINITRESPONSE._serialized_start=712
+ _SERVERINFORMINITRESPONSE._serialized_end=738
+ _SERVERINFORMFINISHREQUEST._serialized_start=740
+ _SERVERINFORMFINISHREQUEST._serialized_end=812
+ _SERVERINFORMFINISHRESPONSE._serialized_start=814
+ _SERVERINFORMFINISHRESPONSE._serialized_end=842
+ _SERVERINFORMATTACHREQUEST._serialized_start=844
+ _SERVERINFORMATTACHREQUEST._serialized_end=916
+ _SERVERINFORMATTACHRESPONSE._serialized_start=918
+ _SERVERINFORMATTACHRESPONSE._serialized_end=1035
+ _SERVERINFORMDETACHREQUEST._serialized_start=1037
+ _SERVERINFORMDETACHREQUEST._serialized_end=1109
+ _SERVERINFORMDETACHRESPONSE._serialized_start=1111
+ _SERVERINFORMDETACHRESPONSE._serialized_end=1139
+ _SERVERINFORMTEARDOWNREQUEST._serialized_start=1141
+ _SERVERINFORMTEARDOWNREQUEST._serialized_end=1234
+ _SERVERINFORMTEARDOWNRESPONSE._serialized_start=1236
+ _SERVERINFORMTEARDOWNRESPONSE._serialized_end=1266
+ _SERVERREQUEST._serialized_start=1269
+ _SERVERREQUEST._serialized_end=2019
+ _SERVERRESPONSE._serialized_start=2022
+ _SERVERRESPONSE._serialized_end=2814
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/wandb_settings_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/wandb_settings_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..ffdc16cb43c99b34a60f875b06e4d6a40086f7b6
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/wandb_settings_pb2.py
@@ -0,0 +1,47 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: wandb/proto/wandb_settings.proto
+"""Generated protocol buffer code."""
+from google.protobuf.internal import builder as _builder
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from google.protobuf import wrappers_pb2 as google_dot_protobuf_dot_wrappers__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n wandb/proto/wandb_settings.proto\x12\x0ewandb_internal\x1a\x1egoogle/protobuf/wrappers.proto\" \n\x0fListStringValue\x12\r\n\x05value\x18\x01 \x03(\t\"\x1d\n\x0cListIntValue\x12\r\n\x05value\x18\x01 \x03(\x05\"\x8a\x01\n\x17MapStringKeyStringValue\x12\x41\n\x05value\x18\x01 \x03(\x0b\x32\x32.wandb_internal.MapStringKeyStringValue.ValueEntry\x1a,\n\nValueEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xcb\x01\n#MapStringKeyMapStringKeyStringValue\x12M\n\x05value\x18\x01 \x03(\x0b\x32>.wandb_internal.MapStringKeyMapStringKeyStringValue.ValueEntry\x1aU\n\nValueEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x36\n\x05value\x18\x02 \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue:\x02\x38\x01\"\x9a\x01\n\x12OpenMetricsFilters\x12\x33\n\x08sequence\x18\x01 \x01(\x0b\x32\x1f.wandb_internal.ListStringValueH\x00\x12\x46\n\x07mapping\x18\x02 \x01(\x0b\x32\x33.wandb_internal.MapStringKeyMapStringKeyStringValueH\x00\x42\x07\n\x05value\"7\n\tRunMoment\x12\x0b\n\x03run\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x01\x12\x0e\n\x06metric\x18\x03 \x01(\t\"\xc2M\n\x08Settings\x12-\n\x07\x61pi_key\x18\x37 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12:\n\x13identity_token_file\x18\xaa\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x37\n\x10\x63redentials_file\x18\xab\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x39\n\x14insecure_disable_ssl\x18\xb9\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12,\n\x08_offline\x18\x1e \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12*\n\x06x_sync\x18\x1f \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x30\n\tsync_file\x18\x86\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x07_shared\x18\xa2\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12,\n\x06run_id\x18k \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12-\n\x07run_url\x18q \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12-\n\x07project\x18\x61 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x06\x65ntity\x18\x45 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x33\n\x0corganization\x18\xbc\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0cx_start_time\x18) \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12.\n\x08root_dir\x18i \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12-\n\x07log_dir\x18U \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0clog_internal\x18V \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0cignore_globs\x18N \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12.\n\x08\x62\x61se_url\x18\x39 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12=\n\x17x_file_stream_max_bytes\x18\xac\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x46\n\x1fx_file_stream_transmit_interval\x18\xaf\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x45\n\x14x_extra_http_headers\x18\x0e \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12=\n\x17x_file_stream_retry_max\x18\x93\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12K\n$x_file_stream_retry_wait_min_seconds\x18\x94\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12K\n$x_file_stream_retry_wait_max_seconds\x18\x95\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x43\n\x1dx_file_stream_timeout_seconds\x18\x0f \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x42\n\x1cx_file_stream_max_line_bytes\x18\xb2\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12?\n\x19x_file_transfer_retry_max\x18\x96\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12M\n&x_file_transfer_retry_wait_min_seconds\x18\x97\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12M\n&x_file_transfer_retry_wait_max_seconds\x18\x98\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x46\n\x1fx_file_transfer_timeout_seconds\x18\x99\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x39\n\x13x_graphql_retry_max\x18\x9a\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12G\n x_graphql_retry_wait_min_seconds\x18\x9b\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12G\n x_graphql_retry_wait_max_seconds\x18\x9c\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12@\n\x19x_graphql_timeout_seconds\x18\x9d\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x31\n\nhttp_proxy\x18\xa8\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0bhttps_proxy\x18\xa9\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12;\n\tx_proxies\x18\xc8\x01 \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12-\n\x07program\x18_ \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0fprogram_relpath\x18` \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x37\n\x10_code_path_local\x18\xa3\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x36\n\x0fprogram_abspath\x18\x9f\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x05_args\x18\x01 \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12)\n\x03_os\x18 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x06\x64ocker\x18\x43 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0cx_executable\x18\r \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12-\n\x07_python\x18\" \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x30\n\tcolab_url\x18\xa0\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12*\n\x04host\x18M \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x08username\x18\x8d\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12+\n\x05\x65mail\x18\x44 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x06resume\x18\x66 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x0bresume_from\x18\xa7\x01 \x01(\x0b\x32\x19.wandb_internal.RunMoment\x12-\n\tfork_from\x18\xa4\x01 \x01(\x0b\x32\x19.wandb_internal.RunMoment\x12\x38\n\x14\x64isable_job_creation\x18\x41 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x30\n\tsweep_url\x18\x83\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12;\n\x16x_disable_update_check\x18\xa5\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x32\n\x0ex_disable_meta\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12-\n\tsave_code\x18s \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\x0b\x64isable_git\x18? \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12;\n\x16x_disable_machine_info\x18\x9e\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x33\n\x0fx_disable_stats\x18\n \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x39\n\x13x_stats_buffer_size\x18\xa1\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12@\n\x19x_stats_sampling_interval\x18\xae\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x30\n\x0bx_stats_pid\x18* \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12<\n\x12x_stats_disk_paths\x18\x92\x01 \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12H\n\"x_stats_neuron_monitor_config_path\x18. \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12<\n\x15x_stats_dcgm_exporter\x18\xbb\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12O\n\x1ex_stats_open_metrics_endpoints\x18/ \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12H\n\x1cx_stats_open_metrics_filters\x18\x30 \x01(\x0b\x32\".wandb_internal.OpenMetricsFilters\x12S\n!x_stats_open_metrics_http_headers\x18\xb8\x01 \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12=\n\x16x_stats_gpu_device_ids\x18\xba\x01 \x01(\x0b\x32\x1c.wandb_internal.ListIntValue\x12\x37\n\x11x_stats_cpu_count\x18\xc2\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12?\n\x19x_stats_cpu_logical_count\x18\xc3\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x37\n\x11x_stats_gpu_count\x18\xc4\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x37\n\x10x_stats_gpu_type\x18\xc5\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12?\n\x1ax_stats_track_process_tree\x18\xc6\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12.\n\x07x_label\x18\xb5\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\tx_primary\x18\xb6\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12:\n\x15x_update_finish_state\x18\xb7\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12<\n\x17\x61llow_offline_artifacts\x18\xb1\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12-\n\x07\x63onsole\x18< \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x36\n\x11\x63onsole_multipart\x18\xa6\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x35\n\x10sync_tensorboard\x18\xb3\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x42\n\x1dx_server_side_derived_summary\x18\xbd\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x46\n!x_server_side_expand_glob_metrics\x18\xbe\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12;\n\x16x_skip_transaction_log\x18\xbf\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12J\n#x_stats_coreweave_metadata_base_url\x18\xc0\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12J\n#x_stats_coreweave_metadata_endpoint\x18\xc1\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x0b_aws_lambda\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x33\n\x0fx_cli_only_mode\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12*\n\x06_colab\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x34\n\x10x_disable_viewer\x18\x0b \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x39\n\x15x_flow_control_custom\x18\x10 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12;\n\x17x_flow_control_disabled\x18\x11 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12>\n\x18x_internal_check_process\x18\x12 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12,\n\x08_ipython\x18\x14 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12,\n\x08_jupyter\x18\x15 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x34\n\x0ex_jupyter_root\x18\x16 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12+\n\x07_kaggle\x18\x17 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12=\n\x18x_live_policy_rate_limit\x18\x18 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12<\n\x17x_live_policy_wait_time\x18\x19 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x30\n\x0bx_log_level\x18\x1a \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x35\n\x10x_network_buffer\x18\x1b \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12)\n\x05_noop\x18\x1c \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12-\n\t_notebook\x18\x1d \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\t_platform\x18! \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x38\n\x12x_runqueue_item_id\x18# \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x37\n\x13x_save_requirements\x18% \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x39\n\x13x_service_transport\x18& \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x34\n\x0ex_service_wait\x18\' \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x35\n\x0f_start_datetime\x18( \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x33\n\r_tmp_code_dir\x18\x31 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x08_windows\x18\x34 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x34\n\x10\x61llow_val_change\x18\x35 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\tanonymous\x18\x36 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12P\n\x1f\x61zure_account_url_to_access_key\x18\x38 \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12.\n\x08\x63ode_dir\x18: \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0c\x63onfig_paths\x18; \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12\x30\n\ndeployment\x18= \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x30\n\x0c\x64isable_code\x18> \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x31\n\rdisable_hints\x18@ \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12,\n\x08\x64isabled\x18\x42 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12)\n\x05\x66orce\x18G \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x30\n\ngit_commit\x18H \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x30\n\ngit_remote\x18I \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x34\n\x0egit_remote_url\x18J \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x08git_root\x18K \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x36\n\x11heartbeat_seconds\x18L \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x32\n\x0cinit_timeout\x18O \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12,\n\x08is_local\x18P \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x30\n\njob_source\x18Q \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x31\n\rlabel_disable\x18R \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12*\n\x06launch\x18S \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x38\n\x12launch_config_path\x18T \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12:\n\x14log_symlink_internal\x18W \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x36\n\x10log_symlink_user\x18X \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x08log_user\x18Y \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x33\n\rlogin_timeout\x18Z \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12*\n\x04mode\x18\\ \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x33\n\rnotebook_name\x18] \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x31\n\x0bproject_url\x18\x62 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12)\n\x05quiet\x18\x63 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12+\n\x07relogin\x18\x65 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x32\n\x0cresume_fname\x18g \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12+\n\x07resumed\x18h \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\trun_group\x18j \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0crun_job_type\x18l \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x08run_mode\x18m \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x08run_name\x18n \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\trun_notes\x18o \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x31\n\x08run_tags\x18p \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12\x35\n\x11sagemaker_disable\x18r \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x35\n\x0fsettings_system\x18t \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x38\n\x12settings_workspace\x18u \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x0bshow_colors\x18v \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12.\n\nshow_emoji\x18w \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\x0bshow_errors\x18x \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12-\n\tshow_info\x18y \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x31\n\rshow_warnings\x18z \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12*\n\x06silent\x18{ \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x32\n\x0cstart_method\x18| \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12*\n\x06strict\x18} \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x33\n\x0esummary_errors\x18~ \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x34\n\x0fsummary_timeout\x18\x7f \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x36\n\x10summary_warnings\x18\x80\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12/\n\x08sweep_id\x18\x81\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x37\n\x10sweep_param_path\x18\x82\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x07symlink\x18\x84\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\x08sync_dir\x18\x85\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12:\n\x13sync_symlink_latest\x18\x87\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12J\n%table_raise_on_max_row_limit_exceeded\x18\x8a\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\x08timespec\x18\x8b\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x07tmp_dir\x18\x8c\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x30\n\twandb_dir\x18\x8e\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0ex_jupyter_name\x18\x8f\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0ex_jupyter_path\x18\x90\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x08job_name\x18\x91\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValueJ\x04\x08\x03\x10\x04J\x04\x08\x06\x10\x07J\x04\x08\x08\x10\tJ\x04\x08\t\x10\nJ\x04\x08\x0c\x10\rJ\x04\x08\x13\x10\x14J\x04\x08$\x10%J\x04\x08+\x10,J\x04\x08,\x10-J\x04\x08-\x10.J\x04\x08\x32\x10\x33J\x04\x08\x33\x10\x34J\x04\x08\x46\x10GJ\x04\x08[\x10\\J\x04\x08^\x10_J\x04\x08\x64\x10\x65J\x06\x08\x88\x01\x10\x89\x01J\x06\x08\x89\x01\x10\x8a\x01J\x06\x08\xad\x01\x10\xae\x01J\x06\x08\xb0\x01\x10\xb1\x01J\x06\x08\xb4\x01\x10\xb5\x01\x42\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_settings_pb2', globals())
+if _descriptor._USE_C_DESCRIPTORS == False:
+
+ DESCRIPTOR._options = None
+ DESCRIPTOR._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _MAPSTRINGKEYSTRINGVALUE_VALUEENTRY._options = None
+ _MAPSTRINGKEYSTRINGVALUE_VALUEENTRY._serialized_options = b'8\001'
+ _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY._options = None
+ _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY._serialized_options = b'8\001'
+ _LISTSTRINGVALUE._serialized_start=84
+ _LISTSTRINGVALUE._serialized_end=116
+ _LISTINTVALUE._serialized_start=118
+ _LISTINTVALUE._serialized_end=147
+ _MAPSTRINGKEYSTRINGVALUE._serialized_start=150
+ _MAPSTRINGKEYSTRINGVALUE._serialized_end=288
+ _MAPSTRINGKEYSTRINGVALUE_VALUEENTRY._serialized_start=244
+ _MAPSTRINGKEYSTRINGVALUE_VALUEENTRY._serialized_end=288
+ _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE._serialized_start=291
+ _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE._serialized_end=494
+ _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY._serialized_start=409
+ _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY._serialized_end=494
+ _OPENMETRICSFILTERS._serialized_start=497
+ _OPENMETRICSFILTERS._serialized_end=651
+ _RUNMOMENT._serialized_start=653
+ _RUNMOMENT._serialized_end=708
+ _SETTINGS._serialized_start=711
+ _SETTINGS._serialized_end=10633
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/wandb_sync_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/wandb_sync_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc2780bbe9c79d80aa0ce7331cc4999735543c1e
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/wandb_sync_pb2.py
@@ -0,0 +1,42 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: wandb/proto/wandb_sync.proto
+"""Generated protocol buffer code."""
+from google.protobuf.internal import builder as _builder
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from wandb.proto import wandb_internal_pb2 as wandb_dot_proto_dot_wandb__internal__pb2
+from wandb.proto import wandb_settings_pb2 as wandb_dot_proto_dot_wandb__settings__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1cwandb/proto/wandb_sync.proto\x12\x0ewandb_internal\x1a wandb/proto/wandb_internal.proto\x1a wandb/proto/wandb_settings.proto\"Q\n\x15ServerInitSyncRequest\x12\x0c\n\x04path\x18\x01 \x03(\t\x12*\n\x08settings\x18\x02 \x01(\x0b\x32\x18.wandb_internal.Settings\"$\n\x16ServerInitSyncResponse\x12\n\n\x02id\x18\x01 \x01(\t\"4\n\x11ServerSyncRequest\x12\n\n\x02id\x18\x01 \x01(\t\x12\x13\n\x0bparallelism\x18\x02 \x01(\r\"I\n\x12ServerSyncResponse\x12\x33\n\x08messages\x18\x01 \x03(\x0b\x32!.wandb_internal.ServerSyncMessage\"%\n\x17ServerSyncStatusRequest\x12\n\n\x02id\x18\x01 \x01(\t\"\x82\x01\n\x18ServerSyncStatusResponse\x12-\n\x05stats\x18\x01 \x01(\x0b\x32\x1e.wandb_internal.OperationStats\x12\x37\n\x0cnew_messages\x18\x02 \x03(\x0b\x32!.wandb_internal.ServerSyncMessage\"\xaa\x01\n\x11ServerSyncMessage\x12<\n\x08severity\x18\x01 \x01(\x0e\x32*.wandb_internal.ServerSyncMessage.Severity\x12\x0f\n\x07\x63ontent\x18\x02 \x01(\t\"F\n\x08Severity\x12\x13\n\x0fSEVERITY_NOTSET\x10\x00\x12\x11\n\rSEVERITY_INFO\x10\x14\x12\x12\n\x0eSEVERITY_ERROR\x10(B\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_sync_pb2', globals())
+if _descriptor._USE_C_DESCRIPTORS == False:
+
+ DESCRIPTOR._options = None
+ DESCRIPTOR._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _SERVERINITSYNCREQUEST._serialized_start=116
+ _SERVERINITSYNCREQUEST._serialized_end=197
+ _SERVERINITSYNCRESPONSE._serialized_start=199
+ _SERVERINITSYNCRESPONSE._serialized_end=235
+ _SERVERSYNCREQUEST._serialized_start=237
+ _SERVERSYNCREQUEST._serialized_end=289
+ _SERVERSYNCRESPONSE._serialized_start=291
+ _SERVERSYNCRESPONSE._serialized_end=364
+ _SERVERSYNCSTATUSREQUEST._serialized_start=366
+ _SERVERSYNCSTATUSREQUEST._serialized_end=403
+ _SERVERSYNCSTATUSRESPONSE._serialized_start=406
+ _SERVERSYNCSTATUSRESPONSE._serialized_end=536
+ _SERVERSYNCMESSAGE._serialized_start=539
+ _SERVERSYNCMESSAGE._serialized_end=709
+ _SERVERSYNCMESSAGE_SEVERITY._serialized_start=639
+ _SERVERSYNCMESSAGE_SEVERITY._serialized_end=709
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/wandb_telemetry_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/wandb_telemetry_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..c576038791b86734cccde81d88853ac30d3dcc50
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v4/wandb_telemetry_pb2.py
@@ -0,0 +1,41 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: wandb/proto/wandb_telemetry.proto
+"""Generated protocol buffer code."""
+from google.protobuf.internal import builder as _builder
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n!wandb/proto/wandb_telemetry.proto\x12\x0ewandb_internal\x1a\x1cwandb/proto/wandb_base.proto\"\xdb\x03\n\x0fTelemetryRecord\x12-\n\x0cimports_init\x18\x01 \x01(\x0b\x32\x17.wandb_internal.Imports\x12/\n\x0eimports_finish\x18\x02 \x01(\x0b\x32\x17.wandb_internal.Imports\x12(\n\x07\x66\x65\x61ture\x18\x03 \x01(\x0b\x32\x17.wandb_internal.Feature\x12\x16\n\x0epython_version\x18\x04 \x01(\t\x12\x13\n\x0b\x63li_version\x18\x05 \x01(\t\x12\x1b\n\x13huggingface_version\x18\x06 \x01(\t\x12 \n\x03\x65nv\x18\x08 \x01(\x0b\x32\x13.wandb_internal.Env\x12%\n\x05label\x18\t \x01(\x0b\x32\x16.wandb_internal.Labels\x12.\n\ndeprecated\x18\n \x01(\x0b\x32\x1a.wandb_internal.Deprecated\x12&\n\x06issues\x18\x0b \x01(\x0b\x32\x16.wandb_internal.Issues\x12\x14\n\x0c\x63ore_version\x18\x0c \x01(\t\x12\x10\n\x08platform\x18\r \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x11\n\x0fTelemetryResult\"\xa8\x0e\n\x07Imports\x12\r\n\x05torch\x18\x01 \x01(\x08\x12\r\n\x05keras\x18\x02 \x01(\x08\x12\x12\n\ntensorflow\x18\x03 \x01(\x08\x12\x0e\n\x06\x66\x61stai\x18\x04 \x01(\x08\x12\x0f\n\x07sklearn\x18\x05 \x01(\x08\x12\x0f\n\x07xgboost\x18\x06 \x01(\x08\x12\x10\n\x08\x63\x61tboost\x18\x07 \x01(\x08\x12\x10\n\x08lightgbm\x18\x08 \x01(\x08\x12\x19\n\x11pytorch_lightning\x18\t \x01(\x08\x12\x0e\n\x06ignite\x18\n \x01(\x08\x12\x14\n\x0ctransformers\x18\x0b \x01(\x08\x12\x0b\n\x03jax\x18\x0c \x01(\x08\x12\x10\n\x08metaflow\x18\r \x01(\x08\x12\x10\n\x08\x61llennlp\x18\x0e \x01(\x08\x12\x11\n\tautogluon\x18\x0f \x01(\x08\x12\x11\n\tautokeras\x18\x10 \x01(\x08\x12\x10\n\x08\x63\x61talyst\x18\x12 \x01(\x08\x12\x10\n\x08\x64\x65\x65pchem\x18\x15 \x01(\x08\x12\x0f\n\x07\x64\x65\x65pctr\x18\x16 \x01(\x08\x12\x0f\n\x07pycaret\x18\x1c \x01(\x08\x12\x14\n\x0cpytorchvideo\x18\x1d \x01(\x08\x12\x0b\n\x03ray\x18\x1e \x01(\x08\x12\x1a\n\x12simpletransformers\x18\x1f \x01(\x08\x12\x0e\n\x06skorch\x18 \x01(\x08\x12\r\n\x05spacy\x18! \x01(\x08\x12\r\n\x05\x66lash\x18\" \x01(\x08\x12\x0e\n\x06optuna\x18# \x01(\x08\x12\x0f\n\x07recbole\x18$ \x01(\x08\x12\x0c\n\x04mmcv\x18% \x01(\x08\x12\r\n\x05mmdet\x18& \x01(\x08\x12\x11\n\ttorchdrug\x18\' \x01(\x08\x12\x11\n\ttorchtext\x18( \x01(\x08\x12\x13\n\x0btorchvision\x18) \x01(\x08\x12\r\n\x05\x65legy\x18* \x01(\x08\x12\x12\n\ndetectron2\x18+ \x01(\x08\x12\r\n\x05\x66lair\x18, \x01(\x08\x12\x0c\n\x04\x66lax\x18- \x01(\x08\x12\x0c\n\x04syft\x18. \x01(\x08\x12\x0b\n\x03TTS\x18/ \x01(\x08\x12\r\n\x05monai\x18\x30 \x01(\x08\x12\x17\n\x0fhuggingface_hub\x18\x31 \x01(\x08\x12\r\n\x05hydra\x18\x32 \x01(\x08\x12\x10\n\x08\x64\x61tasets\x18\x33 \x01(\x08\x12\x0e\n\x06sacred\x18\x34 \x01(\x08\x12\x0e\n\x06joblib\x18\x35 \x01(\x08\x12\x0c\n\x04\x64\x61sk\x18\x36 \x01(\x08\x12\x11\n\tpaddleocr\x18\x38 \x01(\x08\x12\r\n\x05ppdet\x18\x39 \x01(\x08\x12\x11\n\tpaddleseg\x18: \x01(\x08\x12\x11\n\tpaddlenlp\x18; \x01(\x08\x12\r\n\x05mmseg\x18< \x01(\x08\x12\r\n\x05mmocr\x18= \x01(\x08\x12\r\n\x05mmcls\x18> \x01(\x08\x12\x0c\n\x04timm\x18? \x01(\x08\x12\x0f\n\x07\x66\x61irseq\x18@ \x01(\x08\x12\x12\n\ndeepchecks\x18\x41 \x01(\x08\x12\x10\n\x08\x63omposer\x18\x42 \x01(\x08\x12\x10\n\x08sparseml\x18\x43 \x01(\x08\x12\x10\n\x08\x61nomalib\x18\x44 \x01(\x08\x12\r\n\x05zenml\x18\x45 \x01(\x08\x12\x12\n\ncolossalai\x18\x46 \x01(\x08\x12\x12\n\naccelerate\x18G \x01(\x08\x12\x0e\n\x06merlin\x18H \x01(\x08\x12\x0f\n\x07nanodet\x18I \x01(\x08\x12#\n\x1bsegmentation_models_pytorch\x18J \x01(\x08\x12\x1d\n\x15sentence_transformers\x18K \x01(\x08\x12\x0b\n\x03\x64gl\x18L \x01(\x08\x12\x17\n\x0ftorch_geometric\x18M \x01(\x08\x12\x0c\n\x04jina\x18N \x01(\x08\x12\x0e\n\x06kornia\x18O \x01(\x08\x12\x16\n\x0e\x61lbumentations\x18P \x01(\x08\x12\x10\n\x08keras_cv\x18Q \x01(\x08\x12\x10\n\x08mmengine\x18R \x01(\x08\x12\x11\n\tdiffusers\x18S \x01(\x08\x12\x0b\n\x03trl\x18T \x01(\x08\x12\x0c\n\x04trlx\x18U \x01(\x08\x12\x11\n\tlangchain\x18V \x01(\x08\x12\x13\n\x0bllama_index\x18W \x01(\x08\x12\x15\n\rstability_sdk\x18X \x01(\x08\x12\x0f\n\x07prefect\x18Y \x01(\x08\x12\x13\n\x0bprefect_ray\x18Z \x01(\x08\x12\x10\n\x08pinecone\x18[ \x01(\x08\x12\x10\n\x08\x63hromadb\x18\\ \x01(\x08\x12\x10\n\x08weaviate\x18] \x01(\x08\x12\x13\n\x0bpromptlayer\x18^ \x01(\x08\x12\x0e\n\x06openai\x18_ \x01(\x08\x12\x0e\n\x06\x63ohere\x18` \x01(\x08\x12\x11\n\tanthropic\x18\x61 \x01(\x08\x12\x0c\n\x04peft\x18\x62 \x01(\x08\x12\x0f\n\x07optimum\x18\x63 \x01(\x08\x12\x10\n\x08\x65valuate\x18\x64 \x01(\x08\x12\x10\n\x08langflow\x18\x65 \x01(\x08\x12\x12\n\nkeras_core\x18\x66 \x01(\x08\x12\x18\n\x10lightning_fabric\x18g \x01(\x08\x12\x1c\n\x14\x63urated_transformers\x18h \x01(\x08\x12\x0e\n\x06orjson\x18i \x01(\x08\x12\x11\n\tlightning\x18j \x01(\x08\x12\x0c\n\x04\x64spy\x18k \x01(\x08J\x04\x08\x11\x10\x12J\x04\x08\x13\x10\x14J\x04\x08\x14\x10\x15J\x04\x08\x17\x10\x18J\x04\x08\x18\x10\x19J\x04\x08\x19\x10\x1aJ\x04\x08\x1a\x10\x1bJ\x04\x08\x1b\x10\x1cJ\x04\x08\x37\x10\x38\"\xac\r\n\x07\x46\x65\x61ture\x12\r\n\x05watch\x18\x01 \x01(\x08\x12\x0e\n\x06\x66inish\x18\x02 \x01(\x08\x12\x0c\n\x04save\x18\x03 \x01(\x08\x12\x0f\n\x07offline\x18\x04 \x01(\x08\x12\x0f\n\x07resumed\x18\x05 \x01(\x08\x12\x0c\n\x04grpc\x18\x06 \x01(\x08\x12\x0e\n\x06metric\x18\x07 \x01(\x08\x12\r\n\x05keras\x18\x08 \x01(\x08\x12\x11\n\tsagemaker\x18\t \x01(\x08\x12\x1c\n\x14\x61rtifact_incremental\x18\n \x01(\x08\x12\x10\n\x08metaflow\x18\x0b \x01(\x08\x12\x0f\n\x07prodigy\x18\x0c \x01(\x08\x12\x15\n\rset_init_name\x18\r \x01(\x08\x12\x13\n\x0bset_init_id\x18\x0e \x01(\x08\x12\x15\n\rset_init_tags\x18\x0f \x01(\x08\x12\x17\n\x0fset_init_config\x18\x10 \x01(\x08\x12\x14\n\x0cset_run_name\x18\x11 \x01(\x08\x12\x14\n\x0cset_run_tags\x18\x12 \x01(\x08\x12\x17\n\x0fset_config_item\x18\x13 \x01(\x08\x12\x0e\n\x06launch\x18\x14 \x01(\x08\x12\x1c\n\x14torch_profiler_trace\x18\x15 \x01(\x08\x12\x0b\n\x03sb3\x18\x16 \x01(\x08\x12\x17\n\x0finit_return_run\x18\x18 \x01(\x08\x12\x1f\n\x17lightgbm_wandb_callback\x18\x19 \x01(\x08\x12\x1c\n\x14lightgbm_log_summary\x18\x1a \x01(\x08\x12\x1f\n\x17\x63\x61tboost_wandb_callback\x18\x1b \x01(\x08\x12\x1c\n\x14\x63\x61tboost_log_summary\x18\x1c \x01(\x08\x12\x17\n\x0ftensorboard_log\x18\x1d \x01(\x08\x12\x16\n\x0e\x65stimator_hook\x18\x1e \x01(\x08\x12\x1e\n\x16xgboost_wandb_callback\x18\x1f \x01(\x08\x12\"\n\x1axgboost_old_wandb_callback\x18 \x01(\x08\x12\x0e\n\x06\x61ttach\x18! \x01(\x08\x12\x19\n\x11tensorboard_patch\x18\" \x01(\x08\x12\x18\n\x10tensorboard_sync\x18# \x01(\x08\x12\x15\n\rkfp_wandb_log\x18$ \x01(\x08\x12\x1b\n\x13maybe_run_overwrite\x18% \x01(\x08\x12\x1c\n\x14keras_metrics_logger\x18& \x01(\x08\x12\x1e\n\x16keras_model_checkpoint\x18\' \x01(\x08\x12!\n\x19keras_wandb_eval_callback\x18( \x01(\x08\x12\x1d\n\x15\x66low_control_overflow\x18) \x01(\x08\x12\x0c\n\x04sync\x18* \x01(\x08\x12\x1d\n\x15\x66low_control_disabled\x18+ \x01(\x08\x12\x1b\n\x13\x66low_control_custom\x18, \x01(\x08\x12\x14\n\x0copen_metrics\x18. \x01(\x08\x12\x1a\n\x12ultralytics_yolov8\x18/ \x01(\x08\x12\x17\n\x0fimporter_mlflow\x18\x30 \x01(\x08\x12\x15\n\rsync_tfevents\x18\x31 \x01(\x08\x12\x15\n\rasync_uploads\x18\x32 \x01(\x08\x12\x16\n\x0eopenai_autolog\x18\x33 \x01(\x08\x12\x18\n\x10langchain_tracer\x18\x34 \x01(\x08\x12\x16\n\x0e\x63ohere_autolog\x18\x35 \x01(\x08\x12\x1b\n\x13hf_pipeline_autolog\x18\x36 \x01(\x08\x12\r\n\x05lib_c\x18\x38 \x01(\x08\x12\x0f\n\x07lib_cpp\x18\x39 \x01(\x08\x12\x19\n\x11openai_finetuning\x18: \x01(\x08\x12\x19\n\x11\x64iffusers_autolog\x18; \x01(\x08\x12\x1f\n\x17lightning_fabric_logger\x18< \x01(\x08\x12\x14\n\x0cset_step_log\x18= \x01(\x08\x12\x13\n\x0bset_summary\x18> \x01(\x08\x12\x16\n\x0emetric_summary\x18? \x01(\x08\x12\x13\n\x0bmetric_goal\x18@ \x01(\x08\x12\x15\n\rmetric_hidden\x18\x41 \x01(\x08\x12\x18\n\x10metric_step_sync\x18\x42 \x01(\x08\x12\x13\n\x0bshared_mode\x18\x43 \x01(\x08\x12#\n\x1bserver_side_derived_summary\x18\x44 \x01(\x08\x12\x1b\n\x13user_provided_label\x18\x45 \x01(\x08\x12\x1e\n\x16\x64\x63gm_profiling_enabled\x18\x46 \x01(\x08\x12\x11\n\tfork_mode\x18G \x01(\x08\x12\x13\n\x0brewind_mode\x18H \x01(\x08\x12\x15\n\rdspy_callback\x18I \x01(\x08J\x04\x08\x17\x10\x18J\x04\x08-\x10.J\x04\x08\x37\x10\x38\"\xc9\x01\n\x03\x45nv\x12\x0f\n\x07jupyter\x18\x01 \x01(\x08\x12\x0e\n\x06kaggle\x18\x02 \x01(\x08\x12\x0f\n\x07windows\x18\x03 \x01(\x08\x12\x0e\n\x06m1_gpu\x18\x04 \x01(\x08\x12\x10\n\x08trainium\x18\n \x01(\x08\x12\x0b\n\x03pex\x18\x0b \x01(\x08\x12\r\n\x05\x63olab\x18\x0c \x01(\x08\x12\x0f\n\x07ipython\x18\r \x01(\x08\x12\x12\n\naws_lambda\x18\x0e \x01(\x08\x12\x0f\n\x07\x61md_gpu\x18\x0f \x01(\x08J\x04\x08\x05\x10\x06J\x04\x08\x06\x10\x07J\x04\x08\x07\x10\x08J\x04\x08\x08\x10\tJ\x04\x08\t\x10\n\"H\n\x06Labels\x12\x13\n\x0b\x63ode_string\x18\x01 \x01(\t\x12\x13\n\x0brepo_string\x18\x02 \x01(\t\x12\x14\n\x0c\x63ode_version\x18\x03 \x01(\t\"\xc2\x06\n\nDeprecated\x12!\n\x19keras_callback__data_type\x18\x01 \x01(\x08\x12\r\n\x05plots\x18\x05 \x01(\x08\x12!\n\x19init__config_include_keys\x18\x07 \x01(\x08\x12!\n\x19init__config_exclude_keys\x18\x08 \x01(\x08\x12\"\n\x1akeras_callback__save_model\x18\t \x01(\x08\x12\x18\n\x10langchain_tracer\x18\n \x01(\x08\x12\x1a\n\x12\x61rtifact__get_path\x18\x0b \x01(\x08\x12#\n\x1b\x61rtifactmanifestentry__name\x18\x0c \x01(\x08\x12\x1e\n\x16\x61pi__artifact_versions\x18\r \x01(\x08\x12(\n artifact_collection__change_type\x18\x0e \x01(\x08\x12\x1f\n\x17run__define_metric_copy\x18\x0f \x01(\x08\x12\x14\n\x0crun_disabled\x18\x10 \x01(\x08\x12\x16\n\x0ekeras_callback\x18\x11 \x01(\x08\x12$\n\x1crun__define_metric_best_goal\x18\x12 \x01(\x08\x12\x19\n\x11run__finish_quiet\x18\x13 \x01(\x08\x12\x18\n\x10run__reinit_bool\x18\x14 \x01(\x08\x12\x14\n\x0crun__get_url\x18\x15 \x01(\x08\x12\x19\n\x11run__project_name\x18\x16 \x01(\x08\x12\x1c\n\x14run__get_project_url\x18\x17 \x01(\x08\x12\x1a\n\x12run__get_sweep_url\x18\x18 \x01(\x08\x12 \n\x18run__use_artifact_use_as\x18\x19 \x01(\x08\x12\x18\n\x10\x61rtifact__use_as\x18\x1a \x01(\x08\x12\x1d\n\x15\x61rtifact__init_use_as\x18\x1b \x01(\x08\x12\"\n\x1a\x62\x65ta__workflows__log_model\x18\x1c \x01(\x08\x12\"\n\x1a\x62\x65ta__workflows__use_model\x18\x1d \x01(\x08\x12#\n\x1b\x62\x65ta__workflows__link_model\x18\x1e \x01(\x08J\x04\x08\x02\x10\x03J\x04\x08\x03\x10\x04J\x04\x08\x04\x10\x05J\x04\x08\x06\x10\x07\"|\n\x06Issues\x12%\n\x1dsettings__validation_warnings\x18\x01 \x01(\x08\x12!\n\x19settings__unexpected_args\x18\x02 \x01(\x08\x12(\n settings__preprocessing_warnings\x18\x03 \x01(\x08\x42\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_telemetry_pb2', globals())
+if _descriptor._USE_C_DESCRIPTORS == False:
+
+ DESCRIPTOR._options = None
+ DESCRIPTOR._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _TELEMETRYRECORD._serialized_start=84
+ _TELEMETRYRECORD._serialized_end=559
+ _TELEMETRYRESULT._serialized_start=561
+ _TELEMETRYRESULT._serialized_end=578
+ _IMPORTS._serialized_start=581
+ _IMPORTS._serialized_end=2413
+ _FEATURE._serialized_start=2416
+ _FEATURE._serialized_end=4124
+ _ENV._serialized_start=4127
+ _ENV._serialized_end=4328
+ _LABELS._serialized_start=4330
+ _LABELS._serialized_end=4402
+ _DEPRECATED._serialized_start=4405
+ _DEPRECATED._serialized_end=5239
+ _ISSUES._serialized_start=5241
+ _ISSUES._serialized_end=5365
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v5/wandb_api_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v5/wandb_api_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..269ab6c5ec9007f67759d61935e076cc813f3ccf
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v5/wandb_api_pb2.py
@@ -0,0 +1,38 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: wandb/proto/wandb_api.proto
+# Protobuf Python Version: 5.26.1
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1bwandb/proto/wandb_api.proto\x12\x0ewandb_internal\x1a\x1cwandb/proto/wandb_base.proto\"]\n\nApiRequest\x12\x44\n\x10read_run_history\x18\x01 \x01(\x0b\x32(.wandb_internal.ReadRunHistoryApiRequestH\x00\x42\t\n\x07request\"`\n\x0b\x41piResponse\x12\x45\n\x10read_run_history\x18\x01 \x01(\x0b\x32).wandb_internal.ReadRunHistoryApiResponseH\x00\x42\n\n\x08response\"\xaa\x01\n\x18ReadRunHistoryApiRequest\x12\x0e\n\x06\x65ntity\x18\x01 \x01(\t\x12\x0f\n\x07project\x18\x02 \x01(\t\x12\x0e\n\x06run_id\x18\x03 \x01(\t\x12\x0c\n\x04keys\x18\x04 \x03(\t\x12\x10\n\x08min_step\x18\x05 \x01(\x03\x12\x10\n\x08max_step\x18\x06 \x01(\x03\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"d\n\x19ReadRunHistoryApiResponse\x12\x30\n\x0chistory_rows\x18\x01 \x03(\x0b\x32\x1a.wandb_internal.HistoryRow\x12\x15\n\rerror_message\x18\x02 \x01(\t\"G\n\nHistoryRow\x12\x39\n\rhistory_items\x18\x01 \x03(\x0b\x32\".wandb_internal.ParquetHistoryItem\"5\n\x12ParquetHistoryItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\tB\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_api_pb2', _globals)
+if not _descriptor._USE_C_DESCRIPTORS:
+ _globals['DESCRIPTOR']._loaded_options = None
+ _globals['DESCRIPTOR']._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _globals['_APIREQUEST']._serialized_start=77
+ _globals['_APIREQUEST']._serialized_end=170
+ _globals['_APIRESPONSE']._serialized_start=172
+ _globals['_APIRESPONSE']._serialized_end=268
+ _globals['_READRUNHISTORYAPIREQUEST']._serialized_start=271
+ _globals['_READRUNHISTORYAPIREQUEST']._serialized_end=441
+ _globals['_READRUNHISTORYAPIRESPONSE']._serialized_start=443
+ _globals['_READRUNHISTORYAPIRESPONSE']._serialized_end=543
+ _globals['_HISTORYROW']._serialized_start=545
+ _globals['_HISTORYROW']._serialized_end=616
+ _globals['_PARQUETHISTORYITEM']._serialized_start=618
+ _globals['_PARQUETHISTORYITEM']._serialized_end=671
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v5/wandb_base_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v5/wandb_base_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..d02477cff9f03584418a3a316e8cae7db7048f91
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v5/wandb_base_pb2.py
@@ -0,0 +1,31 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: wandb/proto/wandb_base.proto
+# Protobuf Python Version: 5.26.1
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1cwandb/proto/wandb_base.proto\x12\x0ewandb_internal\"6\n\x0b_RecordInfo\x12\x11\n\tstream_id\x18\x01 \x01(\t\x12\x14\n\x0c_tracelog_id\x18\x64 \x01(\t\"!\n\x0c_RequestInfo\x12\x11\n\tstream_id\x18\x01 \x01(\t\"#\n\x0b_ResultInfo\x12\x14\n\x0c_tracelog_id\x18\x64 \x01(\tB\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_base_pb2', _globals)
+if not _descriptor._USE_C_DESCRIPTORS:
+ _globals['DESCRIPTOR']._loaded_options = None
+ _globals['DESCRIPTOR']._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _globals['__RECORDINFO']._serialized_start=48
+ _globals['__RECORDINFO']._serialized_end=102
+ _globals['__REQUESTINFO']._serialized_start=104
+ _globals['__REQUESTINFO']._serialized_end=137
+ _globals['__RESULTINFO']._serialized_start=139
+ _globals['__RESULTINFO']._serialized_end=174
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v5/wandb_internal_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v5/wandb_internal_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..3890b23aa4d3ab4ea8421f0983c249c18b857939
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v5/wandb_internal_pb2.py
@@ -0,0 +1,386 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: wandb/proto/wandb_internal.proto
+# Protobuf Python Version: 5.26.1
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
+from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
+from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2
+from wandb.proto import wandb_telemetry_pb2 as wandb_dot_proto_dot_wandb__telemetry__pb2
+from wandb.proto import wandb_api_pb2 as wandb_dot_proto_dot_wandb__api__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n wandb/proto/wandb_internal.proto\x12\x0ewandb_internal\x1a\x1bgoogle/protobuf/empty.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1cwandb/proto/wandb_base.proto\x1a!wandb/proto/wandb_telemetry.proto\x1a\x1bwandb/proto/wandb_api.proto\"\x82\n\n\x06Record\x12\x0b\n\x03num\x18\x01 \x01(\x03\x12\x30\n\x07history\x18\x02 \x01(\x0b\x32\x1d.wandb_internal.HistoryRecordH\x00\x12\x30\n\x07summary\x18\x03 \x01(\x0b\x32\x1d.wandb_internal.SummaryRecordH\x00\x12.\n\x06output\x18\x04 \x01(\x0b\x32\x1c.wandb_internal.OutputRecordH\x00\x12.\n\x06\x63onfig\x18\x05 \x01(\x0b\x32\x1c.wandb_internal.ConfigRecordH\x00\x12,\n\x05\x66iles\x18\x06 \x01(\x0b\x32\x1b.wandb_internal.FilesRecordH\x00\x12,\n\x05stats\x18\x07 \x01(\x0b\x32\x1b.wandb_internal.StatsRecordH\x00\x12\x32\n\x08\x61rtifact\x18\x08 \x01(\x0b\x32\x1e.wandb_internal.ArtifactRecordH\x00\x12,\n\x08tbrecord\x18\t \x01(\x0b\x32\x18.wandb_internal.TBRecordH\x00\x12,\n\x05\x61lert\x18\n \x01(\x0b\x32\x1b.wandb_internal.AlertRecordH\x00\x12\x34\n\ttelemetry\x18\x0b \x01(\x0b\x32\x1f.wandb_internal.TelemetryRecordH\x00\x12.\n\x06metric\x18\x0c \x01(\x0b\x32\x1c.wandb_internal.MetricRecordH\x00\x12\x35\n\noutput_raw\x18\r \x01(\x0b\x32\x1f.wandb_internal.OutputRawRecordH\x00\x12(\n\x03run\x18\x11 \x01(\x0b\x32\x19.wandb_internal.RunRecordH\x00\x12-\n\x04\x65xit\x18\x12 \x01(\x0b\x32\x1d.wandb_internal.RunExitRecordH\x00\x12,\n\x05\x66inal\x18\x14 \x01(\x0b\x32\x1b.wandb_internal.FinalRecordH\x00\x12.\n\x06header\x18\x15 \x01(\x0b\x32\x1c.wandb_internal.HeaderRecordH\x00\x12.\n\x06\x66ooter\x18\x16 \x01(\x0b\x32\x1c.wandb_internal.FooterRecordH\x00\x12\x39\n\npreempting\x18\x17 \x01(\x0b\x32#.wandb_internal.RunPreemptingRecordH\x00\x12\x34\n\x12noop_link_artifact\x18\x18 \x01(\x0b\x32\x16.google.protobuf.EmptyH\x00\x12\x39\n\x0cuse_artifact\x18\x19 \x01(\x0b\x32!.wandb_internal.UseArtifactRecordH\x00\x12\x38\n\x0b\x65nvironment\x18\x1a \x01(\x0b\x32!.wandb_internal.EnvironmentRecordH\x00\x12*\n\x07request\x18\x64 \x01(\x0b\x32\x17.wandb_internal.RequestH\x00\x12\x31\n\x0b\x61pi_request\x18\x65 \x01(\x0b\x32\x1a.wandb_internal.ApiRequestH\x00\x12(\n\x07\x63ontrol\x18\x10 \x01(\x0b\x32\x17.wandb_internal.Control\x12\x0c\n\x04uuid\x18\x13 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfoB\r\n\x0brecord_type\"\xa8\x01\n\x07\x43ontrol\x12\x10\n\x08req_resp\x18\x01 \x01(\x08\x12\r\n\x05local\x18\x02 \x01(\x08\x12\x10\n\x08relay_id\x18\x03 \x01(\t\x12\x14\n\x0cmailbox_slot\x18\x04 \x01(\t\x12\x13\n\x0b\x61lways_send\x18\x05 \x01(\x08\x12\x14\n\x0c\x66low_control\x18\x06 \x01(\x08\x12\x12\n\nend_offset\x18\x07 \x01(\x03\x12\x15\n\rconnection_id\x18\x08 \x01(\t\"\xf3\x03\n\x06Result\x12\x35\n\nrun_result\x18\x11 \x01(\x0b\x32\x1f.wandb_internal.RunUpdateResultH\x00\x12\x34\n\x0b\x65xit_result\x18\x12 \x01(\x0b\x32\x1d.wandb_internal.RunExitResultH\x00\x12\x33\n\nlog_result\x18\x14 \x01(\x0b\x32\x1d.wandb_internal.HistoryResultH\x00\x12\x37\n\x0esummary_result\x18\x15 \x01(\x0b\x32\x1d.wandb_internal.SummaryResultH\x00\x12\x35\n\routput_result\x18\x16 \x01(\x0b\x32\x1c.wandb_internal.OutputResultH\x00\x12\x35\n\rconfig_result\x18\x17 \x01(\x0b\x32\x1c.wandb_internal.ConfigResultH\x00\x12,\n\x08response\x18\x64 \x01(\x0b\x32\x18.wandb_internal.ResponseH\x00\x12(\n\x07\x63ontrol\x18\x10 \x01(\x0b\x32\x17.wandb_internal.Control\x12\x0c\n\x04uuid\x18\x18 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._ResultInfoB\r\n\x0bresult_type\":\n\x0b\x46inalRecord\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"b\n\x0bVersionInfo\x12\x10\n\x08producer\x18\x01 \x01(\t\x12\x14\n\x0cmin_consumer\x18\x02 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"n\n\x0cHeaderRecord\x12\x31\n\x0cversion_info\x18\x01 \x01(\x0b\x32\x1b.wandb_internal.VersionInfo\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\";\n\x0c\x46ooterRecord\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"9\n\x0b\x42ranchPoint\x12\x0b\n\x03run\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x01\x12\x0e\n\x06metric\x18\x03 \x01(\t\"\x91\x05\n\tRunRecord\x12\x0e\n\x06run_id\x18\x01 \x01(\t\x12\x0e\n\x06\x65ntity\x18\x02 \x01(\t\x12\x0f\n\x07project\x18\x03 \x01(\t\x12,\n\x06\x63onfig\x18\x04 \x01(\x0b\x32\x1c.wandb_internal.ConfigRecord\x12.\n\x07summary\x18\x05 \x01(\x0b\x32\x1d.wandb_internal.SummaryRecord\x12\x11\n\trun_group\x18\x06 \x01(\t\x12\x10\n\x08job_type\x18\x07 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x08 \x01(\t\x12\r\n\x05notes\x18\t \x01(\t\x12\x0c\n\x04tags\x18\n \x03(\t\x12\x30\n\x08settings\x18\x0b \x01(\x0b\x32\x1e.wandb_internal.SettingsRecord\x12\x10\n\x08sweep_id\x18\x0c \x01(\t\x12\x0c\n\x04host\x18\r \x01(\t\x12\x15\n\rstarting_step\x18\x0e \x01(\x03\x12\x12\n\nstorage_id\x18\x10 \x01(\t\x12.\n\nstart_time\x18\x11 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07resumed\x18\x12 \x01(\x08\x12\x32\n\ttelemetry\x18\x13 \x01(\x0b\x32\x1f.wandb_internal.TelemetryRecord\x12\x0f\n\x07runtime\x18\x14 \x01(\x05\x12*\n\x03git\x18\x15 \x01(\x0b\x32\x1d.wandb_internal.GitRepoRecord\x12\x0e\n\x06\x66orked\x18\x16 \x01(\x08\x12\x31\n\x0c\x62ranch_point\x18\x17 \x01(\x0b\x32\x1b.wandb_internal.BranchPoint\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\";\n\rGitRepoRecord\x12\x1a\n\nremote_url\x18\x01 \x01(\tR\x06remote\x12\x0e\n\x06\x63ommit\x18\x02 \x01(\t\"c\n\x0fRunUpdateResult\x12&\n\x03run\x18\x01 \x01(\x0b\x32\x19.wandb_internal.RunRecord\x12(\n\x05\x65rror\x18\x02 \x01(\x0b\x32\x19.wandb_internal.ErrorInfo\"\xac\x01\n\tErrorInfo\x12\x0f\n\x07message\x18\x01 \x01(\t\x12\x31\n\x04\x63ode\x18\x02 \x01(\x0e\x32#.wandb_internal.ErrorInfo.ErrorCode\"[\n\tErrorCode\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x11\n\rCOMMUNICATION\x10\x01\x12\x12\n\x0e\x41UTHENTICATION\x10\x02\x12\t\n\x05USAGE\x10\x03\x12\x0f\n\x0bUNSUPPORTED\x10\x04\"`\n\rRunExitRecord\x12\x11\n\texit_code\x18\x01 \x01(\x05\x12\x0f\n\x07runtime\x18\x02 \x01(\x05\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x0f\n\rRunExitResult\"B\n\x13RunPreemptingRecord\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x15\n\x13RunPreemptingResult\"i\n\x0eSettingsRecord\x12*\n\x04item\x18\x01 \x03(\x0b\x32\x1c.wandb_internal.SettingsItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"/\n\x0cSettingsItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\x1a\n\x0bHistoryStep\x12\x0b\n\x03num\x18\x01 \x01(\x03\"\x92\x01\n\rHistoryRecord\x12)\n\x04item\x18\x01 \x03(\x0b\x32\x1b.wandb_internal.HistoryItem\x12)\n\x04step\x18\x02 \x01(\x0b\x32\x1b.wandb_internal.HistoryStep\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"B\n\x0bHistoryItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nnested_key\x18\x02 \x03(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\x0f\n\rHistoryResult\"\xdc\x01\n\x0cOutputRecord\x12<\n\x0boutput_type\x18\x01 \x01(\x0e\x32\'.wandb_internal.OutputRecord.OutputType\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0c\n\x04line\x18\x03 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"$\n\nOutputType\x12\n\n\x06STDERR\x10\x00\x12\n\n\x06STDOUT\x10\x01\"\x0e\n\x0cOutputResult\"\xe2\x01\n\x0fOutputRawRecord\x12?\n\x0boutput_type\x18\x01 \x01(\x0e\x32*.wandb_internal.OutputRawRecord.OutputType\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0c\n\x04line\x18\x03 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"$\n\nOutputType\x12\n\n\x06STDERR\x10\x00\x12\n\n\x06STDOUT\x10\x01\"\x11\n\x0fOutputRawResult\"\xb4\x03\n\x0cMetricRecord\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x11\n\tglob_name\x18\x02 \x01(\t\x12\x13\n\x0bstep_metric\x18\x04 \x01(\t\x12\x19\n\x11step_metric_index\x18\x05 \x01(\x05\x12.\n\x07options\x18\x06 \x01(\x0b\x32\x1d.wandb_internal.MetricOptions\x12.\n\x07summary\x18\x07 \x01(\x0b\x32\x1d.wandb_internal.MetricSummary\x12\x35\n\x04goal\x18\x08 \x01(\x0e\x32\'.wandb_internal.MetricRecord.MetricGoal\x12/\n\x08_control\x18\t \x01(\x0b\x32\x1d.wandb_internal.MetricControl\x12\x1a\n\x12\x65xpanded_from_glob\x18\n \x01(\x08\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"B\n\nMetricGoal\x12\x0e\n\nGOAL_UNSET\x10\x00\x12\x11\n\rGOAL_MINIMIZE\x10\x01\x12\x11\n\rGOAL_MAXIMIZE\x10\x02\"\x0e\n\x0cMetricResult\"C\n\rMetricOptions\x12\x11\n\tstep_sync\x18\x01 \x01(\x08\x12\x0e\n\x06hidden\x18\x02 \x01(\x08\x12\x0f\n\x07\x64\x65\x66ined\x18\x03 \x01(\x08\"\"\n\rMetricControl\x12\x11\n\toverwrite\x18\x01 \x01(\x08\"~\n\rMetricSummary\x12\x0b\n\x03min\x18\x01 \x01(\x08\x12\x0b\n\x03max\x18\x02 \x01(\x08\x12\x0c\n\x04mean\x18\x03 \x01(\x08\x12\x0c\n\x04\x62\x65st\x18\x04 \x01(\x08\x12\x0c\n\x04last\x18\x05 \x01(\x08\x12\x0c\n\x04none\x18\x06 \x01(\x08\x12\x0c\n\x04\x63opy\x18\x07 \x01(\x08\x12\r\n\x05\x66irst\x18\x08 \x01(\x08\"\x93\x01\n\x0c\x43onfigRecord\x12*\n\x06update\x18\x01 \x03(\x0b\x32\x1a.wandb_internal.ConfigItem\x12*\n\x06remove\x18\x02 \x03(\x0b\x32\x1a.wandb_internal.ConfigItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"A\n\nConfigItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nnested_key\x18\x02 \x03(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\x0e\n\x0c\x43onfigResult\"\x96\x01\n\rSummaryRecord\x12+\n\x06update\x18\x01 \x03(\x0b\x32\x1b.wandb_internal.SummaryItem\x12+\n\x06remove\x18\x02 \x03(\x0b\x32\x1b.wandb_internal.SummaryItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"B\n\x0bSummaryItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nnested_key\x18\x02 \x03(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\x0f\n\rSummaryResult\"d\n\x0b\x46ilesRecord\x12(\n\x05\x66iles\x18\x01 \x03(\x0b\x32\x19.wandb_internal.FilesItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\xec\x01\n\tFilesItem\x12\x0c\n\x04path\x18\x01 \x01(\t\x12\x34\n\x06policy\x18\x02 \x01(\x0e\x32$.wandb_internal.FilesItem.PolicyType\x12\x30\n\x04type\x18\x03 \x01(\x0e\x32\".wandb_internal.FilesItem.FileType\"(\n\nPolicyType\x12\x07\n\x03NOW\x10\x00\x12\x07\n\x03\x45ND\x10\x01\x12\x08\n\x04LIVE\x10\x02\"9\n\x08\x46ileType\x12\t\n\x05OTHER\x10\x00\x12\t\n\x05WANDB\x10\x01\x12\t\n\x05MEDIA\x10\x02\x12\x0c\n\x08\x41RTIFACT\x10\x03J\x04\x08\x10\x10\x11\"\r\n\x0b\x46ilesResult\"\xe6\x01\n\x0bStatsRecord\x12\x39\n\nstats_type\x18\x01 \x01(\x0e\x32%.wandb_internal.StatsRecord.StatsType\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\'\n\x04item\x18\x03 \x03(\x0b\x32\x19.wandb_internal.StatsItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x17\n\tStatsType\x12\n\n\x06SYSTEM\x10\x00\",\n\tStatsItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\xe7\x03\n\x0e\x41rtifactRecord\x12\x0e\n\x06run_id\x18\x01 \x01(\t\x12\x0f\n\x07project\x18\x02 \x01(\t\x12\x0e\n\x06\x65ntity\x18\x03 \x01(\t\x12\x0c\n\x04type\x18\x04 \x01(\t\x12\x0c\n\x04name\x18\x05 \x01(\t\x12\x0e\n\x06\x64igest\x18\x06 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x07 \x01(\t\x12\x10\n\x08metadata\x18\x08 \x01(\t\x12\x14\n\x0cuser_created\x18\t \x01(\x08\x12\x18\n\x10use_after_commit\x18\n \x01(\x08\x12\x0f\n\x07\x61liases\x18\x0b \x03(\t\x12\x32\n\x08manifest\x18\x0c \x01(\x0b\x32 .wandb_internal.ArtifactManifest\x12\x16\n\x0e\x64istributed_id\x18\r \x01(\t\x12\x10\n\x08\x66inalize\x18\x0e \x01(\x08\x12\x11\n\tclient_id\x18\x0f \x01(\t\x12\x1a\n\x12sequence_client_id\x18\x10 \x01(\t\x12\x0f\n\x07\x62\x61se_id\x18\x11 \x01(\t\x12\x1c\n\x14ttl_duration_seconds\x18\x12 \x01(\x03\x12\x0c\n\x04tags\x18\x13 \x03(\t\x12\x19\n\x11incremental_beta1\x18\x64 \x01(\x08\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\xd8\x01\n\x10\x41rtifactManifest\x12\x0f\n\x07version\x18\x01 \x01(\x05\x12\x16\n\x0estorage_policy\x18\x02 \x01(\t\x12\x46\n\x15storage_policy_config\x18\x03 \x03(\x0b\x32\'.wandb_internal.StoragePolicyConfigItem\x12\x37\n\x08\x63ontents\x18\x04 \x03(\x0b\x32%.wandb_internal.ArtifactManifestEntry\x12\x1a\n\x12manifest_file_path\x18\x05 \x01(\t\"\xcf\x01\n\x15\x41rtifactManifestEntry\x12\x0c\n\x04path\x18\x01 \x01(\t\x12\x0e\n\x06\x64igest\x18\x02 \x01(\t\x12\x0b\n\x03ref\x18\x03 \x01(\t\x12\x0c\n\x04size\x18\x04 \x01(\x03\x12\x10\n\x08mimetype\x18\x05 \x01(\t\x12\x12\n\nlocal_path\x18\x06 \x01(\t\x12\x19\n\x11\x62irth_artifact_id\x18\x07 \x01(\t\x12\x12\n\nskip_cache\x18\x08 \x01(\x08\x12(\n\x05\x65xtra\x18\x10 \x03(\x0b\x32\x19.wandb_internal.ExtraItem\",\n\tExtraItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x02 \x01(\t\":\n\x17StoragePolicyConfigItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x02 \x01(\t\"\x10\n\x0e\x41rtifactResult\"\x14\n\x12LinkArtifactResult\"\xf0\x01\n\x13LinkArtifactRequest\x12\x11\n\tclient_id\x18\x01 \x01(\t\x12\x11\n\tserver_id\x18\x02 \x01(\t\x12\x16\n\x0eportfolio_name\x18\x03 \x01(\t\x12\x18\n\x10portfolio_entity\x18\x04 \x01(\t\x12\x19\n\x11portfolio_project\x18\x05 \x01(\t\x12\x19\n\x11portfolio_aliases\x18\x06 \x03(\t\x12\x1e\n\x16portfolio_organization\x18\x07 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"[\n\x14LinkArtifactResponse\x12\x15\n\rerror_message\x18\x01 \x01(\t\x12\x1a\n\rversion_index\x18\x02 \x01(\x05H\x00\x88\x01\x01\x42\x10\n\x0e_version_index\"h\n\x08TBRecord\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\x12\x0f\n\x07log_dir\x18\x01 \x01(\t\x12\x10\n\x08root_dir\x18\x03 \x01(\t\x12\x0c\n\x04save\x18\x02 \x01(\x08\"\n\n\x08TBResult\"}\n\x0b\x41lertRecord\x12\r\n\x05title\x18\x01 \x01(\t\x12\x0c\n\x04text\x18\x02 \x01(\t\x12\r\n\x05level\x18\x03 \x01(\t\x12\x15\n\rwait_duration\x18\x04 \x01(\x03\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\r\n\x0b\x41lertResult\"\xf8\x11\n\x07Request\x12\x38\n\x0bstop_status\x18\x01 \x01(\x0b\x32!.wandb_internal.StopStatusRequestH\x00\x12>\n\x0enetwork_status\x18\x02 \x01(\x0b\x32$.wandb_internal.NetworkStatusRequestH\x00\x12-\n\x05\x64\x65\x66\x65r\x18\x03 \x01(\x0b\x32\x1c.wandb_internal.DeferRequestH\x00\x12\x38\n\x0bget_summary\x18\x04 \x01(\x0b\x32!.wandb_internal.GetSummaryRequestH\x00\x12-\n\x05login\x18\x05 \x01(\x0b\x32\x1c.wandb_internal.LoginRequestH\x00\x12-\n\x05pause\x18\x06 \x01(\x0b\x32\x1c.wandb_internal.PauseRequestH\x00\x12/\n\x06resume\x18\x07 \x01(\x0b\x32\x1d.wandb_internal.ResumeRequestH\x00\x12\x34\n\tpoll_exit\x18\x08 \x01(\x0b\x32\x1f.wandb_internal.PollExitRequestH\x00\x12@\n\x0fsampled_history\x18\t \x01(\x0b\x32%.wandb_internal.SampledHistoryRequestH\x00\x12@\n\x0fpartial_history\x18\n \x01(\x0b\x32%.wandb_internal.PartialHistoryRequestH\x00\x12\x34\n\trun_start\x18\x0b \x01(\x0b\x32\x1f.wandb_internal.RunStartRequestH\x00\x12<\n\rcheck_version\x18\x0c \x01(\x0b\x32#.wandb_internal.CheckVersionRequestH\x00\x12:\n\x0clog_artifact\x18\r \x01(\x0b\x32\".wandb_internal.LogArtifactRequestH\x00\x12\x44\n\x11\x64ownload_artifact\x18\x0e \x01(\x0b\x32\'.wandb_internal.DownloadArtifactRequestH\x00\x12\x35\n\tkeepalive\x18\x11 \x01(\x0b\x32 .wandb_internal.KeepaliveRequestH\x00\x12>\n\x0eserver_feature\x18\x12 \x01(\x0b\x32$.wandb_internal.ServerFeatureRequestH\x00\x12\x36\n\nrun_status\x18\x14 \x01(\x0b\x32 .wandb_internal.RunStatusRequestH\x00\x12/\n\x06\x63\x61ncel\x18\x15 \x01(\x0b\x32\x1d.wandb_internal.CancelRequestH\x00\x12\x44\n\x11internal_messages\x18\x17 \x01(\x0b\x32\'.wandb_internal.InternalMessagesRequestH\x00\x12@\n\x0fpython_packages\x18\x18 \x01(\x0b\x32%.wandb_internal.PythonPackagesRequestH\x00\x12\x33\n\x08shutdown\x18@ \x01(\x0b\x32\x1f.wandb_internal.ShutdownRequestH\x00\x12/\n\x06\x61ttach\x18\x41 \x01(\x0b\x32\x1d.wandb_internal.AttachRequestH\x00\x12/\n\x06status\x18\x42 \x01(\x0b\x32\x1d.wandb_internal.StatusRequestH\x00\x12\x38\n\x0bserver_info\x18\x43 \x01(\x0b\x32!.wandb_internal.ServerInfoRequestH\x00\x12\x38\n\x0bsender_mark\x18\x44 \x01(\x0b\x32!.wandb_internal.SenderMarkRequestH\x00\x12\x38\n\x0bsender_read\x18\x45 \x01(\x0b\x32!.wandb_internal.SenderReadRequestH\x00\x12<\n\rstatus_report\x18\x46 \x01(\x0b\x32#.wandb_internal.StatusReportRequestH\x00\x12>\n\x0esummary_record\x18G \x01(\x0b\x32$.wandb_internal.SummaryRecordRequestH\x00\x12\x42\n\x10telemetry_record\x18H \x01(\x0b\x32&.wandb_internal.TelemetryRecordRequestH\x00\x12\x32\n\x08job_info\x18I \x01(\x0b\x32\x1e.wandb_internal.JobInfoRequestH\x00\x12\x45\n\x12get_system_metrics\x18J \x01(\x0b\x32\'.wandb_internal.GetSystemMetricsRequestH\x00\x12\x34\n\tjob_input\x18M \x01(\x0b\x32\x1f.wandb_internal.JobInputRequestH\x00\x12<\n\rlink_artifact\x18N \x01(\x0b\x32#.wandb_internal.LinkArtifactRequestH\x00\x12N\n\x17run_finish_without_exit\x18O \x01(\x0b\x32+.wandb_internal.RunFinishWithoutExitRequestH\x00\x12\x38\n\x0bsync_finish\x18Q \x01(\x0b\x32!.wandb_internal.SyncFinishRequestH\x00\x12;\n\noperations\x18R \x01(\x0b\x32%.wandb_internal.OperationStatsRequestH\x00\x12\x43\n\x11probe_system_info\x18S \x01(\x0b\x32&.wandb_internal.ProbeSystemInfoRequestH\x00\x12\x39\n\x0btest_inject\x18\xe8\x07 \x01(\x0b\x32!.wandb_internal.TestInjectRequestH\x00\x42\x0e\n\x0crequest_typeJ\x04\x08\x16\x10\x17J\x04\x08K\x10LJ\x04\x08L\x10MJ\x04\x08P\x10Q\"\xd0\x0e\n\x08Response\x12?\n\x12keepalive_response\x18\x12 \x01(\x0b\x32!.wandb_internal.KeepaliveResponseH\x00\x12\x42\n\x14stop_status_response\x18\x13 \x01(\x0b\x32\".wandb_internal.StopStatusResponseH\x00\x12H\n\x17network_status_response\x18\x14 \x01(\x0b\x32%.wandb_internal.NetworkStatusResponseH\x00\x12\x37\n\x0elogin_response\x18\x18 \x01(\x0b\x32\x1d.wandb_internal.LoginResponseH\x00\x12\x42\n\x14get_summary_response\x18\x19 \x01(\x0b\x32\".wandb_internal.GetSummaryResponseH\x00\x12>\n\x12poll_exit_response\x18\x1a \x01(\x0b\x32 .wandb_internal.PollExitResponseH\x00\x12J\n\x18sampled_history_response\x18\x1b \x01(\x0b\x32&.wandb_internal.SampledHistoryResponseH\x00\x12>\n\x12run_start_response\x18\x1c \x01(\x0b\x32 .wandb_internal.RunStartResponseH\x00\x12\x46\n\x16\x63heck_version_response\x18\x1d \x01(\x0b\x32$.wandb_internal.CheckVersionResponseH\x00\x12\x44\n\x15log_artifact_response\x18\x1e \x01(\x0b\x32#.wandb_internal.LogArtifactResponseH\x00\x12N\n\x1a\x64ownload_artifact_response\x18\x1f \x01(\x0b\x32(.wandb_internal.DownloadArtifactResponseH\x00\x12H\n\x17server_feature_response\x18 \x01(\x0b\x32%.wandb_internal.ServerFeatureResponseH\x00\x12@\n\x13run_status_response\x18# \x01(\x0b\x32!.wandb_internal.RunStatusResponseH\x00\x12\x39\n\x0f\x63\x61ncel_response\x18$ \x01(\x0b\x32\x1e.wandb_internal.CancelResponseH\x00\x12N\n\x1ainternal_messages_response\x18% \x01(\x0b\x32(.wandb_internal.InternalMessagesResponseH\x00\x12=\n\x11shutdown_response\x18@ \x01(\x0b\x32 .wandb_internal.ShutdownResponseH\x00\x12\x39\n\x0f\x61ttach_response\x18\x41 \x01(\x0b\x32\x1e.wandb_internal.AttachResponseH\x00\x12\x39\n\x0fstatus_response\x18\x42 \x01(\x0b\x32\x1e.wandb_internal.StatusResponseH\x00\x12\x42\n\x14server_info_response\x18\x43 \x01(\x0b\x32\".wandb_internal.ServerInfoResponseH\x00\x12<\n\x11job_info_response\x18\x44 \x01(\x0b\x32\x1f.wandb_internal.JobInfoResponseH\x00\x12O\n\x1bget_system_metrics_response\x18\x45 \x01(\x0b\x32(.wandb_internal.GetSystemMetricsResponseH\x00\x12\x46\n\x16link_artifact_response\x18G \x01(\x0b\x32$.wandb_internal.LinkArtifactResponseH\x00\x12\x35\n\rsync_response\x18\x46 \x01(\x0b\x32\x1c.wandb_internal.SyncResponseH\x00\x12X\n run_finish_without_exit_response\x18H \x01(\x0b\x32,.wandb_internal.RunFinishWithoutExitResponseH\x00\x12\x45\n\x13operations_response\x18J \x01(\x0b\x32&.wandb_internal.OperationStatsResponseH\x00\x12\x33\n\x0c\x61pi_response\x18T \x01(\x0b\x32\x1b.wandb_internal.ApiResponseH\x00\x12\x43\n\x14test_inject_response\x18\xe8\x07 \x01(\x0b\x32\".wandb_internal.TestInjectResponseH\x00\x42\x0f\n\rresponse_typeJ\x04\x08I\x10J\"\xc0\x02\n\x0c\x44\x65\x66\x65rRequest\x12\x36\n\x05state\x18\x01 \x01(\x0e\x32\'.wandb_internal.DeferRequest.DeferState\"\xf7\x01\n\nDeferState\x12\t\n\x05\x42\x45GIN\x10\x00\x12\r\n\tFLUSH_RUN\x10\x01\x12\x0f\n\x0b\x46LUSH_STATS\x10\x02\x12\x19\n\x15\x46LUSH_PARTIAL_HISTORY\x10\x03\x12\x0c\n\x08\x46LUSH_TB\x10\x04\x12\r\n\tFLUSH_SUM\x10\x05\x12\x13\n\x0f\x46LUSH_DEBOUNCER\x10\x06\x12\x10\n\x0c\x46LUSH_OUTPUT\x10\x07\x12\r\n\tFLUSH_JOB\x10\x08\x12\r\n\tFLUSH_DIR\x10\t\x12\x0c\n\x08\x46LUSH_FP\x10\n\x12\x0b\n\x07JOIN_FP\x10\x0b\x12\x0c\n\x08\x46LUSH_FS\x10\x0c\x12\x0f\n\x0b\x46LUSH_FINAL\x10\r\x12\x07\n\x03\x45ND\x10\x0e\"<\n\x0cPauseRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x0f\n\rPauseResponse\"=\n\rResumeRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x10\n\x0eResumeResponse\"M\n\x0cLoginRequest\x12\x0f\n\x07\x61pi_key\x18\x01 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"&\n\rLoginResponse\x12\x15\n\ractive_entity\x18\x01 \x01(\t\"A\n\x11GetSummaryRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"?\n\x12GetSummaryResponse\x12)\n\x04item\x18\x01 \x03(\x0b\x32\x1b.wandb_internal.SummaryItem\"G\n\x17GetSystemMetricsRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"R\n\x12SystemMetricSample\x12-\n\ttimestamp\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\r\n\x05value\x18\x02 \x01(\x02\"I\n\x13SystemMetricsBuffer\x12\x32\n\x06record\x18\x01 \x03(\x0b\x32\".wandb_internal.SystemMetricSample\"\xca\x01\n\x18GetSystemMetricsResponse\x12S\n\x0esystem_metrics\x18\x01 \x03(\x0b\x32;.wandb_internal.GetSystemMetricsResponse.SystemMetricsEntry\x1aY\n\x12SystemMetricsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x32\n\x05value\x18\x02 \x01(\x0b\x32#.wandb_internal.SystemMetricsBuffer:\x02\x38\x01\"=\n\rStatusRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\")\n\x0eStatusResponse\x12\x17\n\x0frun_should_stop\x18\x01 \x01(\x08\"A\n\x11StopStatusRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"-\n\x12StopStatusResponse\x12\x17\n\x0frun_should_stop\x18\x01 \x01(\x08\"D\n\x14NetworkStatusRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"P\n\x15NetworkStatusResponse\x12\x37\n\x11network_responses\x18\x01 \x03(\x0b\x32\x1c.wandb_internal.HttpResponse\"D\n\x0cHttpResponse\x12\x18\n\x10http_status_code\x18\x01 \x01(\x05\x12\x1a\n\x12http_response_text\x18\x02 \x01(\t\"G\n\x17InternalMessagesRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"N\n\x18InternalMessagesResponse\x12\x32\n\x08messages\x18\x01 \x01(\x0b\x32 .wandb_internal.InternalMessages\"#\n\x10InternalMessages\x12\x0f\n\x07warning\x18\x01 \x03(\t\"?\n\x0fPollExitRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\xf5\x01\n\x10PollExitResponse\x12\x0c\n\x04\x64one\x18\x01 \x01(\x08\x12\x32\n\x0b\x65xit_result\x18\x02 \x01(\x0b\x32\x1d.wandb_internal.RunExitResult\x12\x35\n\x0cpusher_stats\x18\x03 \x01(\x0b\x32\x1f.wandb_internal.FilePusherStats\x12/\n\x0b\x66ile_counts\x18\x04 \x01(\x0b\x32\x1a.wandb_internal.FileCounts\x12\x37\n\x0foperation_stats\x18\x05 \x01(\x0b\x32\x1e.wandb_internal.OperationStats\"E\n\x15OperationStatsRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"Q\n\x16OperationStatsResponse\x12\x37\n\x0foperation_stats\x18\x01 \x01(\x0b\x32\x1e.wandb_internal.OperationStats\"Y\n\x0eOperationStats\x12-\n\noperations\x18\x01 \x03(\x0b\x32\x19.wandb_internal.Operation\x12\x18\n\x10total_operations\x18\x02 \x01(\x03\"\x87\x01\n\tOperation\x12\x0c\n\x04\x64\x65sc\x18\x01 \x01(\t\x12\x17\n\x0fruntime_seconds\x18\x02 \x01(\x01\x12\x10\n\x08progress\x18\x03 \x01(\t\x12\x14\n\x0c\x65rror_status\x18\x04 \x01(\t\x12+\n\x08subtasks\x18\x05 \x03(\x0b\x32\x19.wandb_internal.Operation\"\x13\n\x11SenderMarkRequest\"\x13\n\x11SyncFinishRequest\"E\n\x0cSyncResponse\x12\x0b\n\x03url\x18\x01 \x01(\t\x12(\n\x05\x65rror\x18\x02 \x01(\x0b\x32\x19.wandb_internal.ErrorInfo\"?\n\x11SenderReadRequest\x12\x14\n\x0cstart_offset\x18\x01 \x01(\x03\x12\x14\n\x0c\x66inal_offset\x18\x02 \x01(\x03\"m\n\x13StatusReportRequest\x12\x12\n\nrecord_num\x18\x01 \x01(\x03\x12\x13\n\x0bsent_offset\x18\x02 \x01(\x03\x12-\n\tsync_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"F\n\x14SummaryRecordRequest\x12.\n\x07summary\x18\x01 \x01(\x0b\x32\x1d.wandb_internal.SummaryRecord\"L\n\x16TelemetryRecordRequest\x12\x32\n\ttelemetry\x18\x01 \x01(\x0b\x32\x1f.wandb_internal.TelemetryRecord\"A\n\x11ServerInfoRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"|\n\x12ServerInfoResponse\x12-\n\nlocal_info\x18\x01 \x01(\x0b\x32\x19.wandb_internal.LocalInfo\x12\x37\n\x0fserver_messages\x18\x02 \x01(\x0b\x32\x1e.wandb_internal.ServerMessages\"=\n\x0eServerMessages\x12+\n\x04item\x18\x01 \x03(\x0b\x32\x1d.wandb_internal.ServerMessage\"e\n\rServerMessage\x12\x12\n\nplain_text\x18\x01 \x01(\t\x12\x10\n\x08utf_text\x18\x02 \x01(\t\x12\x11\n\thtml_text\x18\x03 \x01(\t\x12\x0c\n\x04type\x18\x04 \x01(\t\x12\r\n\x05level\x18\x05 \x01(\x05\"c\n\nFileCounts\x12\x13\n\x0bwandb_count\x18\x01 \x01(\x05\x12\x13\n\x0bmedia_count\x18\x02 \x01(\x05\x12\x16\n\x0e\x61rtifact_count\x18\x03 \x01(\x05\x12\x13\n\x0bother_count\x18\x04 \x01(\x05\"U\n\x0f\x46ilePusherStats\x12\x16\n\x0euploaded_bytes\x18\x01 \x01(\x03\x12\x13\n\x0btotal_bytes\x18\x02 \x01(\x03\x12\x15\n\rdeduped_bytes\x18\x03 \x01(\x03\"\x1e\n\rFilesUploaded\x12\r\n\x05\x66iles\x18\x01 \x03(\t\"\xf4\x01\n\x17\x46ileTransferInfoRequest\x12\x42\n\x04type\x18\x01 \x01(\x0e\x32\x34.wandb_internal.FileTransferInfoRequest.TransferType\x12\x0c\n\x04path\x18\x02 \x01(\t\x12\x0b\n\x03url\x18\x03 \x01(\t\x12\x0c\n\x04size\x18\x04 \x01(\x03\x12\x11\n\tprocessed\x18\x05 \x01(\x03\x12/\n\x0b\x66ile_counts\x18\x06 \x01(\x0b\x32\x1a.wandb_internal.FileCounts\"(\n\x0cTransferType\x12\n\n\x06Upload\x10\x00\x12\x0c\n\x08\x44ownload\x10\x01\"1\n\tLocalInfo\x12\x0f\n\x07version\x18\x01 \x01(\t\x12\x13\n\x0bout_of_date\x18\x02 \x01(\x08\"?\n\x0fShutdownRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x12\n\x10ShutdownResponse\"P\n\rAttachRequest\x12\x11\n\tattach_id\x18\x14 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"b\n\x0e\x41ttachResponse\x12&\n\x03run\x18\x01 \x01(\x0b\x32\x19.wandb_internal.RunRecord\x12(\n\x05\x65rror\x18\x02 \x01(\x0b\x32\x19.wandb_internal.ErrorInfo\"\xd5\x02\n\x11TestInjectRequest\x12\x13\n\x0bhandler_exc\x18\x01 \x01(\x08\x12\x14\n\x0chandler_exit\x18\x02 \x01(\x08\x12\x15\n\rhandler_abort\x18\x03 \x01(\x08\x12\x12\n\nsender_exc\x18\x04 \x01(\x08\x12\x13\n\x0bsender_exit\x18\x05 \x01(\x08\x12\x14\n\x0csender_abort\x18\x06 \x01(\x08\x12\x0f\n\x07req_exc\x18\x07 \x01(\x08\x12\x10\n\x08req_exit\x18\x08 \x01(\x08\x12\x11\n\treq_abort\x18\t \x01(\x08\x12\x10\n\x08resp_exc\x18\n \x01(\x08\x12\x11\n\tresp_exit\x18\x0b \x01(\x08\x12\x12\n\nresp_abort\x18\x0c \x01(\x08\x12\x10\n\x08msg_drop\x18\r \x01(\x08\x12\x10\n\x08msg_hang\x18\x0e \x01(\x08\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x14\n\x12TestInjectResponse\"\x1e\n\rHistoryAction\x12\r\n\x05\x66lush\x18\x01 \x01(\x08\"\xca\x01\n\x15PartialHistoryRequest\x12)\n\x04item\x18\x01 \x03(\x0b\x32\x1b.wandb_internal.HistoryItem\x12)\n\x04step\x18\x02 \x01(\x0b\x32\x1b.wandb_internal.HistoryStep\x12-\n\x06\x61\x63tion\x18\x03 \x01(\x0b\x32\x1d.wandb_internal.HistoryAction\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x18\n\x16PartialHistoryResponse\"E\n\x15SampledHistoryRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"_\n\x12SampledHistoryItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nnested_key\x18\x02 \x03(\t\x12\x14\n\x0cvalues_float\x18\x03 \x03(\x02\x12\x12\n\nvalues_int\x18\x04 \x03(\x03\"J\n\x16SampledHistoryResponse\x12\x30\n\x04item\x18\x01 \x03(\x0b\x32\".wandb_internal.SampledHistoryItem\"@\n\x10RunStatusRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"x\n\x11RunStatusResponse\x12\x18\n\x10sync_items_total\x18\x01 \x01(\x03\x12\x1a\n\x12sync_items_pending\x18\x02 \x01(\x03\x12-\n\tsync_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"g\n\x0fRunStartRequest\x12&\n\x03run\x18\x01 \x01(\x0b\x32\x19.wandb_internal.RunRecord\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x12\n\x10RunStartResponse\"K\n\x1bRunFinishWithoutExitRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x1e\n\x1cRunFinishWithoutExitResponse\"\\\n\x13\x43heckVersionRequest\x12\x17\n\x0f\x63urrent_version\x18\x01 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"]\n\x14\x43heckVersionResponse\x12\x17\n\x0fupgrade_message\x18\x01 \x01(\t\x12\x14\n\x0cyank_message\x18\x02 \x01(\t\x12\x16\n\x0e\x64\x65lete_message\x18\x03 \x01(\t\">\n\x0eJobInfoRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"6\n\x0fJobInfoResponse\x12\x12\n\nsequenceId\x18\x01 \x01(\t\x12\x0f\n\x07version\x18\x02 \x01(\t\"\x9f\x01\n\x12LogArtifactRequest\x12\x30\n\x08\x61rtifact\x18\x01 \x01(\x0b\x32\x1e.wandb_internal.ArtifactRecord\x12\x14\n\x0chistory_step\x18\x02 \x01(\x03\x12\x13\n\x0bstaging_dir\x18\x03 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"A\n\x13LogArtifactResponse\x12\x13\n\x0b\x61rtifact_id\x18\x01 \x01(\t\x12\x15\n\rerror_message\x18\x02 \x01(\t\"\xbe\x01\n\x17\x44ownloadArtifactRequest\x12\x13\n\x0b\x61rtifact_id\x18\x01 \x01(\t\x12\x15\n\rdownload_root\x18\x02 \x01(\t\x12 \n\x18\x61llow_missing_references\x18\x04 \x01(\x08\x12\x12\n\nskip_cache\x18\x05 \x01(\x08\x12\x13\n\x0bpath_prefix\x18\x06 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"1\n\x18\x44ownloadArtifactResponse\x12\x15\n\rerror_message\x18\x01 \x01(\t\"@\n\x10KeepaliveRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x13\n\x11KeepaliveResponse\"q\n\x0c\x41rtifactInfo\x12\x10\n\x08\x61rtifact\x18\x01 \x01(\t\x12\x12\n\nentrypoint\x18\x02 \x03(\t\x12\x10\n\x08notebook\x18\x03 \x01(\x08\x12\x15\n\rbuild_context\x18\x04 \x01(\t\x12\x12\n\ndockerfile\x18\x05 \x01(\t\")\n\x07GitInfo\x12\x0e\n\x06remote\x18\x01 \x01(\t\x12\x0e\n\x06\x63ommit\x18\x02 \x01(\t\"\x87\x01\n\tGitSource\x12)\n\x08git_info\x18\x01 \x01(\x0b\x32\x17.wandb_internal.GitInfo\x12\x12\n\nentrypoint\x18\x02 \x03(\t\x12\x10\n\x08notebook\x18\x03 \x01(\x08\x12\x15\n\rbuild_context\x18\x04 \x01(\t\x12\x12\n\ndockerfile\x18\x05 \x01(\t\"\x1c\n\x0bImageSource\x12\r\n\x05image\x18\x01 \x01(\t\"\x8c\x01\n\x06Source\x12&\n\x03git\x18\x01 \x01(\x0b\x32\x19.wandb_internal.GitSource\x12.\n\x08\x61rtifact\x18\x02 \x01(\x0b\x32\x1c.wandb_internal.ArtifactInfo\x12*\n\x05image\x18\x03 \x01(\x0b\x32\x1b.wandb_internal.ImageSource\"k\n\tJobSource\x12\x10\n\x08_version\x18\x01 \x01(\t\x12\x13\n\x0bsource_type\x18\x02 \x01(\t\x12&\n\x06source\x18\x03 \x01(\x0b\x32\x16.wandb_internal.Source\x12\x0f\n\x07runtime\x18\x04 \x01(\t\"V\n\x12PartialJobArtifact\x12\x10\n\x08job_name\x18\x01 \x01(\t\x12.\n\x0bsource_info\x18\x02 \x01(\x0b\x32\x19.wandb_internal.JobSource\"\x9d\x01\n\x11UseArtifactRecord\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0c\n\x04type\x18\x02 \x01(\t\x12\x0c\n\x04name\x18\x03 \x01(\t\x12\x33\n\x07partial\x18\x04 \x01(\x0b\x32\".wandb_internal.PartialJobArtifact\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x13\n\x11UseArtifactResult\"R\n\rCancelRequest\x12\x13\n\x0b\x63\x61ncel_slot\x18\x01 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x10\n\x0e\x43\x61ncelResponse\"\x18\n\x16ProbeSystemInfoRequest\"\'\n\x08\x44iskInfo\x12\r\n\x05total\x18\x01 \x01(\x04\x12\x0c\n\x04used\x18\x02 \x01(\x04\"\x1b\n\nMemoryInfo\x12\r\n\x05total\x18\x01 \x01(\x04\"/\n\x07\x43puInfo\x12\r\n\x05\x63ount\x18\x01 \x01(\r\x12\x15\n\rcount_logical\x18\x02 \x01(\r\"\x9a\x01\n\tAppleInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\necpu_cores\x18\x02 \x01(\r\x12\x12\n\npcpu_cores\x18\x03 \x01(\r\x12\x11\n\tgpu_cores\x18\x04 \x01(\r\x12\x11\n\tmemory_gb\x18\x05 \x01(\r\x12\x18\n\x10swap_total_bytes\x18\x06 \x01(\x04\x12\x17\n\x0fram_total_bytes\x18\x07 \x01(\x04\"k\n\rGpuNvidiaInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0cmemory_total\x18\x02 \x01(\x04\x12\x12\n\ncuda_cores\x18\x03 \x01(\r\x12\x14\n\x0c\x61rchitecture\x18\x04 \x01(\t\x12\x0c\n\x04uuid\x18\x05 \x01(\t\"\x89\x02\n\nGpuAmdInfo\x12\n\n\x02id\x18\x01 \x01(\t\x12\x11\n\tunique_id\x18\x02 \x01(\t\x12\x15\n\rvbios_version\x18\x03 \x01(\t\x12\x19\n\x11performance_level\x18\x04 \x01(\t\x12\x15\n\rgpu_overdrive\x18\x05 \x01(\t\x12\x1c\n\x14gpu_memory_overdrive\x18\x06 \x01(\t\x12\x11\n\tmax_power\x18\x07 \x01(\t\x12\x0e\n\x06series\x18\x08 \x01(\t\x12\r\n\x05model\x18\t \x01(\t\x12\x0e\n\x06vendor\x18\n \x01(\t\x12\x0b\n\x03sku\x18\x0b \x01(\t\x12\x12\n\nsclk_range\x18\x0c \x01(\t\x12\x12\n\nmclk_range\x18\r \x01(\t\"n\n\x0cTrainiumInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06vendor\x18\x02 \x01(\t\x12\x1b\n\x13neuron_device_count\x18\x03 \x01(\r\x12#\n\x1bneuroncore_per_device_count\x18\x04 \x01(\r\"Q\n\x07TPUInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07hbm_gib\x18\x02 \x01(\r\x12\x18\n\x10\x64\x65vices_per_chip\x18\x03 \x01(\r\x12\r\n\x05\x63ount\x18\x04 \x01(\r\"E\n\rCoreWeaveInfo\x12\x14\n\x0c\x63luster_name\x18\x01 \x01(\t\x12\x0e\n\x06org_id\x18\x02 \x01(\t\x12\x0e\n\x06region\x18\x03 \x01(\t\"\xa8\t\n\x11\x45nvironmentRecord\x12\n\n\x02os\x18\x01 \x01(\t\x12\x0e\n\x06python\x18\x02 \x01(\t\x12\x39\n\nstarted_at\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.TimestampR\tstartedAt\x12\x0e\n\x06\x64ocker\x18\x04 \x01(\t\x12\x0c\n\x04\x61rgs\x18\x05 \x03(\t\x12\x0f\n\x07program\x18\x06 \x01(\t\x12\x1b\n\tcode_path\x18\x07 \x01(\tR\x08\x63odePath\x12&\n\x0f\x63ode_path_local\x18\x08 \x01(\tR\rcodePathLocal\x12*\n\x03git\x18\t \x01(\x0b\x32\x1d.wandb_internal.GitRepoRecord\x12\r\n\x05\x65mail\x18\n \x01(\t\x12\x0c\n\x04root\x18\x0b \x01(\t\x12\x0c\n\x04host\x18\x0c \x01(\t\x12\x10\n\x08username\x18\r \x01(\t\x12\x12\n\nexecutable\x18\x0e \x01(\t\x12\r\n\x05\x63olab\x18\x0f \x01(\t\x12\x1c\n\tcpu_count\x18\x10 \x01(\rR\tcpu_count\x12,\n\x11\x63pu_count_logical\x18\x11 \x01(\rR\x11\x63pu_count_logical\x12\x15\n\x08gpu_type\x18\x12 \x01(\tR\x03gpu\x12\x1c\n\tgpu_count\x18\x13 \x01(\rR\tgpu_count\x12\x39\n\x04\x64isk\x18\x14 \x03(\x0b\x32+.wandb_internal.EnvironmentRecord.DiskEntry\x12*\n\x06memory\x18\x15 \x01(\x0b\x32\x1a.wandb_internal.MemoryInfo\x12$\n\x03\x63pu\x18\x16 \x01(\x0b\x32\x17.wandb_internal.CpuInfo\x12(\n\x05\x61pple\x18\x17 \x01(\x0b\x32\x19.wandb_internal.AppleInfo\x12=\n\ngpu_nvidia\x18\x18 \x03(\x0b\x32\x1d.wandb_internal.GpuNvidiaInfoR\ngpu_nvidia\x12\x14\n\x0c\x63uda_version\x18\x19 \x01(\t\x12\x34\n\x07gpu_amd\x18\x1a \x03(\x0b\x32\x1a.wandb_internal.GpuAmdInfoR\x07gpu_amd\x12;\n\x05slurm\x18\x1b \x03(\x0b\x32,.wandb_internal.EnvironmentRecord.SlurmEntry\x12.\n\x08trainium\x18\x1c \x01(\x0b\x32\x1c.wandb_internal.TrainiumInfo\x12$\n\x03tpu\x18\x1d \x01(\x0b\x32\x17.wandb_internal.TPUInfo\x12\x30\n\tcoreweave\x18\x1e \x01(\x0b\x32\x1d.wandb_internal.CoreWeaveInfo\x12\x12\n\twriter_id\x18\xc7\x01 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\x1a\x45\n\tDiskEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\'\n\x05value\x18\x02 \x01(\x0b\x32\x18.wandb_internal.DiskInfo:\x02\x38\x01\x1a,\n\nSlurmEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x8d\x01\n\x15PythonPackagesRequest\x12\x44\n\x07package\x18\x01 \x03(\x0b\x32\x33.wandb_internal.PythonPackagesRequest.PythonPackage\x1a.\n\rPythonPackage\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07version\x18\x02 \x01(\t\"\x1c\n\x0cJobInputPath\x12\x0c\n\x04path\x18\x01 \x03(\t\"\xd6\x01\n\x0eJobInputSource\x12\x44\n\nrun_config\x18\x01 \x01(\x0b\x32..wandb_internal.JobInputSource.RunConfigSourceH\x00\x12?\n\x04\x66ile\x18\x02 \x01(\x0b\x32/.wandb_internal.JobInputSource.ConfigFileSourceH\x00\x1a\x11\n\x0fRunConfigSource\x1a \n\x10\x43onfigFileSource\x12\x0c\n\x04path\x18\x01 \x01(\tB\x08\n\x06source\"\xc7\x01\n\x0fJobInputRequest\x12\x34\n\x0cinput_source\x18\x01 \x01(\x0b\x32\x1e.wandb_internal.JobInputSource\x12\x33\n\rinclude_paths\x18\x02 \x03(\x0b\x32\x1c.wandb_internal.JobInputPath\x12\x33\n\rexclude_paths\x18\x03 \x03(\x0b\x32\x1c.wandb_internal.JobInputPath\x12\x14\n\x0cinput_schema\x18\x04 \x01(\t\"t\n\x14ServerFeatureRequest\x12.\n\x07\x66\x65\x61ture\x18\x01 \x01(\x0e\x32\x1d.wandb_internal.ServerFeature\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"K\n\x15ServerFeatureResponse\x12\x32\n\x07\x66\x65\x61ture\x18\x01 \x01(\x0b\x32!.wandb_internal.ServerFeatureItem\"2\n\x11ServerFeatureItem\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07\x65nabled\x18\x02 \x01(\x08*\xb3\x04\n\rServerFeature\x12\x13\n\x0fLARGE_FILENAMES\x10\x00\x12\x11\n\rARTIFACT_TAGS\x10\x01\x12\x0e\n\nCLIENT_IDS\x10\x02\x12\x1c\n\x18\x41RTIFACT_REGISTRY_SEARCH\x10\x03\x12\x1b\n\x17STRUCTURED_CONSOLE_LOGS\x10\x04\x12(\n$ARTIFACT_COLLECTION_MEMBERSHIP_FILES\x10\x05\x12\x38\n4ARTIFACT_COLLECTION_MEMBERSHIP_FILE_DOWNLOAD_HANDLER\x10\x06\x12\x34\n0USE_ARTIFACT_WITH_ENTITY_AND_PROJECT_INFORMATION\x10\x07\x12\x1f\n\x1b\x45XPAND_DEFINED_METRIC_GLOBS\x10\x08\x12\x1f\n\x1b\x41UTOMATION_EVENT_RUN_METRIC\x10\t\x12&\n\"AUTOMATION_EVENT_RUN_METRIC_CHANGE\x10\n\x12\x1b\n\x17\x41UTOMATION_ACTION_NO_OP\x10\x0b\x12/\n+INCLUDE_ARTIFACT_TYPES_IN_REGISTRY_CREATION\x10\x0c\x12*\n&PROJECT_ARTIFACT_COLLECTION_MEMBERSHIP\x10\r\x12\x31\n-ARTIFACT_MEMBERSHIP_IN_LINK_ARTIFACT_RESPONSE\x10\x0e\x42\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_internal_pb2', _globals)
+if not _descriptor._USE_C_DESCRIPTORS:
+ _globals['DESCRIPTOR']._loaded_options = None
+ _globals['DESCRIPTOR']._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _globals['_GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY']._loaded_options = None
+ _globals['_GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY']._serialized_options = b'8\001'
+ _globals['_ENVIRONMENTRECORD_DISKENTRY']._loaded_options = None
+ _globals['_ENVIRONMENTRECORD_DISKENTRY']._serialized_options = b'8\001'
+ _globals['_ENVIRONMENTRECORD_SLURMENTRY']._loaded_options = None
+ _globals['_ENVIRONMENTRECORD_SLURMENTRY']._serialized_options = b'8\001'
+ _globals['_SERVERFEATURE']._serialized_start=22471
+ _globals['_SERVERFEATURE']._serialized_end=23034
+ _globals['_RECORD']._serialized_start=209
+ _globals['_RECORD']._serialized_end=1491
+ _globals['_CONTROL']._serialized_start=1494
+ _globals['_CONTROL']._serialized_end=1662
+ _globals['_RESULT']._serialized_start=1665
+ _globals['_RESULT']._serialized_end=2164
+ _globals['_FINALRECORD']._serialized_start=2166
+ _globals['_FINALRECORD']._serialized_end=2224
+ _globals['_VERSIONINFO']._serialized_start=2226
+ _globals['_VERSIONINFO']._serialized_end=2324
+ _globals['_HEADERRECORD']._serialized_start=2326
+ _globals['_HEADERRECORD']._serialized_end=2436
+ _globals['_FOOTERRECORD']._serialized_start=2438
+ _globals['_FOOTERRECORD']._serialized_end=2497
+ _globals['_BRANCHPOINT']._serialized_start=2499
+ _globals['_BRANCHPOINT']._serialized_end=2556
+ _globals['_RUNRECORD']._serialized_start=2559
+ _globals['_RUNRECORD']._serialized_end=3216
+ _globals['_GITREPORECORD']._serialized_start=3218
+ _globals['_GITREPORECORD']._serialized_end=3277
+ _globals['_RUNUPDATERESULT']._serialized_start=3279
+ _globals['_RUNUPDATERESULT']._serialized_end=3378
+ _globals['_ERRORINFO']._serialized_start=3381
+ _globals['_ERRORINFO']._serialized_end=3553
+ _globals['_ERRORINFO_ERRORCODE']._serialized_start=3462
+ _globals['_ERRORINFO_ERRORCODE']._serialized_end=3553
+ _globals['_RUNEXITRECORD']._serialized_start=3555
+ _globals['_RUNEXITRECORD']._serialized_end=3651
+ _globals['_RUNEXITRESULT']._serialized_start=3653
+ _globals['_RUNEXITRESULT']._serialized_end=3668
+ _globals['_RUNPREEMPTINGRECORD']._serialized_start=3670
+ _globals['_RUNPREEMPTINGRECORD']._serialized_end=3736
+ _globals['_RUNPREEMPTINGRESULT']._serialized_start=3738
+ _globals['_RUNPREEMPTINGRESULT']._serialized_end=3759
+ _globals['_SETTINGSRECORD']._serialized_start=3761
+ _globals['_SETTINGSRECORD']._serialized_end=3866
+ _globals['_SETTINGSITEM']._serialized_start=3868
+ _globals['_SETTINGSITEM']._serialized_end=3915
+ _globals['_HISTORYSTEP']._serialized_start=3917
+ _globals['_HISTORYSTEP']._serialized_end=3943
+ _globals['_HISTORYRECORD']._serialized_start=3946
+ _globals['_HISTORYRECORD']._serialized_end=4092
+ _globals['_HISTORYITEM']._serialized_start=4094
+ _globals['_HISTORYITEM']._serialized_end=4160
+ _globals['_HISTORYRESULT']._serialized_start=4162
+ _globals['_HISTORYRESULT']._serialized_end=4177
+ _globals['_OUTPUTRECORD']._serialized_start=4180
+ _globals['_OUTPUTRECORD']._serialized_end=4400
+ _globals['_OUTPUTRECORD_OUTPUTTYPE']._serialized_start=4364
+ _globals['_OUTPUTRECORD_OUTPUTTYPE']._serialized_end=4400
+ _globals['_OUTPUTRESULT']._serialized_start=4402
+ _globals['_OUTPUTRESULT']._serialized_end=4416
+ _globals['_OUTPUTRAWRECORD']._serialized_start=4419
+ _globals['_OUTPUTRAWRECORD']._serialized_end=4645
+ _globals['_OUTPUTRAWRECORD_OUTPUTTYPE']._serialized_start=4364
+ _globals['_OUTPUTRAWRECORD_OUTPUTTYPE']._serialized_end=4400
+ _globals['_OUTPUTRAWRESULT']._serialized_start=4647
+ _globals['_OUTPUTRAWRESULT']._serialized_end=4664
+ _globals['_METRICRECORD']._serialized_start=4667
+ _globals['_METRICRECORD']._serialized_end=5103
+ _globals['_METRICRECORD_METRICGOAL']._serialized_start=5037
+ _globals['_METRICRECORD_METRICGOAL']._serialized_end=5103
+ _globals['_METRICRESULT']._serialized_start=5105
+ _globals['_METRICRESULT']._serialized_end=5119
+ _globals['_METRICOPTIONS']._serialized_start=5121
+ _globals['_METRICOPTIONS']._serialized_end=5188
+ _globals['_METRICCONTROL']._serialized_start=5190
+ _globals['_METRICCONTROL']._serialized_end=5224
+ _globals['_METRICSUMMARY']._serialized_start=5226
+ _globals['_METRICSUMMARY']._serialized_end=5352
+ _globals['_CONFIGRECORD']._serialized_start=5355
+ _globals['_CONFIGRECORD']._serialized_end=5502
+ _globals['_CONFIGITEM']._serialized_start=5504
+ _globals['_CONFIGITEM']._serialized_end=5569
+ _globals['_CONFIGRESULT']._serialized_start=5571
+ _globals['_CONFIGRESULT']._serialized_end=5585
+ _globals['_SUMMARYRECORD']._serialized_start=5588
+ _globals['_SUMMARYRECORD']._serialized_end=5738
+ _globals['_SUMMARYITEM']._serialized_start=5740
+ _globals['_SUMMARYITEM']._serialized_end=5806
+ _globals['_SUMMARYRESULT']._serialized_start=5808
+ _globals['_SUMMARYRESULT']._serialized_end=5823
+ _globals['_FILESRECORD']._serialized_start=5825
+ _globals['_FILESRECORD']._serialized_end=5925
+ _globals['_FILESITEM']._serialized_start=5928
+ _globals['_FILESITEM']._serialized_end=6164
+ _globals['_FILESITEM_POLICYTYPE']._serialized_start=6059
+ _globals['_FILESITEM_POLICYTYPE']._serialized_end=6099
+ _globals['_FILESITEM_FILETYPE']._serialized_start=6101
+ _globals['_FILESITEM_FILETYPE']._serialized_end=6158
+ _globals['_FILESRESULT']._serialized_start=6166
+ _globals['_FILESRESULT']._serialized_end=6179
+ _globals['_STATSRECORD']._serialized_start=6182
+ _globals['_STATSRECORD']._serialized_end=6412
+ _globals['_STATSRECORD_STATSTYPE']._serialized_start=6389
+ _globals['_STATSRECORD_STATSTYPE']._serialized_end=6412
+ _globals['_STATSITEM']._serialized_start=6414
+ _globals['_STATSITEM']._serialized_end=6458
+ _globals['_ARTIFACTRECORD']._serialized_start=6461
+ _globals['_ARTIFACTRECORD']._serialized_end=6948
+ _globals['_ARTIFACTMANIFEST']._serialized_start=6951
+ _globals['_ARTIFACTMANIFEST']._serialized_end=7167
+ _globals['_ARTIFACTMANIFESTENTRY']._serialized_start=7170
+ _globals['_ARTIFACTMANIFESTENTRY']._serialized_end=7377
+ _globals['_EXTRAITEM']._serialized_start=7379
+ _globals['_EXTRAITEM']._serialized_end=7423
+ _globals['_STORAGEPOLICYCONFIGITEM']._serialized_start=7425
+ _globals['_STORAGEPOLICYCONFIGITEM']._serialized_end=7483
+ _globals['_ARTIFACTRESULT']._serialized_start=7485
+ _globals['_ARTIFACTRESULT']._serialized_end=7501
+ _globals['_LINKARTIFACTRESULT']._serialized_start=7503
+ _globals['_LINKARTIFACTRESULT']._serialized_end=7523
+ _globals['_LINKARTIFACTREQUEST']._serialized_start=7526
+ _globals['_LINKARTIFACTREQUEST']._serialized_end=7766
+ _globals['_LINKARTIFACTRESPONSE']._serialized_start=7768
+ _globals['_LINKARTIFACTRESPONSE']._serialized_end=7859
+ _globals['_TBRECORD']._serialized_start=7861
+ _globals['_TBRECORD']._serialized_end=7965
+ _globals['_TBRESULT']._serialized_start=7967
+ _globals['_TBRESULT']._serialized_end=7977
+ _globals['_ALERTRECORD']._serialized_start=7979
+ _globals['_ALERTRECORD']._serialized_end=8104
+ _globals['_ALERTRESULT']._serialized_start=8106
+ _globals['_ALERTRESULT']._serialized_end=8119
+ _globals['_REQUEST']._serialized_start=8122
+ _globals['_REQUEST']._serialized_end=10418
+ _globals['_RESPONSE']._serialized_start=10421
+ _globals['_RESPONSE']._serialized_end=12293
+ _globals['_DEFERREQUEST']._serialized_start=12296
+ _globals['_DEFERREQUEST']._serialized_end=12616
+ _globals['_DEFERREQUEST_DEFERSTATE']._serialized_start=12369
+ _globals['_DEFERREQUEST_DEFERSTATE']._serialized_end=12616
+ _globals['_PAUSEREQUEST']._serialized_start=12618
+ _globals['_PAUSEREQUEST']._serialized_end=12678
+ _globals['_PAUSERESPONSE']._serialized_start=12680
+ _globals['_PAUSERESPONSE']._serialized_end=12695
+ _globals['_RESUMEREQUEST']._serialized_start=12697
+ _globals['_RESUMEREQUEST']._serialized_end=12758
+ _globals['_RESUMERESPONSE']._serialized_start=12760
+ _globals['_RESUMERESPONSE']._serialized_end=12776
+ _globals['_LOGINREQUEST']._serialized_start=12778
+ _globals['_LOGINREQUEST']._serialized_end=12855
+ _globals['_LOGINRESPONSE']._serialized_start=12857
+ _globals['_LOGINRESPONSE']._serialized_end=12895
+ _globals['_GETSUMMARYREQUEST']._serialized_start=12897
+ _globals['_GETSUMMARYREQUEST']._serialized_end=12962
+ _globals['_GETSUMMARYRESPONSE']._serialized_start=12964
+ _globals['_GETSUMMARYRESPONSE']._serialized_end=13027
+ _globals['_GETSYSTEMMETRICSREQUEST']._serialized_start=13029
+ _globals['_GETSYSTEMMETRICSREQUEST']._serialized_end=13100
+ _globals['_SYSTEMMETRICSAMPLE']._serialized_start=13102
+ _globals['_SYSTEMMETRICSAMPLE']._serialized_end=13184
+ _globals['_SYSTEMMETRICSBUFFER']._serialized_start=13186
+ _globals['_SYSTEMMETRICSBUFFER']._serialized_end=13259
+ _globals['_GETSYSTEMMETRICSRESPONSE']._serialized_start=13262
+ _globals['_GETSYSTEMMETRICSRESPONSE']._serialized_end=13464
+ _globals['_GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY']._serialized_start=13375
+ _globals['_GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY']._serialized_end=13464
+ _globals['_STATUSREQUEST']._serialized_start=13466
+ _globals['_STATUSREQUEST']._serialized_end=13527
+ _globals['_STATUSRESPONSE']._serialized_start=13529
+ _globals['_STATUSRESPONSE']._serialized_end=13570
+ _globals['_STOPSTATUSREQUEST']._serialized_start=13572
+ _globals['_STOPSTATUSREQUEST']._serialized_end=13637
+ _globals['_STOPSTATUSRESPONSE']._serialized_start=13639
+ _globals['_STOPSTATUSRESPONSE']._serialized_end=13684
+ _globals['_NETWORKSTATUSREQUEST']._serialized_start=13686
+ _globals['_NETWORKSTATUSREQUEST']._serialized_end=13754
+ _globals['_NETWORKSTATUSRESPONSE']._serialized_start=13756
+ _globals['_NETWORKSTATUSRESPONSE']._serialized_end=13836
+ _globals['_HTTPRESPONSE']._serialized_start=13838
+ _globals['_HTTPRESPONSE']._serialized_end=13906
+ _globals['_INTERNALMESSAGESREQUEST']._serialized_start=13908
+ _globals['_INTERNALMESSAGESREQUEST']._serialized_end=13979
+ _globals['_INTERNALMESSAGESRESPONSE']._serialized_start=13981
+ _globals['_INTERNALMESSAGESRESPONSE']._serialized_end=14059
+ _globals['_INTERNALMESSAGES']._serialized_start=14061
+ _globals['_INTERNALMESSAGES']._serialized_end=14096
+ _globals['_POLLEXITREQUEST']._serialized_start=14098
+ _globals['_POLLEXITREQUEST']._serialized_end=14161
+ _globals['_POLLEXITRESPONSE']._serialized_start=14164
+ _globals['_POLLEXITRESPONSE']._serialized_end=14409
+ _globals['_OPERATIONSTATSREQUEST']._serialized_start=14411
+ _globals['_OPERATIONSTATSREQUEST']._serialized_end=14480
+ _globals['_OPERATIONSTATSRESPONSE']._serialized_start=14482
+ _globals['_OPERATIONSTATSRESPONSE']._serialized_end=14563
+ _globals['_OPERATIONSTATS']._serialized_start=14565
+ _globals['_OPERATIONSTATS']._serialized_end=14654
+ _globals['_OPERATION']._serialized_start=14657
+ _globals['_OPERATION']._serialized_end=14792
+ _globals['_SENDERMARKREQUEST']._serialized_start=14794
+ _globals['_SENDERMARKREQUEST']._serialized_end=14813
+ _globals['_SYNCFINISHREQUEST']._serialized_start=14815
+ _globals['_SYNCFINISHREQUEST']._serialized_end=14834
+ _globals['_SYNCRESPONSE']._serialized_start=14836
+ _globals['_SYNCRESPONSE']._serialized_end=14905
+ _globals['_SENDERREADREQUEST']._serialized_start=14907
+ _globals['_SENDERREADREQUEST']._serialized_end=14970
+ _globals['_STATUSREPORTREQUEST']._serialized_start=14972
+ _globals['_STATUSREPORTREQUEST']._serialized_end=15081
+ _globals['_SUMMARYRECORDREQUEST']._serialized_start=15083
+ _globals['_SUMMARYRECORDREQUEST']._serialized_end=15153
+ _globals['_TELEMETRYRECORDREQUEST']._serialized_start=15155
+ _globals['_TELEMETRYRECORDREQUEST']._serialized_end=15231
+ _globals['_SERVERINFOREQUEST']._serialized_start=15233
+ _globals['_SERVERINFOREQUEST']._serialized_end=15298
+ _globals['_SERVERINFORESPONSE']._serialized_start=15300
+ _globals['_SERVERINFORESPONSE']._serialized_end=15424
+ _globals['_SERVERMESSAGES']._serialized_start=15426
+ _globals['_SERVERMESSAGES']._serialized_end=15487
+ _globals['_SERVERMESSAGE']._serialized_start=15489
+ _globals['_SERVERMESSAGE']._serialized_end=15590
+ _globals['_FILECOUNTS']._serialized_start=15592
+ _globals['_FILECOUNTS']._serialized_end=15691
+ _globals['_FILEPUSHERSTATS']._serialized_start=15693
+ _globals['_FILEPUSHERSTATS']._serialized_end=15778
+ _globals['_FILESUPLOADED']._serialized_start=15780
+ _globals['_FILESUPLOADED']._serialized_end=15810
+ _globals['_FILETRANSFERINFOREQUEST']._serialized_start=15813
+ _globals['_FILETRANSFERINFOREQUEST']._serialized_end=16057
+ _globals['_FILETRANSFERINFOREQUEST_TRANSFERTYPE']._serialized_start=16017
+ _globals['_FILETRANSFERINFOREQUEST_TRANSFERTYPE']._serialized_end=16057
+ _globals['_LOCALINFO']._serialized_start=16059
+ _globals['_LOCALINFO']._serialized_end=16108
+ _globals['_SHUTDOWNREQUEST']._serialized_start=16110
+ _globals['_SHUTDOWNREQUEST']._serialized_end=16173
+ _globals['_SHUTDOWNRESPONSE']._serialized_start=16175
+ _globals['_SHUTDOWNRESPONSE']._serialized_end=16193
+ _globals['_ATTACHREQUEST']._serialized_start=16195
+ _globals['_ATTACHREQUEST']._serialized_end=16275
+ _globals['_ATTACHRESPONSE']._serialized_start=16277
+ _globals['_ATTACHRESPONSE']._serialized_end=16375
+ _globals['_TESTINJECTREQUEST']._serialized_start=16378
+ _globals['_TESTINJECTREQUEST']._serialized_end=16719
+ _globals['_TESTINJECTRESPONSE']._serialized_start=16721
+ _globals['_TESTINJECTRESPONSE']._serialized_end=16741
+ _globals['_HISTORYACTION']._serialized_start=16743
+ _globals['_HISTORYACTION']._serialized_end=16773
+ _globals['_PARTIALHISTORYREQUEST']._serialized_start=16776
+ _globals['_PARTIALHISTORYREQUEST']._serialized_end=16978
+ _globals['_PARTIALHISTORYRESPONSE']._serialized_start=16980
+ _globals['_PARTIALHISTORYRESPONSE']._serialized_end=17004
+ _globals['_SAMPLEDHISTORYREQUEST']._serialized_start=17006
+ _globals['_SAMPLEDHISTORYREQUEST']._serialized_end=17075
+ _globals['_SAMPLEDHISTORYITEM']._serialized_start=17077
+ _globals['_SAMPLEDHISTORYITEM']._serialized_end=17172
+ _globals['_SAMPLEDHISTORYRESPONSE']._serialized_start=17174
+ _globals['_SAMPLEDHISTORYRESPONSE']._serialized_end=17248
+ _globals['_RUNSTATUSREQUEST']._serialized_start=17250
+ _globals['_RUNSTATUSREQUEST']._serialized_end=17314
+ _globals['_RUNSTATUSRESPONSE']._serialized_start=17316
+ _globals['_RUNSTATUSRESPONSE']._serialized_end=17436
+ _globals['_RUNSTARTREQUEST']._serialized_start=17438
+ _globals['_RUNSTARTREQUEST']._serialized_end=17541
+ _globals['_RUNSTARTRESPONSE']._serialized_start=17543
+ _globals['_RUNSTARTRESPONSE']._serialized_end=17561
+ _globals['_RUNFINISHWITHOUTEXITREQUEST']._serialized_start=17563
+ _globals['_RUNFINISHWITHOUTEXITREQUEST']._serialized_end=17638
+ _globals['_RUNFINISHWITHOUTEXITRESPONSE']._serialized_start=17640
+ _globals['_RUNFINISHWITHOUTEXITRESPONSE']._serialized_end=17670
+ _globals['_CHECKVERSIONREQUEST']._serialized_start=17672
+ _globals['_CHECKVERSIONREQUEST']._serialized_end=17764
+ _globals['_CHECKVERSIONRESPONSE']._serialized_start=17766
+ _globals['_CHECKVERSIONRESPONSE']._serialized_end=17859
+ _globals['_JOBINFOREQUEST']._serialized_start=17861
+ _globals['_JOBINFOREQUEST']._serialized_end=17923
+ _globals['_JOBINFORESPONSE']._serialized_start=17925
+ _globals['_JOBINFORESPONSE']._serialized_end=17979
+ _globals['_LOGARTIFACTREQUEST']._serialized_start=17982
+ _globals['_LOGARTIFACTREQUEST']._serialized_end=18141
+ _globals['_LOGARTIFACTRESPONSE']._serialized_start=18143
+ _globals['_LOGARTIFACTRESPONSE']._serialized_end=18208
+ _globals['_DOWNLOADARTIFACTREQUEST']._serialized_start=18211
+ _globals['_DOWNLOADARTIFACTREQUEST']._serialized_end=18401
+ _globals['_DOWNLOADARTIFACTRESPONSE']._serialized_start=18403
+ _globals['_DOWNLOADARTIFACTRESPONSE']._serialized_end=18452
+ _globals['_KEEPALIVEREQUEST']._serialized_start=18454
+ _globals['_KEEPALIVEREQUEST']._serialized_end=18518
+ _globals['_KEEPALIVERESPONSE']._serialized_start=18520
+ _globals['_KEEPALIVERESPONSE']._serialized_end=18539
+ _globals['_ARTIFACTINFO']._serialized_start=18541
+ _globals['_ARTIFACTINFO']._serialized_end=18654
+ _globals['_GITINFO']._serialized_start=18656
+ _globals['_GITINFO']._serialized_end=18697
+ _globals['_GITSOURCE']._serialized_start=18700
+ _globals['_GITSOURCE']._serialized_end=18835
+ _globals['_IMAGESOURCE']._serialized_start=18837
+ _globals['_IMAGESOURCE']._serialized_end=18865
+ _globals['_SOURCE']._serialized_start=18868
+ _globals['_SOURCE']._serialized_end=19008
+ _globals['_JOBSOURCE']._serialized_start=19010
+ _globals['_JOBSOURCE']._serialized_end=19117
+ _globals['_PARTIALJOBARTIFACT']._serialized_start=19119
+ _globals['_PARTIALJOBARTIFACT']._serialized_end=19205
+ _globals['_USEARTIFACTRECORD']._serialized_start=19208
+ _globals['_USEARTIFACTRECORD']._serialized_end=19365
+ _globals['_USEARTIFACTRESULT']._serialized_start=19367
+ _globals['_USEARTIFACTRESULT']._serialized_end=19386
+ _globals['_CANCELREQUEST']._serialized_start=19388
+ _globals['_CANCELREQUEST']._serialized_end=19470
+ _globals['_CANCELRESPONSE']._serialized_start=19472
+ _globals['_CANCELRESPONSE']._serialized_end=19488
+ _globals['_PROBESYSTEMINFOREQUEST']._serialized_start=19490
+ _globals['_PROBESYSTEMINFOREQUEST']._serialized_end=19514
+ _globals['_DISKINFO']._serialized_start=19516
+ _globals['_DISKINFO']._serialized_end=19555
+ _globals['_MEMORYINFO']._serialized_start=19557
+ _globals['_MEMORYINFO']._serialized_end=19584
+ _globals['_CPUINFO']._serialized_start=19586
+ _globals['_CPUINFO']._serialized_end=19633
+ _globals['_APPLEINFO']._serialized_start=19636
+ _globals['_APPLEINFO']._serialized_end=19790
+ _globals['_GPUNVIDIAINFO']._serialized_start=19792
+ _globals['_GPUNVIDIAINFO']._serialized_end=19899
+ _globals['_GPUAMDINFO']._serialized_start=19902
+ _globals['_GPUAMDINFO']._serialized_end=20167
+ _globals['_TRAINIUMINFO']._serialized_start=20169
+ _globals['_TRAINIUMINFO']._serialized_end=20279
+ _globals['_TPUINFO']._serialized_start=20281
+ _globals['_TPUINFO']._serialized_end=20362
+ _globals['_COREWEAVEINFO']._serialized_start=20364
+ _globals['_COREWEAVEINFO']._serialized_end=20433
+ _globals['_ENVIRONMENTRECORD']._serialized_start=20436
+ _globals['_ENVIRONMENTRECORD']._serialized_end=21628
+ _globals['_ENVIRONMENTRECORD_DISKENTRY']._serialized_start=21513
+ _globals['_ENVIRONMENTRECORD_DISKENTRY']._serialized_end=21582
+ _globals['_ENVIRONMENTRECORD_SLURMENTRY']._serialized_start=21584
+ _globals['_ENVIRONMENTRECORD_SLURMENTRY']._serialized_end=21628
+ _globals['_PYTHONPACKAGESREQUEST']._serialized_start=21631
+ _globals['_PYTHONPACKAGESREQUEST']._serialized_end=21772
+ _globals['_PYTHONPACKAGESREQUEST_PYTHONPACKAGE']._serialized_start=21726
+ _globals['_PYTHONPACKAGESREQUEST_PYTHONPACKAGE']._serialized_end=21772
+ _globals['_JOBINPUTPATH']._serialized_start=21774
+ _globals['_JOBINPUTPATH']._serialized_end=21802
+ _globals['_JOBINPUTSOURCE']._serialized_start=21805
+ _globals['_JOBINPUTSOURCE']._serialized_end=22019
+ _globals['_JOBINPUTSOURCE_RUNCONFIGSOURCE']._serialized_start=21958
+ _globals['_JOBINPUTSOURCE_RUNCONFIGSOURCE']._serialized_end=21975
+ _globals['_JOBINPUTSOURCE_CONFIGFILESOURCE']._serialized_start=21977
+ _globals['_JOBINPUTSOURCE_CONFIGFILESOURCE']._serialized_end=22009
+ _globals['_JOBINPUTREQUEST']._serialized_start=22022
+ _globals['_JOBINPUTREQUEST']._serialized_end=22221
+ _globals['_SERVERFEATUREREQUEST']._serialized_start=22223
+ _globals['_SERVERFEATUREREQUEST']._serialized_end=22339
+ _globals['_SERVERFEATURERESPONSE']._serialized_start=22341
+ _globals['_SERVERFEATURERESPONSE']._serialized_end=22416
+ _globals['_SERVERFEATUREITEM']._serialized_start=22418
+ _globals['_SERVERFEATUREITEM']._serialized_end=22468
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v5/wandb_server_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v5/wandb_server_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..5426eeea8d6d07ff91ab48ecddaeaee6488a4641
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v5/wandb_server_pb2.py
@@ -0,0 +1,65 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: wandb/proto/wandb_server.proto
+# Protobuf Python Version: 5.26.1
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2
+from wandb.proto import wandb_internal_pb2 as wandb_dot_proto_dot_wandb__internal__pb2
+from wandb.proto import wandb_settings_pb2 as wandb_dot_proto_dot_wandb__settings__pb2
+from wandb.proto import wandb_sync_pb2 as wandb_dot_proto_dot_wandb__sync__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1ewandb/proto/wandb_server.proto\x12\x0ewandb_internal\x1a\x1cwandb/proto/wandb_base.proto\x1a wandb/proto/wandb_internal.proto\x1a wandb/proto/wandb_settings.proto\x1a\x1cwandb/proto/wandb_sync.proto\"k\n\x19ServerAuthenticateRequest\x12\x0f\n\x07\x61pi_key\x18\x01 \x01(\t\x12\x10\n\x08\x62\x61se_url\x18\x02 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"w\n\x1aServerAuthenticateResponse\x12\x16\n\x0e\x64\x65\x66\x61ult_entity\x18\x01 \x01(\t\x12\x14\n\x0c\x65rror_status\x18\x02 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"D\n\x15ServerShutdownRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x18\n\x16ServerShutdownResponse\"B\n\x13ServerStatusRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x16\n\x14ServerStatusResponse\"r\n\x17ServerInformInitRequest\x12*\n\x08settings\x18\x01 \x01(\x0b\x32\x18.wandb_internal.Settings\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1a\n\x18ServerInformInitResponse\"H\n\x19ServerInformFinishRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1c\n\x1aServerInformFinishResponse\"H\n\x19ServerInformAttachRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"u\n\x1aServerInformAttachResponse\x12*\n\x08settings\x18\x01 \x01(\x0b\x32\x18.wandb_internal.Settings\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"H\n\x19ServerInformDetachRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1c\n\x1aServerInformDetachResponse\"]\n\x1bServerInformTeardownRequest\x12\x11\n\texit_code\x18\x01 \x01(\x05\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1e\n\x1cServerInformTeardownResponse\"\xee\x05\n\rServerRequest\x12\x12\n\nrequest_id\x18\n \x01(\t\x12\x30\n\x0erecord_publish\x18\x01 \x01(\x0b\x32\x16.wandb_internal.RecordH\x00\x12\x34\n\x12record_communicate\x18\x02 \x01(\x0b\x32\x16.wandb_internal.RecordH\x00\x12>\n\x0binform_init\x18\x03 \x01(\x0b\x32\'.wandb_internal.ServerInformInitRequestH\x00\x12\x42\n\rinform_finish\x18\x04 \x01(\x0b\x32).wandb_internal.ServerInformFinishRequestH\x00\x12\x42\n\rinform_attach\x18\x05 \x01(\x0b\x32).wandb_internal.ServerInformAttachRequestH\x00\x12\x42\n\rinform_detach\x18\x06 \x01(\x0b\x32).wandb_internal.ServerInformDetachRequestH\x00\x12\x46\n\x0finform_teardown\x18\x07 \x01(\x0b\x32+.wandb_internal.ServerInformTeardownRequestH\x00\x12\x41\n\x0c\x61uthenticate\x18\t \x01(\x0b\x32).wandb_internal.ServerAuthenticateRequestH\x00\x12:\n\tinit_sync\x18\x0b \x01(\x0b\x32%.wandb_internal.ServerInitSyncRequestH\x00\x12\x31\n\x04sync\x18\x0c \x01(\x0b\x32!.wandb_internal.ServerSyncRequestH\x00\x12>\n\x0bsync_status\x18\r \x01(\x0b\x32\'.wandb_internal.ServerSyncStatusRequestH\x00\x42\x15\n\x13server_request_typeJ\x04\x08\x08\x10\t\"\x98\x06\n\x0eServerResponse\x12\x12\n\nrequest_id\x18\n \x01(\t\x12\x34\n\x12result_communicate\x18\x02 \x01(\x0b\x32\x16.wandb_internal.ResultH\x00\x12H\n\x14inform_init_response\x18\x03 \x01(\x0b\x32(.wandb_internal.ServerInformInitResponseH\x00\x12L\n\x16inform_finish_response\x18\x04 \x01(\x0b\x32*.wandb_internal.ServerInformFinishResponseH\x00\x12L\n\x16inform_attach_response\x18\x05 \x01(\x0b\x32*.wandb_internal.ServerInformAttachResponseH\x00\x12L\n\x16inform_detach_response\x18\x06 \x01(\x0b\x32*.wandb_internal.ServerInformDetachResponseH\x00\x12P\n\x18inform_teardown_response\x18\x07 \x01(\x0b\x32,.wandb_internal.ServerInformTeardownResponseH\x00\x12K\n\x15\x61uthenticate_response\x18\t \x01(\x0b\x32*.wandb_internal.ServerAuthenticateResponseH\x00\x12\x44\n\x12init_sync_response\x18\x0b \x01(\x0b\x32&.wandb_internal.ServerInitSyncResponseH\x00\x12;\n\rsync_response\x18\x0c \x01(\x0b\x32\".wandb_internal.ServerSyncResponseH\x00\x12H\n\x14sync_status_response\x18\r \x01(\x0b\x32(.wandb_internal.ServerSyncStatusResponseH\x00\x42\x16\n\x14server_response_typeJ\x04\x08\x08\x10\tB\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_server_pb2', _globals)
+if not _descriptor._USE_C_DESCRIPTORS:
+ _globals['DESCRIPTOR']._loaded_options = None
+ _globals['DESCRIPTOR']._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _globals['_SERVERAUTHENTICATEREQUEST']._serialized_start=178
+ _globals['_SERVERAUTHENTICATEREQUEST']._serialized_end=285
+ _globals['_SERVERAUTHENTICATERESPONSE']._serialized_start=287
+ _globals['_SERVERAUTHENTICATERESPONSE']._serialized_end=406
+ _globals['_SERVERSHUTDOWNREQUEST']._serialized_start=408
+ _globals['_SERVERSHUTDOWNREQUEST']._serialized_end=476
+ _globals['_SERVERSHUTDOWNRESPONSE']._serialized_start=478
+ _globals['_SERVERSHUTDOWNRESPONSE']._serialized_end=502
+ _globals['_SERVERSTATUSREQUEST']._serialized_start=504
+ _globals['_SERVERSTATUSREQUEST']._serialized_end=570
+ _globals['_SERVERSTATUSRESPONSE']._serialized_start=572
+ _globals['_SERVERSTATUSRESPONSE']._serialized_end=594
+ _globals['_SERVERINFORMINITREQUEST']._serialized_start=596
+ _globals['_SERVERINFORMINITREQUEST']._serialized_end=710
+ _globals['_SERVERINFORMINITRESPONSE']._serialized_start=712
+ _globals['_SERVERINFORMINITRESPONSE']._serialized_end=738
+ _globals['_SERVERINFORMFINISHREQUEST']._serialized_start=740
+ _globals['_SERVERINFORMFINISHREQUEST']._serialized_end=812
+ _globals['_SERVERINFORMFINISHRESPONSE']._serialized_start=814
+ _globals['_SERVERINFORMFINISHRESPONSE']._serialized_end=842
+ _globals['_SERVERINFORMATTACHREQUEST']._serialized_start=844
+ _globals['_SERVERINFORMATTACHREQUEST']._serialized_end=916
+ _globals['_SERVERINFORMATTACHRESPONSE']._serialized_start=918
+ _globals['_SERVERINFORMATTACHRESPONSE']._serialized_end=1035
+ _globals['_SERVERINFORMDETACHREQUEST']._serialized_start=1037
+ _globals['_SERVERINFORMDETACHREQUEST']._serialized_end=1109
+ _globals['_SERVERINFORMDETACHRESPONSE']._serialized_start=1111
+ _globals['_SERVERINFORMDETACHRESPONSE']._serialized_end=1139
+ _globals['_SERVERINFORMTEARDOWNREQUEST']._serialized_start=1141
+ _globals['_SERVERINFORMTEARDOWNREQUEST']._serialized_end=1234
+ _globals['_SERVERINFORMTEARDOWNRESPONSE']._serialized_start=1236
+ _globals['_SERVERINFORMTEARDOWNRESPONSE']._serialized_end=1266
+ _globals['_SERVERREQUEST']._serialized_start=1269
+ _globals['_SERVERREQUEST']._serialized_end=2019
+ _globals['_SERVERRESPONSE']._serialized_start=2022
+ _globals['_SERVERRESPONSE']._serialized_end=2814
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v5/wandb_settings_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v5/wandb_settings_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..324e2e5593f9903d7ebf2e9d21e2934641c2a348
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v5/wandb_settings_pb2.py
@@ -0,0 +1,48 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: wandb/proto/wandb_settings.proto
+# Protobuf Python Version: 5.26.1
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from google.protobuf import wrappers_pb2 as google_dot_protobuf_dot_wrappers__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n wandb/proto/wandb_settings.proto\x12\x0ewandb_internal\x1a\x1egoogle/protobuf/wrappers.proto\" \n\x0fListStringValue\x12\r\n\x05value\x18\x01 \x03(\t\"\x1d\n\x0cListIntValue\x12\r\n\x05value\x18\x01 \x03(\x05\"\x8a\x01\n\x17MapStringKeyStringValue\x12\x41\n\x05value\x18\x01 \x03(\x0b\x32\x32.wandb_internal.MapStringKeyStringValue.ValueEntry\x1a,\n\nValueEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xcb\x01\n#MapStringKeyMapStringKeyStringValue\x12M\n\x05value\x18\x01 \x03(\x0b\x32>.wandb_internal.MapStringKeyMapStringKeyStringValue.ValueEntry\x1aU\n\nValueEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x36\n\x05value\x18\x02 \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue:\x02\x38\x01\"\x9a\x01\n\x12OpenMetricsFilters\x12\x33\n\x08sequence\x18\x01 \x01(\x0b\x32\x1f.wandb_internal.ListStringValueH\x00\x12\x46\n\x07mapping\x18\x02 \x01(\x0b\x32\x33.wandb_internal.MapStringKeyMapStringKeyStringValueH\x00\x42\x07\n\x05value\"7\n\tRunMoment\x12\x0b\n\x03run\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x01\x12\x0e\n\x06metric\x18\x03 \x01(\t\"\xc2M\n\x08Settings\x12-\n\x07\x61pi_key\x18\x37 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12:\n\x13identity_token_file\x18\xaa\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x37\n\x10\x63redentials_file\x18\xab\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x39\n\x14insecure_disable_ssl\x18\xb9\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12,\n\x08_offline\x18\x1e \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12*\n\x06x_sync\x18\x1f \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x30\n\tsync_file\x18\x86\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x07_shared\x18\xa2\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12,\n\x06run_id\x18k \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12-\n\x07run_url\x18q \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12-\n\x07project\x18\x61 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x06\x65ntity\x18\x45 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x33\n\x0corganization\x18\xbc\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0cx_start_time\x18) \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12.\n\x08root_dir\x18i \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12-\n\x07log_dir\x18U \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0clog_internal\x18V \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0cignore_globs\x18N \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12.\n\x08\x62\x61se_url\x18\x39 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12=\n\x17x_file_stream_max_bytes\x18\xac\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x46\n\x1fx_file_stream_transmit_interval\x18\xaf\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x45\n\x14x_extra_http_headers\x18\x0e \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12=\n\x17x_file_stream_retry_max\x18\x93\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12K\n$x_file_stream_retry_wait_min_seconds\x18\x94\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12K\n$x_file_stream_retry_wait_max_seconds\x18\x95\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x43\n\x1dx_file_stream_timeout_seconds\x18\x0f \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x42\n\x1cx_file_stream_max_line_bytes\x18\xb2\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12?\n\x19x_file_transfer_retry_max\x18\x96\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12M\n&x_file_transfer_retry_wait_min_seconds\x18\x97\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12M\n&x_file_transfer_retry_wait_max_seconds\x18\x98\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x46\n\x1fx_file_transfer_timeout_seconds\x18\x99\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x39\n\x13x_graphql_retry_max\x18\x9a\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12G\n x_graphql_retry_wait_min_seconds\x18\x9b\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12G\n x_graphql_retry_wait_max_seconds\x18\x9c\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12@\n\x19x_graphql_timeout_seconds\x18\x9d\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x31\n\nhttp_proxy\x18\xa8\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0bhttps_proxy\x18\xa9\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12;\n\tx_proxies\x18\xc8\x01 \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12-\n\x07program\x18_ \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0fprogram_relpath\x18` \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x37\n\x10_code_path_local\x18\xa3\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x36\n\x0fprogram_abspath\x18\x9f\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x05_args\x18\x01 \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12)\n\x03_os\x18 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x06\x64ocker\x18\x43 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0cx_executable\x18\r \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12-\n\x07_python\x18\" \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x30\n\tcolab_url\x18\xa0\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12*\n\x04host\x18M \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x08username\x18\x8d\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12+\n\x05\x65mail\x18\x44 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x06resume\x18\x66 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x0bresume_from\x18\xa7\x01 \x01(\x0b\x32\x19.wandb_internal.RunMoment\x12-\n\tfork_from\x18\xa4\x01 \x01(\x0b\x32\x19.wandb_internal.RunMoment\x12\x38\n\x14\x64isable_job_creation\x18\x41 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x30\n\tsweep_url\x18\x83\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12;\n\x16x_disable_update_check\x18\xa5\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x32\n\x0ex_disable_meta\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12-\n\tsave_code\x18s \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\x0b\x64isable_git\x18? \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12;\n\x16x_disable_machine_info\x18\x9e\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x33\n\x0fx_disable_stats\x18\n \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x39\n\x13x_stats_buffer_size\x18\xa1\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12@\n\x19x_stats_sampling_interval\x18\xae\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x30\n\x0bx_stats_pid\x18* \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12<\n\x12x_stats_disk_paths\x18\x92\x01 \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12H\n\"x_stats_neuron_monitor_config_path\x18. \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12<\n\x15x_stats_dcgm_exporter\x18\xbb\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12O\n\x1ex_stats_open_metrics_endpoints\x18/ \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12H\n\x1cx_stats_open_metrics_filters\x18\x30 \x01(\x0b\x32\".wandb_internal.OpenMetricsFilters\x12S\n!x_stats_open_metrics_http_headers\x18\xb8\x01 \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12=\n\x16x_stats_gpu_device_ids\x18\xba\x01 \x01(\x0b\x32\x1c.wandb_internal.ListIntValue\x12\x37\n\x11x_stats_cpu_count\x18\xc2\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12?\n\x19x_stats_cpu_logical_count\x18\xc3\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x37\n\x11x_stats_gpu_count\x18\xc4\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x37\n\x10x_stats_gpu_type\x18\xc5\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12?\n\x1ax_stats_track_process_tree\x18\xc6\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12.\n\x07x_label\x18\xb5\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\tx_primary\x18\xb6\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12:\n\x15x_update_finish_state\x18\xb7\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12<\n\x17\x61llow_offline_artifacts\x18\xb1\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12-\n\x07\x63onsole\x18< \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x36\n\x11\x63onsole_multipart\x18\xa6\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x35\n\x10sync_tensorboard\x18\xb3\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x42\n\x1dx_server_side_derived_summary\x18\xbd\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x46\n!x_server_side_expand_glob_metrics\x18\xbe\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12;\n\x16x_skip_transaction_log\x18\xbf\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12J\n#x_stats_coreweave_metadata_base_url\x18\xc0\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12J\n#x_stats_coreweave_metadata_endpoint\x18\xc1\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x0b_aws_lambda\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x33\n\x0fx_cli_only_mode\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12*\n\x06_colab\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x34\n\x10x_disable_viewer\x18\x0b \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x39\n\x15x_flow_control_custom\x18\x10 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12;\n\x17x_flow_control_disabled\x18\x11 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12>\n\x18x_internal_check_process\x18\x12 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12,\n\x08_ipython\x18\x14 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12,\n\x08_jupyter\x18\x15 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x34\n\x0ex_jupyter_root\x18\x16 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12+\n\x07_kaggle\x18\x17 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12=\n\x18x_live_policy_rate_limit\x18\x18 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12<\n\x17x_live_policy_wait_time\x18\x19 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x30\n\x0bx_log_level\x18\x1a \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x35\n\x10x_network_buffer\x18\x1b \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12)\n\x05_noop\x18\x1c \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12-\n\t_notebook\x18\x1d \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\t_platform\x18! \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x38\n\x12x_runqueue_item_id\x18# \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x37\n\x13x_save_requirements\x18% \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x39\n\x13x_service_transport\x18& \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x34\n\x0ex_service_wait\x18\' \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x35\n\x0f_start_datetime\x18( \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x33\n\r_tmp_code_dir\x18\x31 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x08_windows\x18\x34 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x34\n\x10\x61llow_val_change\x18\x35 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\tanonymous\x18\x36 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12P\n\x1f\x61zure_account_url_to_access_key\x18\x38 \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12.\n\x08\x63ode_dir\x18: \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0c\x63onfig_paths\x18; \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12\x30\n\ndeployment\x18= \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x30\n\x0c\x64isable_code\x18> \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x31\n\rdisable_hints\x18@ \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12,\n\x08\x64isabled\x18\x42 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12)\n\x05\x66orce\x18G \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x30\n\ngit_commit\x18H \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x30\n\ngit_remote\x18I \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x34\n\x0egit_remote_url\x18J \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x08git_root\x18K \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x36\n\x11heartbeat_seconds\x18L \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x32\n\x0cinit_timeout\x18O \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12,\n\x08is_local\x18P \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x30\n\njob_source\x18Q \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x31\n\rlabel_disable\x18R \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12*\n\x06launch\x18S \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x38\n\x12launch_config_path\x18T \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12:\n\x14log_symlink_internal\x18W \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x36\n\x10log_symlink_user\x18X \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x08log_user\x18Y \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x33\n\rlogin_timeout\x18Z \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12*\n\x04mode\x18\\ \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x33\n\rnotebook_name\x18] \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x31\n\x0bproject_url\x18\x62 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12)\n\x05quiet\x18\x63 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12+\n\x07relogin\x18\x65 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x32\n\x0cresume_fname\x18g \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12+\n\x07resumed\x18h \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\trun_group\x18j \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0crun_job_type\x18l \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x08run_mode\x18m \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x08run_name\x18n \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\trun_notes\x18o \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x31\n\x08run_tags\x18p \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12\x35\n\x11sagemaker_disable\x18r \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x35\n\x0fsettings_system\x18t \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x38\n\x12settings_workspace\x18u \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x0bshow_colors\x18v \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12.\n\nshow_emoji\x18w \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\x0bshow_errors\x18x \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12-\n\tshow_info\x18y \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x31\n\rshow_warnings\x18z \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12*\n\x06silent\x18{ \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x32\n\x0cstart_method\x18| \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12*\n\x06strict\x18} \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x33\n\x0esummary_errors\x18~ \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x34\n\x0fsummary_timeout\x18\x7f \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x36\n\x10summary_warnings\x18\x80\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12/\n\x08sweep_id\x18\x81\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x37\n\x10sweep_param_path\x18\x82\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x07symlink\x18\x84\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\x08sync_dir\x18\x85\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12:\n\x13sync_symlink_latest\x18\x87\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12J\n%table_raise_on_max_row_limit_exceeded\x18\x8a\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\x08timespec\x18\x8b\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x07tmp_dir\x18\x8c\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x30\n\twandb_dir\x18\x8e\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0ex_jupyter_name\x18\x8f\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0ex_jupyter_path\x18\x90\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x08job_name\x18\x91\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValueJ\x04\x08\x03\x10\x04J\x04\x08\x06\x10\x07J\x04\x08\x08\x10\tJ\x04\x08\t\x10\nJ\x04\x08\x0c\x10\rJ\x04\x08\x13\x10\x14J\x04\x08$\x10%J\x04\x08+\x10,J\x04\x08,\x10-J\x04\x08-\x10.J\x04\x08\x32\x10\x33J\x04\x08\x33\x10\x34J\x04\x08\x46\x10GJ\x04\x08[\x10\\J\x04\x08^\x10_J\x04\x08\x64\x10\x65J\x06\x08\x88\x01\x10\x89\x01J\x06\x08\x89\x01\x10\x8a\x01J\x06\x08\xad\x01\x10\xae\x01J\x06\x08\xb0\x01\x10\xb1\x01J\x06\x08\xb4\x01\x10\xb5\x01\x42\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_settings_pb2', _globals)
+if not _descriptor._USE_C_DESCRIPTORS:
+ _globals['DESCRIPTOR']._loaded_options = None
+ _globals['DESCRIPTOR']._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _globals['_MAPSTRINGKEYSTRINGVALUE_VALUEENTRY']._loaded_options = None
+ _globals['_MAPSTRINGKEYSTRINGVALUE_VALUEENTRY']._serialized_options = b'8\001'
+ _globals['_MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY']._loaded_options = None
+ _globals['_MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY']._serialized_options = b'8\001'
+ _globals['_LISTSTRINGVALUE']._serialized_start=84
+ _globals['_LISTSTRINGVALUE']._serialized_end=116
+ _globals['_LISTINTVALUE']._serialized_start=118
+ _globals['_LISTINTVALUE']._serialized_end=147
+ _globals['_MAPSTRINGKEYSTRINGVALUE']._serialized_start=150
+ _globals['_MAPSTRINGKEYSTRINGVALUE']._serialized_end=288
+ _globals['_MAPSTRINGKEYSTRINGVALUE_VALUEENTRY']._serialized_start=244
+ _globals['_MAPSTRINGKEYSTRINGVALUE_VALUEENTRY']._serialized_end=288
+ _globals['_MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE']._serialized_start=291
+ _globals['_MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE']._serialized_end=494
+ _globals['_MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY']._serialized_start=409
+ _globals['_MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY']._serialized_end=494
+ _globals['_OPENMETRICSFILTERS']._serialized_start=497
+ _globals['_OPENMETRICSFILTERS']._serialized_end=651
+ _globals['_RUNMOMENT']._serialized_start=653
+ _globals['_RUNMOMENT']._serialized_end=708
+ _globals['_SETTINGS']._serialized_start=711
+ _globals['_SETTINGS']._serialized_end=10633
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v5/wandb_sync_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v5/wandb_sync_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c43ffc03b0eccd2565e0a05fac3dd8ab13ef82b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v5/wandb_sync_pb2.py
@@ -0,0 +1,43 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: wandb/proto/wandb_sync.proto
+# Protobuf Python Version: 5.26.1
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from wandb.proto import wandb_internal_pb2 as wandb_dot_proto_dot_wandb__internal__pb2
+from wandb.proto import wandb_settings_pb2 as wandb_dot_proto_dot_wandb__settings__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1cwandb/proto/wandb_sync.proto\x12\x0ewandb_internal\x1a wandb/proto/wandb_internal.proto\x1a wandb/proto/wandb_settings.proto\"Q\n\x15ServerInitSyncRequest\x12\x0c\n\x04path\x18\x01 \x03(\t\x12*\n\x08settings\x18\x02 \x01(\x0b\x32\x18.wandb_internal.Settings\"$\n\x16ServerInitSyncResponse\x12\n\n\x02id\x18\x01 \x01(\t\"4\n\x11ServerSyncRequest\x12\n\n\x02id\x18\x01 \x01(\t\x12\x13\n\x0bparallelism\x18\x02 \x01(\r\"I\n\x12ServerSyncResponse\x12\x33\n\x08messages\x18\x01 \x03(\x0b\x32!.wandb_internal.ServerSyncMessage\"%\n\x17ServerSyncStatusRequest\x12\n\n\x02id\x18\x01 \x01(\t\"\x82\x01\n\x18ServerSyncStatusResponse\x12-\n\x05stats\x18\x01 \x01(\x0b\x32\x1e.wandb_internal.OperationStats\x12\x37\n\x0cnew_messages\x18\x02 \x03(\x0b\x32!.wandb_internal.ServerSyncMessage\"\xaa\x01\n\x11ServerSyncMessage\x12<\n\x08severity\x18\x01 \x01(\x0e\x32*.wandb_internal.ServerSyncMessage.Severity\x12\x0f\n\x07\x63ontent\x18\x02 \x01(\t\"F\n\x08Severity\x12\x13\n\x0fSEVERITY_NOTSET\x10\x00\x12\x11\n\rSEVERITY_INFO\x10\x14\x12\x12\n\x0eSEVERITY_ERROR\x10(B\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_sync_pb2', _globals)
+if not _descriptor._USE_C_DESCRIPTORS:
+ _globals['DESCRIPTOR']._loaded_options = None
+ _globals['DESCRIPTOR']._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _globals['_SERVERINITSYNCREQUEST']._serialized_start=116
+ _globals['_SERVERINITSYNCREQUEST']._serialized_end=197
+ _globals['_SERVERINITSYNCRESPONSE']._serialized_start=199
+ _globals['_SERVERINITSYNCRESPONSE']._serialized_end=235
+ _globals['_SERVERSYNCREQUEST']._serialized_start=237
+ _globals['_SERVERSYNCREQUEST']._serialized_end=289
+ _globals['_SERVERSYNCRESPONSE']._serialized_start=291
+ _globals['_SERVERSYNCRESPONSE']._serialized_end=364
+ _globals['_SERVERSYNCSTATUSREQUEST']._serialized_start=366
+ _globals['_SERVERSYNCSTATUSREQUEST']._serialized_end=403
+ _globals['_SERVERSYNCSTATUSRESPONSE']._serialized_start=406
+ _globals['_SERVERSYNCSTATUSRESPONSE']._serialized_end=536
+ _globals['_SERVERSYNCMESSAGE']._serialized_start=539
+ _globals['_SERVERSYNCMESSAGE']._serialized_end=709
+ _globals['_SERVERSYNCMESSAGE_SEVERITY']._serialized_start=639
+ _globals['_SERVERSYNCMESSAGE_SEVERITY']._serialized_end=709
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v5/wandb_telemetry_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v5/wandb_telemetry_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..68389d94aad589a742274f70a4074c4b974ef9bf
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v5/wandb_telemetry_pb2.py
@@ -0,0 +1,42 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: wandb/proto/wandb_telemetry.proto
+# Protobuf Python Version: 5.26.1
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n!wandb/proto/wandb_telemetry.proto\x12\x0ewandb_internal\x1a\x1cwandb/proto/wandb_base.proto\"\xdb\x03\n\x0fTelemetryRecord\x12-\n\x0cimports_init\x18\x01 \x01(\x0b\x32\x17.wandb_internal.Imports\x12/\n\x0eimports_finish\x18\x02 \x01(\x0b\x32\x17.wandb_internal.Imports\x12(\n\x07\x66\x65\x61ture\x18\x03 \x01(\x0b\x32\x17.wandb_internal.Feature\x12\x16\n\x0epython_version\x18\x04 \x01(\t\x12\x13\n\x0b\x63li_version\x18\x05 \x01(\t\x12\x1b\n\x13huggingface_version\x18\x06 \x01(\t\x12 \n\x03\x65nv\x18\x08 \x01(\x0b\x32\x13.wandb_internal.Env\x12%\n\x05label\x18\t \x01(\x0b\x32\x16.wandb_internal.Labels\x12.\n\ndeprecated\x18\n \x01(\x0b\x32\x1a.wandb_internal.Deprecated\x12&\n\x06issues\x18\x0b \x01(\x0b\x32\x16.wandb_internal.Issues\x12\x14\n\x0c\x63ore_version\x18\x0c \x01(\t\x12\x10\n\x08platform\x18\r \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x11\n\x0fTelemetryResult\"\xa8\x0e\n\x07Imports\x12\r\n\x05torch\x18\x01 \x01(\x08\x12\r\n\x05keras\x18\x02 \x01(\x08\x12\x12\n\ntensorflow\x18\x03 \x01(\x08\x12\x0e\n\x06\x66\x61stai\x18\x04 \x01(\x08\x12\x0f\n\x07sklearn\x18\x05 \x01(\x08\x12\x0f\n\x07xgboost\x18\x06 \x01(\x08\x12\x10\n\x08\x63\x61tboost\x18\x07 \x01(\x08\x12\x10\n\x08lightgbm\x18\x08 \x01(\x08\x12\x19\n\x11pytorch_lightning\x18\t \x01(\x08\x12\x0e\n\x06ignite\x18\n \x01(\x08\x12\x14\n\x0ctransformers\x18\x0b \x01(\x08\x12\x0b\n\x03jax\x18\x0c \x01(\x08\x12\x10\n\x08metaflow\x18\r \x01(\x08\x12\x10\n\x08\x61llennlp\x18\x0e \x01(\x08\x12\x11\n\tautogluon\x18\x0f \x01(\x08\x12\x11\n\tautokeras\x18\x10 \x01(\x08\x12\x10\n\x08\x63\x61talyst\x18\x12 \x01(\x08\x12\x10\n\x08\x64\x65\x65pchem\x18\x15 \x01(\x08\x12\x0f\n\x07\x64\x65\x65pctr\x18\x16 \x01(\x08\x12\x0f\n\x07pycaret\x18\x1c \x01(\x08\x12\x14\n\x0cpytorchvideo\x18\x1d \x01(\x08\x12\x0b\n\x03ray\x18\x1e \x01(\x08\x12\x1a\n\x12simpletransformers\x18\x1f \x01(\x08\x12\x0e\n\x06skorch\x18 \x01(\x08\x12\r\n\x05spacy\x18! \x01(\x08\x12\r\n\x05\x66lash\x18\" \x01(\x08\x12\x0e\n\x06optuna\x18# \x01(\x08\x12\x0f\n\x07recbole\x18$ \x01(\x08\x12\x0c\n\x04mmcv\x18% \x01(\x08\x12\r\n\x05mmdet\x18& \x01(\x08\x12\x11\n\ttorchdrug\x18\' \x01(\x08\x12\x11\n\ttorchtext\x18( \x01(\x08\x12\x13\n\x0btorchvision\x18) \x01(\x08\x12\r\n\x05\x65legy\x18* \x01(\x08\x12\x12\n\ndetectron2\x18+ \x01(\x08\x12\r\n\x05\x66lair\x18, \x01(\x08\x12\x0c\n\x04\x66lax\x18- \x01(\x08\x12\x0c\n\x04syft\x18. \x01(\x08\x12\x0b\n\x03TTS\x18/ \x01(\x08\x12\r\n\x05monai\x18\x30 \x01(\x08\x12\x17\n\x0fhuggingface_hub\x18\x31 \x01(\x08\x12\r\n\x05hydra\x18\x32 \x01(\x08\x12\x10\n\x08\x64\x61tasets\x18\x33 \x01(\x08\x12\x0e\n\x06sacred\x18\x34 \x01(\x08\x12\x0e\n\x06joblib\x18\x35 \x01(\x08\x12\x0c\n\x04\x64\x61sk\x18\x36 \x01(\x08\x12\x11\n\tpaddleocr\x18\x38 \x01(\x08\x12\r\n\x05ppdet\x18\x39 \x01(\x08\x12\x11\n\tpaddleseg\x18: \x01(\x08\x12\x11\n\tpaddlenlp\x18; \x01(\x08\x12\r\n\x05mmseg\x18< \x01(\x08\x12\r\n\x05mmocr\x18= \x01(\x08\x12\r\n\x05mmcls\x18> \x01(\x08\x12\x0c\n\x04timm\x18? \x01(\x08\x12\x0f\n\x07\x66\x61irseq\x18@ \x01(\x08\x12\x12\n\ndeepchecks\x18\x41 \x01(\x08\x12\x10\n\x08\x63omposer\x18\x42 \x01(\x08\x12\x10\n\x08sparseml\x18\x43 \x01(\x08\x12\x10\n\x08\x61nomalib\x18\x44 \x01(\x08\x12\r\n\x05zenml\x18\x45 \x01(\x08\x12\x12\n\ncolossalai\x18\x46 \x01(\x08\x12\x12\n\naccelerate\x18G \x01(\x08\x12\x0e\n\x06merlin\x18H \x01(\x08\x12\x0f\n\x07nanodet\x18I \x01(\x08\x12#\n\x1bsegmentation_models_pytorch\x18J \x01(\x08\x12\x1d\n\x15sentence_transformers\x18K \x01(\x08\x12\x0b\n\x03\x64gl\x18L \x01(\x08\x12\x17\n\x0ftorch_geometric\x18M \x01(\x08\x12\x0c\n\x04jina\x18N \x01(\x08\x12\x0e\n\x06kornia\x18O \x01(\x08\x12\x16\n\x0e\x61lbumentations\x18P \x01(\x08\x12\x10\n\x08keras_cv\x18Q \x01(\x08\x12\x10\n\x08mmengine\x18R \x01(\x08\x12\x11\n\tdiffusers\x18S \x01(\x08\x12\x0b\n\x03trl\x18T \x01(\x08\x12\x0c\n\x04trlx\x18U \x01(\x08\x12\x11\n\tlangchain\x18V \x01(\x08\x12\x13\n\x0bllama_index\x18W \x01(\x08\x12\x15\n\rstability_sdk\x18X \x01(\x08\x12\x0f\n\x07prefect\x18Y \x01(\x08\x12\x13\n\x0bprefect_ray\x18Z \x01(\x08\x12\x10\n\x08pinecone\x18[ \x01(\x08\x12\x10\n\x08\x63hromadb\x18\\ \x01(\x08\x12\x10\n\x08weaviate\x18] \x01(\x08\x12\x13\n\x0bpromptlayer\x18^ \x01(\x08\x12\x0e\n\x06openai\x18_ \x01(\x08\x12\x0e\n\x06\x63ohere\x18` \x01(\x08\x12\x11\n\tanthropic\x18\x61 \x01(\x08\x12\x0c\n\x04peft\x18\x62 \x01(\x08\x12\x0f\n\x07optimum\x18\x63 \x01(\x08\x12\x10\n\x08\x65valuate\x18\x64 \x01(\x08\x12\x10\n\x08langflow\x18\x65 \x01(\x08\x12\x12\n\nkeras_core\x18\x66 \x01(\x08\x12\x18\n\x10lightning_fabric\x18g \x01(\x08\x12\x1c\n\x14\x63urated_transformers\x18h \x01(\x08\x12\x0e\n\x06orjson\x18i \x01(\x08\x12\x11\n\tlightning\x18j \x01(\x08\x12\x0c\n\x04\x64spy\x18k \x01(\x08J\x04\x08\x11\x10\x12J\x04\x08\x13\x10\x14J\x04\x08\x14\x10\x15J\x04\x08\x17\x10\x18J\x04\x08\x18\x10\x19J\x04\x08\x19\x10\x1aJ\x04\x08\x1a\x10\x1bJ\x04\x08\x1b\x10\x1cJ\x04\x08\x37\x10\x38\"\xac\r\n\x07\x46\x65\x61ture\x12\r\n\x05watch\x18\x01 \x01(\x08\x12\x0e\n\x06\x66inish\x18\x02 \x01(\x08\x12\x0c\n\x04save\x18\x03 \x01(\x08\x12\x0f\n\x07offline\x18\x04 \x01(\x08\x12\x0f\n\x07resumed\x18\x05 \x01(\x08\x12\x0c\n\x04grpc\x18\x06 \x01(\x08\x12\x0e\n\x06metric\x18\x07 \x01(\x08\x12\r\n\x05keras\x18\x08 \x01(\x08\x12\x11\n\tsagemaker\x18\t \x01(\x08\x12\x1c\n\x14\x61rtifact_incremental\x18\n \x01(\x08\x12\x10\n\x08metaflow\x18\x0b \x01(\x08\x12\x0f\n\x07prodigy\x18\x0c \x01(\x08\x12\x15\n\rset_init_name\x18\r \x01(\x08\x12\x13\n\x0bset_init_id\x18\x0e \x01(\x08\x12\x15\n\rset_init_tags\x18\x0f \x01(\x08\x12\x17\n\x0fset_init_config\x18\x10 \x01(\x08\x12\x14\n\x0cset_run_name\x18\x11 \x01(\x08\x12\x14\n\x0cset_run_tags\x18\x12 \x01(\x08\x12\x17\n\x0fset_config_item\x18\x13 \x01(\x08\x12\x0e\n\x06launch\x18\x14 \x01(\x08\x12\x1c\n\x14torch_profiler_trace\x18\x15 \x01(\x08\x12\x0b\n\x03sb3\x18\x16 \x01(\x08\x12\x17\n\x0finit_return_run\x18\x18 \x01(\x08\x12\x1f\n\x17lightgbm_wandb_callback\x18\x19 \x01(\x08\x12\x1c\n\x14lightgbm_log_summary\x18\x1a \x01(\x08\x12\x1f\n\x17\x63\x61tboost_wandb_callback\x18\x1b \x01(\x08\x12\x1c\n\x14\x63\x61tboost_log_summary\x18\x1c \x01(\x08\x12\x17\n\x0ftensorboard_log\x18\x1d \x01(\x08\x12\x16\n\x0e\x65stimator_hook\x18\x1e \x01(\x08\x12\x1e\n\x16xgboost_wandb_callback\x18\x1f \x01(\x08\x12\"\n\x1axgboost_old_wandb_callback\x18 \x01(\x08\x12\x0e\n\x06\x61ttach\x18! \x01(\x08\x12\x19\n\x11tensorboard_patch\x18\" \x01(\x08\x12\x18\n\x10tensorboard_sync\x18# \x01(\x08\x12\x15\n\rkfp_wandb_log\x18$ \x01(\x08\x12\x1b\n\x13maybe_run_overwrite\x18% \x01(\x08\x12\x1c\n\x14keras_metrics_logger\x18& \x01(\x08\x12\x1e\n\x16keras_model_checkpoint\x18\' \x01(\x08\x12!\n\x19keras_wandb_eval_callback\x18( \x01(\x08\x12\x1d\n\x15\x66low_control_overflow\x18) \x01(\x08\x12\x0c\n\x04sync\x18* \x01(\x08\x12\x1d\n\x15\x66low_control_disabled\x18+ \x01(\x08\x12\x1b\n\x13\x66low_control_custom\x18, \x01(\x08\x12\x14\n\x0copen_metrics\x18. \x01(\x08\x12\x1a\n\x12ultralytics_yolov8\x18/ \x01(\x08\x12\x17\n\x0fimporter_mlflow\x18\x30 \x01(\x08\x12\x15\n\rsync_tfevents\x18\x31 \x01(\x08\x12\x15\n\rasync_uploads\x18\x32 \x01(\x08\x12\x16\n\x0eopenai_autolog\x18\x33 \x01(\x08\x12\x18\n\x10langchain_tracer\x18\x34 \x01(\x08\x12\x16\n\x0e\x63ohere_autolog\x18\x35 \x01(\x08\x12\x1b\n\x13hf_pipeline_autolog\x18\x36 \x01(\x08\x12\r\n\x05lib_c\x18\x38 \x01(\x08\x12\x0f\n\x07lib_cpp\x18\x39 \x01(\x08\x12\x19\n\x11openai_finetuning\x18: \x01(\x08\x12\x19\n\x11\x64iffusers_autolog\x18; \x01(\x08\x12\x1f\n\x17lightning_fabric_logger\x18< \x01(\x08\x12\x14\n\x0cset_step_log\x18= \x01(\x08\x12\x13\n\x0bset_summary\x18> \x01(\x08\x12\x16\n\x0emetric_summary\x18? \x01(\x08\x12\x13\n\x0bmetric_goal\x18@ \x01(\x08\x12\x15\n\rmetric_hidden\x18\x41 \x01(\x08\x12\x18\n\x10metric_step_sync\x18\x42 \x01(\x08\x12\x13\n\x0bshared_mode\x18\x43 \x01(\x08\x12#\n\x1bserver_side_derived_summary\x18\x44 \x01(\x08\x12\x1b\n\x13user_provided_label\x18\x45 \x01(\x08\x12\x1e\n\x16\x64\x63gm_profiling_enabled\x18\x46 \x01(\x08\x12\x11\n\tfork_mode\x18G \x01(\x08\x12\x13\n\x0brewind_mode\x18H \x01(\x08\x12\x15\n\rdspy_callback\x18I \x01(\x08J\x04\x08\x17\x10\x18J\x04\x08-\x10.J\x04\x08\x37\x10\x38\"\xc9\x01\n\x03\x45nv\x12\x0f\n\x07jupyter\x18\x01 \x01(\x08\x12\x0e\n\x06kaggle\x18\x02 \x01(\x08\x12\x0f\n\x07windows\x18\x03 \x01(\x08\x12\x0e\n\x06m1_gpu\x18\x04 \x01(\x08\x12\x10\n\x08trainium\x18\n \x01(\x08\x12\x0b\n\x03pex\x18\x0b \x01(\x08\x12\r\n\x05\x63olab\x18\x0c \x01(\x08\x12\x0f\n\x07ipython\x18\r \x01(\x08\x12\x12\n\naws_lambda\x18\x0e \x01(\x08\x12\x0f\n\x07\x61md_gpu\x18\x0f \x01(\x08J\x04\x08\x05\x10\x06J\x04\x08\x06\x10\x07J\x04\x08\x07\x10\x08J\x04\x08\x08\x10\tJ\x04\x08\t\x10\n\"H\n\x06Labels\x12\x13\n\x0b\x63ode_string\x18\x01 \x01(\t\x12\x13\n\x0brepo_string\x18\x02 \x01(\t\x12\x14\n\x0c\x63ode_version\x18\x03 \x01(\t\"\xc2\x06\n\nDeprecated\x12!\n\x19keras_callback__data_type\x18\x01 \x01(\x08\x12\r\n\x05plots\x18\x05 \x01(\x08\x12!\n\x19init__config_include_keys\x18\x07 \x01(\x08\x12!\n\x19init__config_exclude_keys\x18\x08 \x01(\x08\x12\"\n\x1akeras_callback__save_model\x18\t \x01(\x08\x12\x18\n\x10langchain_tracer\x18\n \x01(\x08\x12\x1a\n\x12\x61rtifact__get_path\x18\x0b \x01(\x08\x12#\n\x1b\x61rtifactmanifestentry__name\x18\x0c \x01(\x08\x12\x1e\n\x16\x61pi__artifact_versions\x18\r \x01(\x08\x12(\n artifact_collection__change_type\x18\x0e \x01(\x08\x12\x1f\n\x17run__define_metric_copy\x18\x0f \x01(\x08\x12\x14\n\x0crun_disabled\x18\x10 \x01(\x08\x12\x16\n\x0ekeras_callback\x18\x11 \x01(\x08\x12$\n\x1crun__define_metric_best_goal\x18\x12 \x01(\x08\x12\x19\n\x11run__finish_quiet\x18\x13 \x01(\x08\x12\x18\n\x10run__reinit_bool\x18\x14 \x01(\x08\x12\x14\n\x0crun__get_url\x18\x15 \x01(\x08\x12\x19\n\x11run__project_name\x18\x16 \x01(\x08\x12\x1c\n\x14run__get_project_url\x18\x17 \x01(\x08\x12\x1a\n\x12run__get_sweep_url\x18\x18 \x01(\x08\x12 \n\x18run__use_artifact_use_as\x18\x19 \x01(\x08\x12\x18\n\x10\x61rtifact__use_as\x18\x1a \x01(\x08\x12\x1d\n\x15\x61rtifact__init_use_as\x18\x1b \x01(\x08\x12\"\n\x1a\x62\x65ta__workflows__log_model\x18\x1c \x01(\x08\x12\"\n\x1a\x62\x65ta__workflows__use_model\x18\x1d \x01(\x08\x12#\n\x1b\x62\x65ta__workflows__link_model\x18\x1e \x01(\x08J\x04\x08\x02\x10\x03J\x04\x08\x03\x10\x04J\x04\x08\x04\x10\x05J\x04\x08\x06\x10\x07\"|\n\x06Issues\x12%\n\x1dsettings__validation_warnings\x18\x01 \x01(\x08\x12!\n\x19settings__unexpected_args\x18\x02 \x01(\x08\x12(\n settings__preprocessing_warnings\x18\x03 \x01(\x08\x42\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_telemetry_pb2', _globals)
+if not _descriptor._USE_C_DESCRIPTORS:
+ _globals['DESCRIPTOR']._loaded_options = None
+ _globals['DESCRIPTOR']._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _globals['_TELEMETRYRECORD']._serialized_start=84
+ _globals['_TELEMETRYRECORD']._serialized_end=559
+ _globals['_TELEMETRYRESULT']._serialized_start=561
+ _globals['_TELEMETRYRESULT']._serialized_end=578
+ _globals['_IMPORTS']._serialized_start=581
+ _globals['_IMPORTS']._serialized_end=2413
+ _globals['_FEATURE']._serialized_start=2416
+ _globals['_FEATURE']._serialized_end=4124
+ _globals['_ENV']._serialized_start=4127
+ _globals['_ENV']._serialized_end=4328
+ _globals['_LABELS']._serialized_start=4330
+ _globals['_LABELS']._serialized_end=4402
+ _globals['_DEPRECATED']._serialized_start=4405
+ _globals['_DEPRECATED']._serialized_end=5239
+ _globals['_ISSUES']._serialized_start=5241
+ _globals['_ISSUES']._serialized_end=5365
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v6/wandb_api_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v6/wandb_api_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc767298a44cfe245266ffe38c020a299c6d639e
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v6/wandb_api_pb2.py
@@ -0,0 +1,48 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# NO CHECKED-IN PROTOBUF GENCODE
+# source: wandb/proto/wandb_api.proto
+# Protobuf Python Version: 6.31.1
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import runtime_version as _runtime_version
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+_runtime_version.ValidateProtobufRuntimeVersion(
+ _runtime_version.Domain.PUBLIC,
+ 6,
+ 31,
+ 1,
+ '',
+ 'wandb/proto/wandb_api.proto'
+)
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1bwandb/proto/wandb_api.proto\x12\x0ewandb_internal\x1a\x1cwandb/proto/wandb_base.proto\"]\n\nApiRequest\x12\x44\n\x10read_run_history\x18\x01 \x01(\x0b\x32(.wandb_internal.ReadRunHistoryApiRequestH\x00\x42\t\n\x07request\"`\n\x0b\x41piResponse\x12\x45\n\x10read_run_history\x18\x01 \x01(\x0b\x32).wandb_internal.ReadRunHistoryApiResponseH\x00\x42\n\n\x08response\"\xaa\x01\n\x18ReadRunHistoryApiRequest\x12\x0e\n\x06\x65ntity\x18\x01 \x01(\t\x12\x0f\n\x07project\x18\x02 \x01(\t\x12\x0e\n\x06run_id\x18\x03 \x01(\t\x12\x0c\n\x04keys\x18\x04 \x03(\t\x12\x10\n\x08min_step\x18\x05 \x01(\x03\x12\x10\n\x08max_step\x18\x06 \x01(\x03\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"d\n\x19ReadRunHistoryApiResponse\x12\x30\n\x0chistory_rows\x18\x01 \x03(\x0b\x32\x1a.wandb_internal.HistoryRow\x12\x15\n\rerror_message\x18\x02 \x01(\t\"G\n\nHistoryRow\x12\x39\n\rhistory_items\x18\x01 \x03(\x0b\x32\".wandb_internal.ParquetHistoryItem\"5\n\x12ParquetHistoryItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\tB\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_api_pb2', _globals)
+if not _descriptor._USE_C_DESCRIPTORS:
+ _globals['DESCRIPTOR']._loaded_options = None
+ _globals['DESCRIPTOR']._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _globals['_APIREQUEST']._serialized_start=77
+ _globals['_APIREQUEST']._serialized_end=170
+ _globals['_APIRESPONSE']._serialized_start=172
+ _globals['_APIRESPONSE']._serialized_end=268
+ _globals['_READRUNHISTORYAPIREQUEST']._serialized_start=271
+ _globals['_READRUNHISTORYAPIREQUEST']._serialized_end=441
+ _globals['_READRUNHISTORYAPIRESPONSE']._serialized_start=443
+ _globals['_READRUNHISTORYAPIRESPONSE']._serialized_end=543
+ _globals['_HISTORYROW']._serialized_start=545
+ _globals['_HISTORYROW']._serialized_end=616
+ _globals['_PARQUETHISTORYITEM']._serialized_start=618
+ _globals['_PARQUETHISTORYITEM']._serialized_end=671
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v6/wandb_base_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v6/wandb_base_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..31678f20d64c9fb9cc6112d6e66917059df2b152
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v6/wandb_base_pb2.py
@@ -0,0 +1,41 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# NO CHECKED-IN PROTOBUF GENCODE
+# source: wandb/proto/wandb_base.proto
+# Protobuf Python Version: 6.31.1
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import runtime_version as _runtime_version
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+_runtime_version.ValidateProtobufRuntimeVersion(
+ _runtime_version.Domain.PUBLIC,
+ 6,
+ 31,
+ 1,
+ '',
+ 'wandb/proto/wandb_base.proto'
+)
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1cwandb/proto/wandb_base.proto\x12\x0ewandb_internal\"6\n\x0b_RecordInfo\x12\x11\n\tstream_id\x18\x01 \x01(\t\x12\x14\n\x0c_tracelog_id\x18\x64 \x01(\t\"!\n\x0c_RequestInfo\x12\x11\n\tstream_id\x18\x01 \x01(\t\"#\n\x0b_ResultInfo\x12\x14\n\x0c_tracelog_id\x18\x64 \x01(\tB\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_base_pb2', _globals)
+if not _descriptor._USE_C_DESCRIPTORS:
+ _globals['DESCRIPTOR']._loaded_options = None
+ _globals['DESCRIPTOR']._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _globals['__RECORDINFO']._serialized_start=48
+ _globals['__RECORDINFO']._serialized_end=102
+ _globals['__REQUESTINFO']._serialized_start=104
+ _globals['__REQUESTINFO']._serialized_end=137
+ _globals['__RESULTINFO']._serialized_start=139
+ _globals['__RESULTINFO']._serialized_end=174
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v6/wandb_internal_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v6/wandb_internal_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..59f3323ca5ccd5977f3920e0d70e8028ae5dc5ef
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v6/wandb_internal_pb2.py
@@ -0,0 +1,396 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# NO CHECKED-IN PROTOBUF GENCODE
+# source: wandb/proto/wandb_internal.proto
+# Protobuf Python Version: 6.31.1
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import runtime_version as _runtime_version
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+_runtime_version.ValidateProtobufRuntimeVersion(
+ _runtime_version.Domain.PUBLIC,
+ 6,
+ 31,
+ 1,
+ '',
+ 'wandb/proto/wandb_internal.proto'
+)
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
+from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
+from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2
+from wandb.proto import wandb_telemetry_pb2 as wandb_dot_proto_dot_wandb__telemetry__pb2
+from wandb.proto import wandb_api_pb2 as wandb_dot_proto_dot_wandb__api__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n wandb/proto/wandb_internal.proto\x12\x0ewandb_internal\x1a\x1bgoogle/protobuf/empty.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1cwandb/proto/wandb_base.proto\x1a!wandb/proto/wandb_telemetry.proto\x1a\x1bwandb/proto/wandb_api.proto\"\x82\n\n\x06Record\x12\x0b\n\x03num\x18\x01 \x01(\x03\x12\x30\n\x07history\x18\x02 \x01(\x0b\x32\x1d.wandb_internal.HistoryRecordH\x00\x12\x30\n\x07summary\x18\x03 \x01(\x0b\x32\x1d.wandb_internal.SummaryRecordH\x00\x12.\n\x06output\x18\x04 \x01(\x0b\x32\x1c.wandb_internal.OutputRecordH\x00\x12.\n\x06\x63onfig\x18\x05 \x01(\x0b\x32\x1c.wandb_internal.ConfigRecordH\x00\x12,\n\x05\x66iles\x18\x06 \x01(\x0b\x32\x1b.wandb_internal.FilesRecordH\x00\x12,\n\x05stats\x18\x07 \x01(\x0b\x32\x1b.wandb_internal.StatsRecordH\x00\x12\x32\n\x08\x61rtifact\x18\x08 \x01(\x0b\x32\x1e.wandb_internal.ArtifactRecordH\x00\x12,\n\x08tbrecord\x18\t \x01(\x0b\x32\x18.wandb_internal.TBRecordH\x00\x12,\n\x05\x61lert\x18\n \x01(\x0b\x32\x1b.wandb_internal.AlertRecordH\x00\x12\x34\n\ttelemetry\x18\x0b \x01(\x0b\x32\x1f.wandb_internal.TelemetryRecordH\x00\x12.\n\x06metric\x18\x0c \x01(\x0b\x32\x1c.wandb_internal.MetricRecordH\x00\x12\x35\n\noutput_raw\x18\r \x01(\x0b\x32\x1f.wandb_internal.OutputRawRecordH\x00\x12(\n\x03run\x18\x11 \x01(\x0b\x32\x19.wandb_internal.RunRecordH\x00\x12-\n\x04\x65xit\x18\x12 \x01(\x0b\x32\x1d.wandb_internal.RunExitRecordH\x00\x12,\n\x05\x66inal\x18\x14 \x01(\x0b\x32\x1b.wandb_internal.FinalRecordH\x00\x12.\n\x06header\x18\x15 \x01(\x0b\x32\x1c.wandb_internal.HeaderRecordH\x00\x12.\n\x06\x66ooter\x18\x16 \x01(\x0b\x32\x1c.wandb_internal.FooterRecordH\x00\x12\x39\n\npreempting\x18\x17 \x01(\x0b\x32#.wandb_internal.RunPreemptingRecordH\x00\x12\x34\n\x12noop_link_artifact\x18\x18 \x01(\x0b\x32\x16.google.protobuf.EmptyH\x00\x12\x39\n\x0cuse_artifact\x18\x19 \x01(\x0b\x32!.wandb_internal.UseArtifactRecordH\x00\x12\x38\n\x0b\x65nvironment\x18\x1a \x01(\x0b\x32!.wandb_internal.EnvironmentRecordH\x00\x12*\n\x07request\x18\x64 \x01(\x0b\x32\x17.wandb_internal.RequestH\x00\x12\x31\n\x0b\x61pi_request\x18\x65 \x01(\x0b\x32\x1a.wandb_internal.ApiRequestH\x00\x12(\n\x07\x63ontrol\x18\x10 \x01(\x0b\x32\x17.wandb_internal.Control\x12\x0c\n\x04uuid\x18\x13 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfoB\r\n\x0brecord_type\"\xa8\x01\n\x07\x43ontrol\x12\x10\n\x08req_resp\x18\x01 \x01(\x08\x12\r\n\x05local\x18\x02 \x01(\x08\x12\x10\n\x08relay_id\x18\x03 \x01(\t\x12\x14\n\x0cmailbox_slot\x18\x04 \x01(\t\x12\x13\n\x0b\x61lways_send\x18\x05 \x01(\x08\x12\x14\n\x0c\x66low_control\x18\x06 \x01(\x08\x12\x12\n\nend_offset\x18\x07 \x01(\x03\x12\x15\n\rconnection_id\x18\x08 \x01(\t\"\xf3\x03\n\x06Result\x12\x35\n\nrun_result\x18\x11 \x01(\x0b\x32\x1f.wandb_internal.RunUpdateResultH\x00\x12\x34\n\x0b\x65xit_result\x18\x12 \x01(\x0b\x32\x1d.wandb_internal.RunExitResultH\x00\x12\x33\n\nlog_result\x18\x14 \x01(\x0b\x32\x1d.wandb_internal.HistoryResultH\x00\x12\x37\n\x0esummary_result\x18\x15 \x01(\x0b\x32\x1d.wandb_internal.SummaryResultH\x00\x12\x35\n\routput_result\x18\x16 \x01(\x0b\x32\x1c.wandb_internal.OutputResultH\x00\x12\x35\n\rconfig_result\x18\x17 \x01(\x0b\x32\x1c.wandb_internal.ConfigResultH\x00\x12,\n\x08response\x18\x64 \x01(\x0b\x32\x18.wandb_internal.ResponseH\x00\x12(\n\x07\x63ontrol\x18\x10 \x01(\x0b\x32\x17.wandb_internal.Control\x12\x0c\n\x04uuid\x18\x18 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._ResultInfoB\r\n\x0bresult_type\":\n\x0b\x46inalRecord\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"b\n\x0bVersionInfo\x12\x10\n\x08producer\x18\x01 \x01(\t\x12\x14\n\x0cmin_consumer\x18\x02 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"n\n\x0cHeaderRecord\x12\x31\n\x0cversion_info\x18\x01 \x01(\x0b\x32\x1b.wandb_internal.VersionInfo\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\";\n\x0c\x46ooterRecord\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"9\n\x0b\x42ranchPoint\x12\x0b\n\x03run\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x01\x12\x0e\n\x06metric\x18\x03 \x01(\t\"\x91\x05\n\tRunRecord\x12\x0e\n\x06run_id\x18\x01 \x01(\t\x12\x0e\n\x06\x65ntity\x18\x02 \x01(\t\x12\x0f\n\x07project\x18\x03 \x01(\t\x12,\n\x06\x63onfig\x18\x04 \x01(\x0b\x32\x1c.wandb_internal.ConfigRecord\x12.\n\x07summary\x18\x05 \x01(\x0b\x32\x1d.wandb_internal.SummaryRecord\x12\x11\n\trun_group\x18\x06 \x01(\t\x12\x10\n\x08job_type\x18\x07 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x08 \x01(\t\x12\r\n\x05notes\x18\t \x01(\t\x12\x0c\n\x04tags\x18\n \x03(\t\x12\x30\n\x08settings\x18\x0b \x01(\x0b\x32\x1e.wandb_internal.SettingsRecord\x12\x10\n\x08sweep_id\x18\x0c \x01(\t\x12\x0c\n\x04host\x18\r \x01(\t\x12\x15\n\rstarting_step\x18\x0e \x01(\x03\x12\x12\n\nstorage_id\x18\x10 \x01(\t\x12.\n\nstart_time\x18\x11 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07resumed\x18\x12 \x01(\x08\x12\x32\n\ttelemetry\x18\x13 \x01(\x0b\x32\x1f.wandb_internal.TelemetryRecord\x12\x0f\n\x07runtime\x18\x14 \x01(\x05\x12*\n\x03git\x18\x15 \x01(\x0b\x32\x1d.wandb_internal.GitRepoRecord\x12\x0e\n\x06\x66orked\x18\x16 \x01(\x08\x12\x31\n\x0c\x62ranch_point\x18\x17 \x01(\x0b\x32\x1b.wandb_internal.BranchPoint\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\";\n\rGitRepoRecord\x12\x1a\n\nremote_url\x18\x01 \x01(\tR\x06remote\x12\x0e\n\x06\x63ommit\x18\x02 \x01(\t\"c\n\x0fRunUpdateResult\x12&\n\x03run\x18\x01 \x01(\x0b\x32\x19.wandb_internal.RunRecord\x12(\n\x05\x65rror\x18\x02 \x01(\x0b\x32\x19.wandb_internal.ErrorInfo\"\xac\x01\n\tErrorInfo\x12\x0f\n\x07message\x18\x01 \x01(\t\x12\x31\n\x04\x63ode\x18\x02 \x01(\x0e\x32#.wandb_internal.ErrorInfo.ErrorCode\"[\n\tErrorCode\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x11\n\rCOMMUNICATION\x10\x01\x12\x12\n\x0e\x41UTHENTICATION\x10\x02\x12\t\n\x05USAGE\x10\x03\x12\x0f\n\x0bUNSUPPORTED\x10\x04\"`\n\rRunExitRecord\x12\x11\n\texit_code\x18\x01 \x01(\x05\x12\x0f\n\x07runtime\x18\x02 \x01(\x05\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x0f\n\rRunExitResult\"B\n\x13RunPreemptingRecord\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x15\n\x13RunPreemptingResult\"i\n\x0eSettingsRecord\x12*\n\x04item\x18\x01 \x03(\x0b\x32\x1c.wandb_internal.SettingsItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"/\n\x0cSettingsItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\x1a\n\x0bHistoryStep\x12\x0b\n\x03num\x18\x01 \x01(\x03\"\x92\x01\n\rHistoryRecord\x12)\n\x04item\x18\x01 \x03(\x0b\x32\x1b.wandb_internal.HistoryItem\x12)\n\x04step\x18\x02 \x01(\x0b\x32\x1b.wandb_internal.HistoryStep\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"B\n\x0bHistoryItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nnested_key\x18\x02 \x03(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\x0f\n\rHistoryResult\"\xdc\x01\n\x0cOutputRecord\x12<\n\x0boutput_type\x18\x01 \x01(\x0e\x32\'.wandb_internal.OutputRecord.OutputType\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0c\n\x04line\x18\x03 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"$\n\nOutputType\x12\n\n\x06STDERR\x10\x00\x12\n\n\x06STDOUT\x10\x01\"\x0e\n\x0cOutputResult\"\xe2\x01\n\x0fOutputRawRecord\x12?\n\x0boutput_type\x18\x01 \x01(\x0e\x32*.wandb_internal.OutputRawRecord.OutputType\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0c\n\x04line\x18\x03 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"$\n\nOutputType\x12\n\n\x06STDERR\x10\x00\x12\n\n\x06STDOUT\x10\x01\"\x11\n\x0fOutputRawResult\"\xb4\x03\n\x0cMetricRecord\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x11\n\tglob_name\x18\x02 \x01(\t\x12\x13\n\x0bstep_metric\x18\x04 \x01(\t\x12\x19\n\x11step_metric_index\x18\x05 \x01(\x05\x12.\n\x07options\x18\x06 \x01(\x0b\x32\x1d.wandb_internal.MetricOptions\x12.\n\x07summary\x18\x07 \x01(\x0b\x32\x1d.wandb_internal.MetricSummary\x12\x35\n\x04goal\x18\x08 \x01(\x0e\x32\'.wandb_internal.MetricRecord.MetricGoal\x12/\n\x08_control\x18\t \x01(\x0b\x32\x1d.wandb_internal.MetricControl\x12\x1a\n\x12\x65xpanded_from_glob\x18\n \x01(\x08\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"B\n\nMetricGoal\x12\x0e\n\nGOAL_UNSET\x10\x00\x12\x11\n\rGOAL_MINIMIZE\x10\x01\x12\x11\n\rGOAL_MAXIMIZE\x10\x02\"\x0e\n\x0cMetricResult\"C\n\rMetricOptions\x12\x11\n\tstep_sync\x18\x01 \x01(\x08\x12\x0e\n\x06hidden\x18\x02 \x01(\x08\x12\x0f\n\x07\x64\x65\x66ined\x18\x03 \x01(\x08\"\"\n\rMetricControl\x12\x11\n\toverwrite\x18\x01 \x01(\x08\"~\n\rMetricSummary\x12\x0b\n\x03min\x18\x01 \x01(\x08\x12\x0b\n\x03max\x18\x02 \x01(\x08\x12\x0c\n\x04mean\x18\x03 \x01(\x08\x12\x0c\n\x04\x62\x65st\x18\x04 \x01(\x08\x12\x0c\n\x04last\x18\x05 \x01(\x08\x12\x0c\n\x04none\x18\x06 \x01(\x08\x12\x0c\n\x04\x63opy\x18\x07 \x01(\x08\x12\r\n\x05\x66irst\x18\x08 \x01(\x08\"\x93\x01\n\x0c\x43onfigRecord\x12*\n\x06update\x18\x01 \x03(\x0b\x32\x1a.wandb_internal.ConfigItem\x12*\n\x06remove\x18\x02 \x03(\x0b\x32\x1a.wandb_internal.ConfigItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"A\n\nConfigItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nnested_key\x18\x02 \x03(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\x0e\n\x0c\x43onfigResult\"\x96\x01\n\rSummaryRecord\x12+\n\x06update\x18\x01 \x03(\x0b\x32\x1b.wandb_internal.SummaryItem\x12+\n\x06remove\x18\x02 \x03(\x0b\x32\x1b.wandb_internal.SummaryItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"B\n\x0bSummaryItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nnested_key\x18\x02 \x03(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\x0f\n\rSummaryResult\"d\n\x0b\x46ilesRecord\x12(\n\x05\x66iles\x18\x01 \x03(\x0b\x32\x19.wandb_internal.FilesItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\xec\x01\n\tFilesItem\x12\x0c\n\x04path\x18\x01 \x01(\t\x12\x34\n\x06policy\x18\x02 \x01(\x0e\x32$.wandb_internal.FilesItem.PolicyType\x12\x30\n\x04type\x18\x03 \x01(\x0e\x32\".wandb_internal.FilesItem.FileType\"(\n\nPolicyType\x12\x07\n\x03NOW\x10\x00\x12\x07\n\x03\x45ND\x10\x01\x12\x08\n\x04LIVE\x10\x02\"9\n\x08\x46ileType\x12\t\n\x05OTHER\x10\x00\x12\t\n\x05WANDB\x10\x01\x12\t\n\x05MEDIA\x10\x02\x12\x0c\n\x08\x41RTIFACT\x10\x03J\x04\x08\x10\x10\x11\"\r\n\x0b\x46ilesResult\"\xe6\x01\n\x0bStatsRecord\x12\x39\n\nstats_type\x18\x01 \x01(\x0e\x32%.wandb_internal.StatsRecord.StatsType\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\'\n\x04item\x18\x03 \x03(\x0b\x32\x19.wandb_internal.StatsItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x17\n\tStatsType\x12\n\n\x06SYSTEM\x10\x00\",\n\tStatsItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\xe7\x03\n\x0e\x41rtifactRecord\x12\x0e\n\x06run_id\x18\x01 \x01(\t\x12\x0f\n\x07project\x18\x02 \x01(\t\x12\x0e\n\x06\x65ntity\x18\x03 \x01(\t\x12\x0c\n\x04type\x18\x04 \x01(\t\x12\x0c\n\x04name\x18\x05 \x01(\t\x12\x0e\n\x06\x64igest\x18\x06 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x07 \x01(\t\x12\x10\n\x08metadata\x18\x08 \x01(\t\x12\x14\n\x0cuser_created\x18\t \x01(\x08\x12\x18\n\x10use_after_commit\x18\n \x01(\x08\x12\x0f\n\x07\x61liases\x18\x0b \x03(\t\x12\x32\n\x08manifest\x18\x0c \x01(\x0b\x32 .wandb_internal.ArtifactManifest\x12\x16\n\x0e\x64istributed_id\x18\r \x01(\t\x12\x10\n\x08\x66inalize\x18\x0e \x01(\x08\x12\x11\n\tclient_id\x18\x0f \x01(\t\x12\x1a\n\x12sequence_client_id\x18\x10 \x01(\t\x12\x0f\n\x07\x62\x61se_id\x18\x11 \x01(\t\x12\x1c\n\x14ttl_duration_seconds\x18\x12 \x01(\x03\x12\x0c\n\x04tags\x18\x13 \x03(\t\x12\x19\n\x11incremental_beta1\x18\x64 \x01(\x08\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\xd8\x01\n\x10\x41rtifactManifest\x12\x0f\n\x07version\x18\x01 \x01(\x05\x12\x16\n\x0estorage_policy\x18\x02 \x01(\t\x12\x46\n\x15storage_policy_config\x18\x03 \x03(\x0b\x32\'.wandb_internal.StoragePolicyConfigItem\x12\x37\n\x08\x63ontents\x18\x04 \x03(\x0b\x32%.wandb_internal.ArtifactManifestEntry\x12\x1a\n\x12manifest_file_path\x18\x05 \x01(\t\"\xcf\x01\n\x15\x41rtifactManifestEntry\x12\x0c\n\x04path\x18\x01 \x01(\t\x12\x0e\n\x06\x64igest\x18\x02 \x01(\t\x12\x0b\n\x03ref\x18\x03 \x01(\t\x12\x0c\n\x04size\x18\x04 \x01(\x03\x12\x10\n\x08mimetype\x18\x05 \x01(\t\x12\x12\n\nlocal_path\x18\x06 \x01(\t\x12\x19\n\x11\x62irth_artifact_id\x18\x07 \x01(\t\x12\x12\n\nskip_cache\x18\x08 \x01(\x08\x12(\n\x05\x65xtra\x18\x10 \x03(\x0b\x32\x19.wandb_internal.ExtraItem\",\n\tExtraItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x02 \x01(\t\":\n\x17StoragePolicyConfigItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x02 \x01(\t\"\x10\n\x0e\x41rtifactResult\"\x14\n\x12LinkArtifactResult\"\xf0\x01\n\x13LinkArtifactRequest\x12\x11\n\tclient_id\x18\x01 \x01(\t\x12\x11\n\tserver_id\x18\x02 \x01(\t\x12\x16\n\x0eportfolio_name\x18\x03 \x01(\t\x12\x18\n\x10portfolio_entity\x18\x04 \x01(\t\x12\x19\n\x11portfolio_project\x18\x05 \x01(\t\x12\x19\n\x11portfolio_aliases\x18\x06 \x03(\t\x12\x1e\n\x16portfolio_organization\x18\x07 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"[\n\x14LinkArtifactResponse\x12\x15\n\rerror_message\x18\x01 \x01(\t\x12\x1a\n\rversion_index\x18\x02 \x01(\x05H\x00\x88\x01\x01\x42\x10\n\x0e_version_index\"h\n\x08TBRecord\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\x12\x0f\n\x07log_dir\x18\x01 \x01(\t\x12\x10\n\x08root_dir\x18\x03 \x01(\t\x12\x0c\n\x04save\x18\x02 \x01(\x08\"\n\n\x08TBResult\"}\n\x0b\x41lertRecord\x12\r\n\x05title\x18\x01 \x01(\t\x12\x0c\n\x04text\x18\x02 \x01(\t\x12\r\n\x05level\x18\x03 \x01(\t\x12\x15\n\rwait_duration\x18\x04 \x01(\x03\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\r\n\x0b\x41lertResult\"\xf8\x11\n\x07Request\x12\x38\n\x0bstop_status\x18\x01 \x01(\x0b\x32!.wandb_internal.StopStatusRequestH\x00\x12>\n\x0enetwork_status\x18\x02 \x01(\x0b\x32$.wandb_internal.NetworkStatusRequestH\x00\x12-\n\x05\x64\x65\x66\x65r\x18\x03 \x01(\x0b\x32\x1c.wandb_internal.DeferRequestH\x00\x12\x38\n\x0bget_summary\x18\x04 \x01(\x0b\x32!.wandb_internal.GetSummaryRequestH\x00\x12-\n\x05login\x18\x05 \x01(\x0b\x32\x1c.wandb_internal.LoginRequestH\x00\x12-\n\x05pause\x18\x06 \x01(\x0b\x32\x1c.wandb_internal.PauseRequestH\x00\x12/\n\x06resume\x18\x07 \x01(\x0b\x32\x1d.wandb_internal.ResumeRequestH\x00\x12\x34\n\tpoll_exit\x18\x08 \x01(\x0b\x32\x1f.wandb_internal.PollExitRequestH\x00\x12@\n\x0fsampled_history\x18\t \x01(\x0b\x32%.wandb_internal.SampledHistoryRequestH\x00\x12@\n\x0fpartial_history\x18\n \x01(\x0b\x32%.wandb_internal.PartialHistoryRequestH\x00\x12\x34\n\trun_start\x18\x0b \x01(\x0b\x32\x1f.wandb_internal.RunStartRequestH\x00\x12<\n\rcheck_version\x18\x0c \x01(\x0b\x32#.wandb_internal.CheckVersionRequestH\x00\x12:\n\x0clog_artifact\x18\r \x01(\x0b\x32\".wandb_internal.LogArtifactRequestH\x00\x12\x44\n\x11\x64ownload_artifact\x18\x0e \x01(\x0b\x32\'.wandb_internal.DownloadArtifactRequestH\x00\x12\x35\n\tkeepalive\x18\x11 \x01(\x0b\x32 .wandb_internal.KeepaliveRequestH\x00\x12>\n\x0eserver_feature\x18\x12 \x01(\x0b\x32$.wandb_internal.ServerFeatureRequestH\x00\x12\x36\n\nrun_status\x18\x14 \x01(\x0b\x32 .wandb_internal.RunStatusRequestH\x00\x12/\n\x06\x63\x61ncel\x18\x15 \x01(\x0b\x32\x1d.wandb_internal.CancelRequestH\x00\x12\x44\n\x11internal_messages\x18\x17 \x01(\x0b\x32\'.wandb_internal.InternalMessagesRequestH\x00\x12@\n\x0fpython_packages\x18\x18 \x01(\x0b\x32%.wandb_internal.PythonPackagesRequestH\x00\x12\x33\n\x08shutdown\x18@ \x01(\x0b\x32\x1f.wandb_internal.ShutdownRequestH\x00\x12/\n\x06\x61ttach\x18\x41 \x01(\x0b\x32\x1d.wandb_internal.AttachRequestH\x00\x12/\n\x06status\x18\x42 \x01(\x0b\x32\x1d.wandb_internal.StatusRequestH\x00\x12\x38\n\x0bserver_info\x18\x43 \x01(\x0b\x32!.wandb_internal.ServerInfoRequestH\x00\x12\x38\n\x0bsender_mark\x18\x44 \x01(\x0b\x32!.wandb_internal.SenderMarkRequestH\x00\x12\x38\n\x0bsender_read\x18\x45 \x01(\x0b\x32!.wandb_internal.SenderReadRequestH\x00\x12<\n\rstatus_report\x18\x46 \x01(\x0b\x32#.wandb_internal.StatusReportRequestH\x00\x12>\n\x0esummary_record\x18G \x01(\x0b\x32$.wandb_internal.SummaryRecordRequestH\x00\x12\x42\n\x10telemetry_record\x18H \x01(\x0b\x32&.wandb_internal.TelemetryRecordRequestH\x00\x12\x32\n\x08job_info\x18I \x01(\x0b\x32\x1e.wandb_internal.JobInfoRequestH\x00\x12\x45\n\x12get_system_metrics\x18J \x01(\x0b\x32\'.wandb_internal.GetSystemMetricsRequestH\x00\x12\x34\n\tjob_input\x18M \x01(\x0b\x32\x1f.wandb_internal.JobInputRequestH\x00\x12<\n\rlink_artifact\x18N \x01(\x0b\x32#.wandb_internal.LinkArtifactRequestH\x00\x12N\n\x17run_finish_without_exit\x18O \x01(\x0b\x32+.wandb_internal.RunFinishWithoutExitRequestH\x00\x12\x38\n\x0bsync_finish\x18Q \x01(\x0b\x32!.wandb_internal.SyncFinishRequestH\x00\x12;\n\noperations\x18R \x01(\x0b\x32%.wandb_internal.OperationStatsRequestH\x00\x12\x43\n\x11probe_system_info\x18S \x01(\x0b\x32&.wandb_internal.ProbeSystemInfoRequestH\x00\x12\x39\n\x0btest_inject\x18\xe8\x07 \x01(\x0b\x32!.wandb_internal.TestInjectRequestH\x00\x42\x0e\n\x0crequest_typeJ\x04\x08\x16\x10\x17J\x04\x08K\x10LJ\x04\x08L\x10MJ\x04\x08P\x10Q\"\xd0\x0e\n\x08Response\x12?\n\x12keepalive_response\x18\x12 \x01(\x0b\x32!.wandb_internal.KeepaliveResponseH\x00\x12\x42\n\x14stop_status_response\x18\x13 \x01(\x0b\x32\".wandb_internal.StopStatusResponseH\x00\x12H\n\x17network_status_response\x18\x14 \x01(\x0b\x32%.wandb_internal.NetworkStatusResponseH\x00\x12\x37\n\x0elogin_response\x18\x18 \x01(\x0b\x32\x1d.wandb_internal.LoginResponseH\x00\x12\x42\n\x14get_summary_response\x18\x19 \x01(\x0b\x32\".wandb_internal.GetSummaryResponseH\x00\x12>\n\x12poll_exit_response\x18\x1a \x01(\x0b\x32 .wandb_internal.PollExitResponseH\x00\x12J\n\x18sampled_history_response\x18\x1b \x01(\x0b\x32&.wandb_internal.SampledHistoryResponseH\x00\x12>\n\x12run_start_response\x18\x1c \x01(\x0b\x32 .wandb_internal.RunStartResponseH\x00\x12\x46\n\x16\x63heck_version_response\x18\x1d \x01(\x0b\x32$.wandb_internal.CheckVersionResponseH\x00\x12\x44\n\x15log_artifact_response\x18\x1e \x01(\x0b\x32#.wandb_internal.LogArtifactResponseH\x00\x12N\n\x1a\x64ownload_artifact_response\x18\x1f \x01(\x0b\x32(.wandb_internal.DownloadArtifactResponseH\x00\x12H\n\x17server_feature_response\x18 \x01(\x0b\x32%.wandb_internal.ServerFeatureResponseH\x00\x12@\n\x13run_status_response\x18# \x01(\x0b\x32!.wandb_internal.RunStatusResponseH\x00\x12\x39\n\x0f\x63\x61ncel_response\x18$ \x01(\x0b\x32\x1e.wandb_internal.CancelResponseH\x00\x12N\n\x1ainternal_messages_response\x18% \x01(\x0b\x32(.wandb_internal.InternalMessagesResponseH\x00\x12=\n\x11shutdown_response\x18@ \x01(\x0b\x32 .wandb_internal.ShutdownResponseH\x00\x12\x39\n\x0f\x61ttach_response\x18\x41 \x01(\x0b\x32\x1e.wandb_internal.AttachResponseH\x00\x12\x39\n\x0fstatus_response\x18\x42 \x01(\x0b\x32\x1e.wandb_internal.StatusResponseH\x00\x12\x42\n\x14server_info_response\x18\x43 \x01(\x0b\x32\".wandb_internal.ServerInfoResponseH\x00\x12<\n\x11job_info_response\x18\x44 \x01(\x0b\x32\x1f.wandb_internal.JobInfoResponseH\x00\x12O\n\x1bget_system_metrics_response\x18\x45 \x01(\x0b\x32(.wandb_internal.GetSystemMetricsResponseH\x00\x12\x46\n\x16link_artifact_response\x18G \x01(\x0b\x32$.wandb_internal.LinkArtifactResponseH\x00\x12\x35\n\rsync_response\x18\x46 \x01(\x0b\x32\x1c.wandb_internal.SyncResponseH\x00\x12X\n run_finish_without_exit_response\x18H \x01(\x0b\x32,.wandb_internal.RunFinishWithoutExitResponseH\x00\x12\x45\n\x13operations_response\x18J \x01(\x0b\x32&.wandb_internal.OperationStatsResponseH\x00\x12\x33\n\x0c\x61pi_response\x18T \x01(\x0b\x32\x1b.wandb_internal.ApiResponseH\x00\x12\x43\n\x14test_inject_response\x18\xe8\x07 \x01(\x0b\x32\".wandb_internal.TestInjectResponseH\x00\x42\x0f\n\rresponse_typeJ\x04\x08I\x10J\"\xc0\x02\n\x0c\x44\x65\x66\x65rRequest\x12\x36\n\x05state\x18\x01 \x01(\x0e\x32\'.wandb_internal.DeferRequest.DeferState\"\xf7\x01\n\nDeferState\x12\t\n\x05\x42\x45GIN\x10\x00\x12\r\n\tFLUSH_RUN\x10\x01\x12\x0f\n\x0b\x46LUSH_STATS\x10\x02\x12\x19\n\x15\x46LUSH_PARTIAL_HISTORY\x10\x03\x12\x0c\n\x08\x46LUSH_TB\x10\x04\x12\r\n\tFLUSH_SUM\x10\x05\x12\x13\n\x0f\x46LUSH_DEBOUNCER\x10\x06\x12\x10\n\x0c\x46LUSH_OUTPUT\x10\x07\x12\r\n\tFLUSH_JOB\x10\x08\x12\r\n\tFLUSH_DIR\x10\t\x12\x0c\n\x08\x46LUSH_FP\x10\n\x12\x0b\n\x07JOIN_FP\x10\x0b\x12\x0c\n\x08\x46LUSH_FS\x10\x0c\x12\x0f\n\x0b\x46LUSH_FINAL\x10\r\x12\x07\n\x03\x45ND\x10\x0e\"<\n\x0cPauseRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x0f\n\rPauseResponse\"=\n\rResumeRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x10\n\x0eResumeResponse\"M\n\x0cLoginRequest\x12\x0f\n\x07\x61pi_key\x18\x01 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"&\n\rLoginResponse\x12\x15\n\ractive_entity\x18\x01 \x01(\t\"A\n\x11GetSummaryRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"?\n\x12GetSummaryResponse\x12)\n\x04item\x18\x01 \x03(\x0b\x32\x1b.wandb_internal.SummaryItem\"G\n\x17GetSystemMetricsRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"R\n\x12SystemMetricSample\x12-\n\ttimestamp\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\r\n\x05value\x18\x02 \x01(\x02\"I\n\x13SystemMetricsBuffer\x12\x32\n\x06record\x18\x01 \x03(\x0b\x32\".wandb_internal.SystemMetricSample\"\xca\x01\n\x18GetSystemMetricsResponse\x12S\n\x0esystem_metrics\x18\x01 \x03(\x0b\x32;.wandb_internal.GetSystemMetricsResponse.SystemMetricsEntry\x1aY\n\x12SystemMetricsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x32\n\x05value\x18\x02 \x01(\x0b\x32#.wandb_internal.SystemMetricsBuffer:\x02\x38\x01\"=\n\rStatusRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\")\n\x0eStatusResponse\x12\x17\n\x0frun_should_stop\x18\x01 \x01(\x08\"A\n\x11StopStatusRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"-\n\x12StopStatusResponse\x12\x17\n\x0frun_should_stop\x18\x01 \x01(\x08\"D\n\x14NetworkStatusRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"P\n\x15NetworkStatusResponse\x12\x37\n\x11network_responses\x18\x01 \x03(\x0b\x32\x1c.wandb_internal.HttpResponse\"D\n\x0cHttpResponse\x12\x18\n\x10http_status_code\x18\x01 \x01(\x05\x12\x1a\n\x12http_response_text\x18\x02 \x01(\t\"G\n\x17InternalMessagesRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"N\n\x18InternalMessagesResponse\x12\x32\n\x08messages\x18\x01 \x01(\x0b\x32 .wandb_internal.InternalMessages\"#\n\x10InternalMessages\x12\x0f\n\x07warning\x18\x01 \x03(\t\"?\n\x0fPollExitRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\xf5\x01\n\x10PollExitResponse\x12\x0c\n\x04\x64one\x18\x01 \x01(\x08\x12\x32\n\x0b\x65xit_result\x18\x02 \x01(\x0b\x32\x1d.wandb_internal.RunExitResult\x12\x35\n\x0cpusher_stats\x18\x03 \x01(\x0b\x32\x1f.wandb_internal.FilePusherStats\x12/\n\x0b\x66ile_counts\x18\x04 \x01(\x0b\x32\x1a.wandb_internal.FileCounts\x12\x37\n\x0foperation_stats\x18\x05 \x01(\x0b\x32\x1e.wandb_internal.OperationStats\"E\n\x15OperationStatsRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"Q\n\x16OperationStatsResponse\x12\x37\n\x0foperation_stats\x18\x01 \x01(\x0b\x32\x1e.wandb_internal.OperationStats\"Y\n\x0eOperationStats\x12-\n\noperations\x18\x01 \x03(\x0b\x32\x19.wandb_internal.Operation\x12\x18\n\x10total_operations\x18\x02 \x01(\x03\"\x87\x01\n\tOperation\x12\x0c\n\x04\x64\x65sc\x18\x01 \x01(\t\x12\x17\n\x0fruntime_seconds\x18\x02 \x01(\x01\x12\x10\n\x08progress\x18\x03 \x01(\t\x12\x14\n\x0c\x65rror_status\x18\x04 \x01(\t\x12+\n\x08subtasks\x18\x05 \x03(\x0b\x32\x19.wandb_internal.Operation\"\x13\n\x11SenderMarkRequest\"\x13\n\x11SyncFinishRequest\"E\n\x0cSyncResponse\x12\x0b\n\x03url\x18\x01 \x01(\t\x12(\n\x05\x65rror\x18\x02 \x01(\x0b\x32\x19.wandb_internal.ErrorInfo\"?\n\x11SenderReadRequest\x12\x14\n\x0cstart_offset\x18\x01 \x01(\x03\x12\x14\n\x0c\x66inal_offset\x18\x02 \x01(\x03\"m\n\x13StatusReportRequest\x12\x12\n\nrecord_num\x18\x01 \x01(\x03\x12\x13\n\x0bsent_offset\x18\x02 \x01(\x03\x12-\n\tsync_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"F\n\x14SummaryRecordRequest\x12.\n\x07summary\x18\x01 \x01(\x0b\x32\x1d.wandb_internal.SummaryRecord\"L\n\x16TelemetryRecordRequest\x12\x32\n\ttelemetry\x18\x01 \x01(\x0b\x32\x1f.wandb_internal.TelemetryRecord\"A\n\x11ServerInfoRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"|\n\x12ServerInfoResponse\x12-\n\nlocal_info\x18\x01 \x01(\x0b\x32\x19.wandb_internal.LocalInfo\x12\x37\n\x0fserver_messages\x18\x02 \x01(\x0b\x32\x1e.wandb_internal.ServerMessages\"=\n\x0eServerMessages\x12+\n\x04item\x18\x01 \x03(\x0b\x32\x1d.wandb_internal.ServerMessage\"e\n\rServerMessage\x12\x12\n\nplain_text\x18\x01 \x01(\t\x12\x10\n\x08utf_text\x18\x02 \x01(\t\x12\x11\n\thtml_text\x18\x03 \x01(\t\x12\x0c\n\x04type\x18\x04 \x01(\t\x12\r\n\x05level\x18\x05 \x01(\x05\"c\n\nFileCounts\x12\x13\n\x0bwandb_count\x18\x01 \x01(\x05\x12\x13\n\x0bmedia_count\x18\x02 \x01(\x05\x12\x16\n\x0e\x61rtifact_count\x18\x03 \x01(\x05\x12\x13\n\x0bother_count\x18\x04 \x01(\x05\"U\n\x0f\x46ilePusherStats\x12\x16\n\x0euploaded_bytes\x18\x01 \x01(\x03\x12\x13\n\x0btotal_bytes\x18\x02 \x01(\x03\x12\x15\n\rdeduped_bytes\x18\x03 \x01(\x03\"\x1e\n\rFilesUploaded\x12\r\n\x05\x66iles\x18\x01 \x03(\t\"\xf4\x01\n\x17\x46ileTransferInfoRequest\x12\x42\n\x04type\x18\x01 \x01(\x0e\x32\x34.wandb_internal.FileTransferInfoRequest.TransferType\x12\x0c\n\x04path\x18\x02 \x01(\t\x12\x0b\n\x03url\x18\x03 \x01(\t\x12\x0c\n\x04size\x18\x04 \x01(\x03\x12\x11\n\tprocessed\x18\x05 \x01(\x03\x12/\n\x0b\x66ile_counts\x18\x06 \x01(\x0b\x32\x1a.wandb_internal.FileCounts\"(\n\x0cTransferType\x12\n\n\x06Upload\x10\x00\x12\x0c\n\x08\x44ownload\x10\x01\"1\n\tLocalInfo\x12\x0f\n\x07version\x18\x01 \x01(\t\x12\x13\n\x0bout_of_date\x18\x02 \x01(\x08\"?\n\x0fShutdownRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x12\n\x10ShutdownResponse\"P\n\rAttachRequest\x12\x11\n\tattach_id\x18\x14 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"b\n\x0e\x41ttachResponse\x12&\n\x03run\x18\x01 \x01(\x0b\x32\x19.wandb_internal.RunRecord\x12(\n\x05\x65rror\x18\x02 \x01(\x0b\x32\x19.wandb_internal.ErrorInfo\"\xd5\x02\n\x11TestInjectRequest\x12\x13\n\x0bhandler_exc\x18\x01 \x01(\x08\x12\x14\n\x0chandler_exit\x18\x02 \x01(\x08\x12\x15\n\rhandler_abort\x18\x03 \x01(\x08\x12\x12\n\nsender_exc\x18\x04 \x01(\x08\x12\x13\n\x0bsender_exit\x18\x05 \x01(\x08\x12\x14\n\x0csender_abort\x18\x06 \x01(\x08\x12\x0f\n\x07req_exc\x18\x07 \x01(\x08\x12\x10\n\x08req_exit\x18\x08 \x01(\x08\x12\x11\n\treq_abort\x18\t \x01(\x08\x12\x10\n\x08resp_exc\x18\n \x01(\x08\x12\x11\n\tresp_exit\x18\x0b \x01(\x08\x12\x12\n\nresp_abort\x18\x0c \x01(\x08\x12\x10\n\x08msg_drop\x18\r \x01(\x08\x12\x10\n\x08msg_hang\x18\x0e \x01(\x08\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x14\n\x12TestInjectResponse\"\x1e\n\rHistoryAction\x12\r\n\x05\x66lush\x18\x01 \x01(\x08\"\xca\x01\n\x15PartialHistoryRequest\x12)\n\x04item\x18\x01 \x03(\x0b\x32\x1b.wandb_internal.HistoryItem\x12)\n\x04step\x18\x02 \x01(\x0b\x32\x1b.wandb_internal.HistoryStep\x12-\n\x06\x61\x63tion\x18\x03 \x01(\x0b\x32\x1d.wandb_internal.HistoryAction\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x18\n\x16PartialHistoryResponse\"E\n\x15SampledHistoryRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"_\n\x12SampledHistoryItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nnested_key\x18\x02 \x03(\t\x12\x14\n\x0cvalues_float\x18\x03 \x03(\x02\x12\x12\n\nvalues_int\x18\x04 \x03(\x03\"J\n\x16SampledHistoryResponse\x12\x30\n\x04item\x18\x01 \x03(\x0b\x32\".wandb_internal.SampledHistoryItem\"@\n\x10RunStatusRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"x\n\x11RunStatusResponse\x12\x18\n\x10sync_items_total\x18\x01 \x01(\x03\x12\x1a\n\x12sync_items_pending\x18\x02 \x01(\x03\x12-\n\tsync_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"g\n\x0fRunStartRequest\x12&\n\x03run\x18\x01 \x01(\x0b\x32\x19.wandb_internal.RunRecord\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x12\n\x10RunStartResponse\"K\n\x1bRunFinishWithoutExitRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x1e\n\x1cRunFinishWithoutExitResponse\"\\\n\x13\x43heckVersionRequest\x12\x17\n\x0f\x63urrent_version\x18\x01 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"]\n\x14\x43heckVersionResponse\x12\x17\n\x0fupgrade_message\x18\x01 \x01(\t\x12\x14\n\x0cyank_message\x18\x02 \x01(\t\x12\x16\n\x0e\x64\x65lete_message\x18\x03 \x01(\t\">\n\x0eJobInfoRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"6\n\x0fJobInfoResponse\x12\x12\n\nsequenceId\x18\x01 \x01(\t\x12\x0f\n\x07version\x18\x02 \x01(\t\"\x9f\x01\n\x12LogArtifactRequest\x12\x30\n\x08\x61rtifact\x18\x01 \x01(\x0b\x32\x1e.wandb_internal.ArtifactRecord\x12\x14\n\x0chistory_step\x18\x02 \x01(\x03\x12\x13\n\x0bstaging_dir\x18\x03 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"A\n\x13LogArtifactResponse\x12\x13\n\x0b\x61rtifact_id\x18\x01 \x01(\t\x12\x15\n\rerror_message\x18\x02 \x01(\t\"\xbe\x01\n\x17\x44ownloadArtifactRequest\x12\x13\n\x0b\x61rtifact_id\x18\x01 \x01(\t\x12\x15\n\rdownload_root\x18\x02 \x01(\t\x12 \n\x18\x61llow_missing_references\x18\x04 \x01(\x08\x12\x12\n\nskip_cache\x18\x05 \x01(\x08\x12\x13\n\x0bpath_prefix\x18\x06 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"1\n\x18\x44ownloadArtifactResponse\x12\x15\n\rerror_message\x18\x01 \x01(\t\"@\n\x10KeepaliveRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x13\n\x11KeepaliveResponse\"q\n\x0c\x41rtifactInfo\x12\x10\n\x08\x61rtifact\x18\x01 \x01(\t\x12\x12\n\nentrypoint\x18\x02 \x03(\t\x12\x10\n\x08notebook\x18\x03 \x01(\x08\x12\x15\n\rbuild_context\x18\x04 \x01(\t\x12\x12\n\ndockerfile\x18\x05 \x01(\t\")\n\x07GitInfo\x12\x0e\n\x06remote\x18\x01 \x01(\t\x12\x0e\n\x06\x63ommit\x18\x02 \x01(\t\"\x87\x01\n\tGitSource\x12)\n\x08git_info\x18\x01 \x01(\x0b\x32\x17.wandb_internal.GitInfo\x12\x12\n\nentrypoint\x18\x02 \x03(\t\x12\x10\n\x08notebook\x18\x03 \x01(\x08\x12\x15\n\rbuild_context\x18\x04 \x01(\t\x12\x12\n\ndockerfile\x18\x05 \x01(\t\"\x1c\n\x0bImageSource\x12\r\n\x05image\x18\x01 \x01(\t\"\x8c\x01\n\x06Source\x12&\n\x03git\x18\x01 \x01(\x0b\x32\x19.wandb_internal.GitSource\x12.\n\x08\x61rtifact\x18\x02 \x01(\x0b\x32\x1c.wandb_internal.ArtifactInfo\x12*\n\x05image\x18\x03 \x01(\x0b\x32\x1b.wandb_internal.ImageSource\"k\n\tJobSource\x12\x10\n\x08_version\x18\x01 \x01(\t\x12\x13\n\x0bsource_type\x18\x02 \x01(\t\x12&\n\x06source\x18\x03 \x01(\x0b\x32\x16.wandb_internal.Source\x12\x0f\n\x07runtime\x18\x04 \x01(\t\"V\n\x12PartialJobArtifact\x12\x10\n\x08job_name\x18\x01 \x01(\t\x12.\n\x0bsource_info\x18\x02 \x01(\x0b\x32\x19.wandb_internal.JobSource\"\x9d\x01\n\x11UseArtifactRecord\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0c\n\x04type\x18\x02 \x01(\t\x12\x0c\n\x04name\x18\x03 \x01(\t\x12\x33\n\x07partial\x18\x04 \x01(\x0b\x32\".wandb_internal.PartialJobArtifact\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x13\n\x11UseArtifactResult\"R\n\rCancelRequest\x12\x13\n\x0b\x63\x61ncel_slot\x18\x01 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x10\n\x0e\x43\x61ncelResponse\"\x18\n\x16ProbeSystemInfoRequest\"\'\n\x08\x44iskInfo\x12\r\n\x05total\x18\x01 \x01(\x04\x12\x0c\n\x04used\x18\x02 \x01(\x04\"\x1b\n\nMemoryInfo\x12\r\n\x05total\x18\x01 \x01(\x04\"/\n\x07\x43puInfo\x12\r\n\x05\x63ount\x18\x01 \x01(\r\x12\x15\n\rcount_logical\x18\x02 \x01(\r\"\x9a\x01\n\tAppleInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\necpu_cores\x18\x02 \x01(\r\x12\x12\n\npcpu_cores\x18\x03 \x01(\r\x12\x11\n\tgpu_cores\x18\x04 \x01(\r\x12\x11\n\tmemory_gb\x18\x05 \x01(\r\x12\x18\n\x10swap_total_bytes\x18\x06 \x01(\x04\x12\x17\n\x0fram_total_bytes\x18\x07 \x01(\x04\"k\n\rGpuNvidiaInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0cmemory_total\x18\x02 \x01(\x04\x12\x12\n\ncuda_cores\x18\x03 \x01(\r\x12\x14\n\x0c\x61rchitecture\x18\x04 \x01(\t\x12\x0c\n\x04uuid\x18\x05 \x01(\t\"\x89\x02\n\nGpuAmdInfo\x12\n\n\x02id\x18\x01 \x01(\t\x12\x11\n\tunique_id\x18\x02 \x01(\t\x12\x15\n\rvbios_version\x18\x03 \x01(\t\x12\x19\n\x11performance_level\x18\x04 \x01(\t\x12\x15\n\rgpu_overdrive\x18\x05 \x01(\t\x12\x1c\n\x14gpu_memory_overdrive\x18\x06 \x01(\t\x12\x11\n\tmax_power\x18\x07 \x01(\t\x12\x0e\n\x06series\x18\x08 \x01(\t\x12\r\n\x05model\x18\t \x01(\t\x12\x0e\n\x06vendor\x18\n \x01(\t\x12\x0b\n\x03sku\x18\x0b \x01(\t\x12\x12\n\nsclk_range\x18\x0c \x01(\t\x12\x12\n\nmclk_range\x18\r \x01(\t\"n\n\x0cTrainiumInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06vendor\x18\x02 \x01(\t\x12\x1b\n\x13neuron_device_count\x18\x03 \x01(\r\x12#\n\x1bneuroncore_per_device_count\x18\x04 \x01(\r\"Q\n\x07TPUInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07hbm_gib\x18\x02 \x01(\r\x12\x18\n\x10\x64\x65vices_per_chip\x18\x03 \x01(\r\x12\r\n\x05\x63ount\x18\x04 \x01(\r\"E\n\rCoreWeaveInfo\x12\x14\n\x0c\x63luster_name\x18\x01 \x01(\t\x12\x0e\n\x06org_id\x18\x02 \x01(\t\x12\x0e\n\x06region\x18\x03 \x01(\t\"\xa8\t\n\x11\x45nvironmentRecord\x12\n\n\x02os\x18\x01 \x01(\t\x12\x0e\n\x06python\x18\x02 \x01(\t\x12\x39\n\nstarted_at\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.TimestampR\tstartedAt\x12\x0e\n\x06\x64ocker\x18\x04 \x01(\t\x12\x0c\n\x04\x61rgs\x18\x05 \x03(\t\x12\x0f\n\x07program\x18\x06 \x01(\t\x12\x1b\n\tcode_path\x18\x07 \x01(\tR\x08\x63odePath\x12&\n\x0f\x63ode_path_local\x18\x08 \x01(\tR\rcodePathLocal\x12*\n\x03git\x18\t \x01(\x0b\x32\x1d.wandb_internal.GitRepoRecord\x12\r\n\x05\x65mail\x18\n \x01(\t\x12\x0c\n\x04root\x18\x0b \x01(\t\x12\x0c\n\x04host\x18\x0c \x01(\t\x12\x10\n\x08username\x18\r \x01(\t\x12\x12\n\nexecutable\x18\x0e \x01(\t\x12\r\n\x05\x63olab\x18\x0f \x01(\t\x12\x1c\n\tcpu_count\x18\x10 \x01(\rR\tcpu_count\x12,\n\x11\x63pu_count_logical\x18\x11 \x01(\rR\x11\x63pu_count_logical\x12\x15\n\x08gpu_type\x18\x12 \x01(\tR\x03gpu\x12\x1c\n\tgpu_count\x18\x13 \x01(\rR\tgpu_count\x12\x39\n\x04\x64isk\x18\x14 \x03(\x0b\x32+.wandb_internal.EnvironmentRecord.DiskEntry\x12*\n\x06memory\x18\x15 \x01(\x0b\x32\x1a.wandb_internal.MemoryInfo\x12$\n\x03\x63pu\x18\x16 \x01(\x0b\x32\x17.wandb_internal.CpuInfo\x12(\n\x05\x61pple\x18\x17 \x01(\x0b\x32\x19.wandb_internal.AppleInfo\x12=\n\ngpu_nvidia\x18\x18 \x03(\x0b\x32\x1d.wandb_internal.GpuNvidiaInfoR\ngpu_nvidia\x12\x14\n\x0c\x63uda_version\x18\x19 \x01(\t\x12\x34\n\x07gpu_amd\x18\x1a \x03(\x0b\x32\x1a.wandb_internal.GpuAmdInfoR\x07gpu_amd\x12;\n\x05slurm\x18\x1b \x03(\x0b\x32,.wandb_internal.EnvironmentRecord.SlurmEntry\x12.\n\x08trainium\x18\x1c \x01(\x0b\x32\x1c.wandb_internal.TrainiumInfo\x12$\n\x03tpu\x18\x1d \x01(\x0b\x32\x17.wandb_internal.TPUInfo\x12\x30\n\tcoreweave\x18\x1e \x01(\x0b\x32\x1d.wandb_internal.CoreWeaveInfo\x12\x12\n\twriter_id\x18\xc7\x01 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\x1a\x45\n\tDiskEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\'\n\x05value\x18\x02 \x01(\x0b\x32\x18.wandb_internal.DiskInfo:\x02\x38\x01\x1a,\n\nSlurmEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x8d\x01\n\x15PythonPackagesRequest\x12\x44\n\x07package\x18\x01 \x03(\x0b\x32\x33.wandb_internal.PythonPackagesRequest.PythonPackage\x1a.\n\rPythonPackage\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07version\x18\x02 \x01(\t\"\x1c\n\x0cJobInputPath\x12\x0c\n\x04path\x18\x01 \x03(\t\"\xd6\x01\n\x0eJobInputSource\x12\x44\n\nrun_config\x18\x01 \x01(\x0b\x32..wandb_internal.JobInputSource.RunConfigSourceH\x00\x12?\n\x04\x66ile\x18\x02 \x01(\x0b\x32/.wandb_internal.JobInputSource.ConfigFileSourceH\x00\x1a\x11\n\x0fRunConfigSource\x1a \n\x10\x43onfigFileSource\x12\x0c\n\x04path\x18\x01 \x01(\tB\x08\n\x06source\"\xc7\x01\n\x0fJobInputRequest\x12\x34\n\x0cinput_source\x18\x01 \x01(\x0b\x32\x1e.wandb_internal.JobInputSource\x12\x33\n\rinclude_paths\x18\x02 \x03(\x0b\x32\x1c.wandb_internal.JobInputPath\x12\x33\n\rexclude_paths\x18\x03 \x03(\x0b\x32\x1c.wandb_internal.JobInputPath\x12\x14\n\x0cinput_schema\x18\x04 \x01(\t\"t\n\x14ServerFeatureRequest\x12.\n\x07\x66\x65\x61ture\x18\x01 \x01(\x0e\x32\x1d.wandb_internal.ServerFeature\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"K\n\x15ServerFeatureResponse\x12\x32\n\x07\x66\x65\x61ture\x18\x01 \x01(\x0b\x32!.wandb_internal.ServerFeatureItem\"2\n\x11ServerFeatureItem\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07\x65nabled\x18\x02 \x01(\x08*\xb3\x04\n\rServerFeature\x12\x13\n\x0fLARGE_FILENAMES\x10\x00\x12\x11\n\rARTIFACT_TAGS\x10\x01\x12\x0e\n\nCLIENT_IDS\x10\x02\x12\x1c\n\x18\x41RTIFACT_REGISTRY_SEARCH\x10\x03\x12\x1b\n\x17STRUCTURED_CONSOLE_LOGS\x10\x04\x12(\n$ARTIFACT_COLLECTION_MEMBERSHIP_FILES\x10\x05\x12\x38\n4ARTIFACT_COLLECTION_MEMBERSHIP_FILE_DOWNLOAD_HANDLER\x10\x06\x12\x34\n0USE_ARTIFACT_WITH_ENTITY_AND_PROJECT_INFORMATION\x10\x07\x12\x1f\n\x1b\x45XPAND_DEFINED_METRIC_GLOBS\x10\x08\x12\x1f\n\x1b\x41UTOMATION_EVENT_RUN_METRIC\x10\t\x12&\n\"AUTOMATION_EVENT_RUN_METRIC_CHANGE\x10\n\x12\x1b\n\x17\x41UTOMATION_ACTION_NO_OP\x10\x0b\x12/\n+INCLUDE_ARTIFACT_TYPES_IN_REGISTRY_CREATION\x10\x0c\x12*\n&PROJECT_ARTIFACT_COLLECTION_MEMBERSHIP\x10\r\x12\x31\n-ARTIFACT_MEMBERSHIP_IN_LINK_ARTIFACT_RESPONSE\x10\x0e\x42\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_internal_pb2', _globals)
+if not _descriptor._USE_C_DESCRIPTORS:
+ _globals['DESCRIPTOR']._loaded_options = None
+ _globals['DESCRIPTOR']._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _globals['_GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY']._loaded_options = None
+ _globals['_GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY']._serialized_options = b'8\001'
+ _globals['_ENVIRONMENTRECORD_DISKENTRY']._loaded_options = None
+ _globals['_ENVIRONMENTRECORD_DISKENTRY']._serialized_options = b'8\001'
+ _globals['_ENVIRONMENTRECORD_SLURMENTRY']._loaded_options = None
+ _globals['_ENVIRONMENTRECORD_SLURMENTRY']._serialized_options = b'8\001'
+ _globals['_SERVERFEATURE']._serialized_start=22471
+ _globals['_SERVERFEATURE']._serialized_end=23034
+ _globals['_RECORD']._serialized_start=209
+ _globals['_RECORD']._serialized_end=1491
+ _globals['_CONTROL']._serialized_start=1494
+ _globals['_CONTROL']._serialized_end=1662
+ _globals['_RESULT']._serialized_start=1665
+ _globals['_RESULT']._serialized_end=2164
+ _globals['_FINALRECORD']._serialized_start=2166
+ _globals['_FINALRECORD']._serialized_end=2224
+ _globals['_VERSIONINFO']._serialized_start=2226
+ _globals['_VERSIONINFO']._serialized_end=2324
+ _globals['_HEADERRECORD']._serialized_start=2326
+ _globals['_HEADERRECORD']._serialized_end=2436
+ _globals['_FOOTERRECORD']._serialized_start=2438
+ _globals['_FOOTERRECORD']._serialized_end=2497
+ _globals['_BRANCHPOINT']._serialized_start=2499
+ _globals['_BRANCHPOINT']._serialized_end=2556
+ _globals['_RUNRECORD']._serialized_start=2559
+ _globals['_RUNRECORD']._serialized_end=3216
+ _globals['_GITREPORECORD']._serialized_start=3218
+ _globals['_GITREPORECORD']._serialized_end=3277
+ _globals['_RUNUPDATERESULT']._serialized_start=3279
+ _globals['_RUNUPDATERESULT']._serialized_end=3378
+ _globals['_ERRORINFO']._serialized_start=3381
+ _globals['_ERRORINFO']._serialized_end=3553
+ _globals['_ERRORINFO_ERRORCODE']._serialized_start=3462
+ _globals['_ERRORINFO_ERRORCODE']._serialized_end=3553
+ _globals['_RUNEXITRECORD']._serialized_start=3555
+ _globals['_RUNEXITRECORD']._serialized_end=3651
+ _globals['_RUNEXITRESULT']._serialized_start=3653
+ _globals['_RUNEXITRESULT']._serialized_end=3668
+ _globals['_RUNPREEMPTINGRECORD']._serialized_start=3670
+ _globals['_RUNPREEMPTINGRECORD']._serialized_end=3736
+ _globals['_RUNPREEMPTINGRESULT']._serialized_start=3738
+ _globals['_RUNPREEMPTINGRESULT']._serialized_end=3759
+ _globals['_SETTINGSRECORD']._serialized_start=3761
+ _globals['_SETTINGSRECORD']._serialized_end=3866
+ _globals['_SETTINGSITEM']._serialized_start=3868
+ _globals['_SETTINGSITEM']._serialized_end=3915
+ _globals['_HISTORYSTEP']._serialized_start=3917
+ _globals['_HISTORYSTEP']._serialized_end=3943
+ _globals['_HISTORYRECORD']._serialized_start=3946
+ _globals['_HISTORYRECORD']._serialized_end=4092
+ _globals['_HISTORYITEM']._serialized_start=4094
+ _globals['_HISTORYITEM']._serialized_end=4160
+ _globals['_HISTORYRESULT']._serialized_start=4162
+ _globals['_HISTORYRESULT']._serialized_end=4177
+ _globals['_OUTPUTRECORD']._serialized_start=4180
+ _globals['_OUTPUTRECORD']._serialized_end=4400
+ _globals['_OUTPUTRECORD_OUTPUTTYPE']._serialized_start=4364
+ _globals['_OUTPUTRECORD_OUTPUTTYPE']._serialized_end=4400
+ _globals['_OUTPUTRESULT']._serialized_start=4402
+ _globals['_OUTPUTRESULT']._serialized_end=4416
+ _globals['_OUTPUTRAWRECORD']._serialized_start=4419
+ _globals['_OUTPUTRAWRECORD']._serialized_end=4645
+ _globals['_OUTPUTRAWRECORD_OUTPUTTYPE']._serialized_start=4364
+ _globals['_OUTPUTRAWRECORD_OUTPUTTYPE']._serialized_end=4400
+ _globals['_OUTPUTRAWRESULT']._serialized_start=4647
+ _globals['_OUTPUTRAWRESULT']._serialized_end=4664
+ _globals['_METRICRECORD']._serialized_start=4667
+ _globals['_METRICRECORD']._serialized_end=5103
+ _globals['_METRICRECORD_METRICGOAL']._serialized_start=5037
+ _globals['_METRICRECORD_METRICGOAL']._serialized_end=5103
+ _globals['_METRICRESULT']._serialized_start=5105
+ _globals['_METRICRESULT']._serialized_end=5119
+ _globals['_METRICOPTIONS']._serialized_start=5121
+ _globals['_METRICOPTIONS']._serialized_end=5188
+ _globals['_METRICCONTROL']._serialized_start=5190
+ _globals['_METRICCONTROL']._serialized_end=5224
+ _globals['_METRICSUMMARY']._serialized_start=5226
+ _globals['_METRICSUMMARY']._serialized_end=5352
+ _globals['_CONFIGRECORD']._serialized_start=5355
+ _globals['_CONFIGRECORD']._serialized_end=5502
+ _globals['_CONFIGITEM']._serialized_start=5504
+ _globals['_CONFIGITEM']._serialized_end=5569
+ _globals['_CONFIGRESULT']._serialized_start=5571
+ _globals['_CONFIGRESULT']._serialized_end=5585
+ _globals['_SUMMARYRECORD']._serialized_start=5588
+ _globals['_SUMMARYRECORD']._serialized_end=5738
+ _globals['_SUMMARYITEM']._serialized_start=5740
+ _globals['_SUMMARYITEM']._serialized_end=5806
+ _globals['_SUMMARYRESULT']._serialized_start=5808
+ _globals['_SUMMARYRESULT']._serialized_end=5823
+ _globals['_FILESRECORD']._serialized_start=5825
+ _globals['_FILESRECORD']._serialized_end=5925
+ _globals['_FILESITEM']._serialized_start=5928
+ _globals['_FILESITEM']._serialized_end=6164
+ _globals['_FILESITEM_POLICYTYPE']._serialized_start=6059
+ _globals['_FILESITEM_POLICYTYPE']._serialized_end=6099
+ _globals['_FILESITEM_FILETYPE']._serialized_start=6101
+ _globals['_FILESITEM_FILETYPE']._serialized_end=6158
+ _globals['_FILESRESULT']._serialized_start=6166
+ _globals['_FILESRESULT']._serialized_end=6179
+ _globals['_STATSRECORD']._serialized_start=6182
+ _globals['_STATSRECORD']._serialized_end=6412
+ _globals['_STATSRECORD_STATSTYPE']._serialized_start=6389
+ _globals['_STATSRECORD_STATSTYPE']._serialized_end=6412
+ _globals['_STATSITEM']._serialized_start=6414
+ _globals['_STATSITEM']._serialized_end=6458
+ _globals['_ARTIFACTRECORD']._serialized_start=6461
+ _globals['_ARTIFACTRECORD']._serialized_end=6948
+ _globals['_ARTIFACTMANIFEST']._serialized_start=6951
+ _globals['_ARTIFACTMANIFEST']._serialized_end=7167
+ _globals['_ARTIFACTMANIFESTENTRY']._serialized_start=7170
+ _globals['_ARTIFACTMANIFESTENTRY']._serialized_end=7377
+ _globals['_EXTRAITEM']._serialized_start=7379
+ _globals['_EXTRAITEM']._serialized_end=7423
+ _globals['_STORAGEPOLICYCONFIGITEM']._serialized_start=7425
+ _globals['_STORAGEPOLICYCONFIGITEM']._serialized_end=7483
+ _globals['_ARTIFACTRESULT']._serialized_start=7485
+ _globals['_ARTIFACTRESULT']._serialized_end=7501
+ _globals['_LINKARTIFACTRESULT']._serialized_start=7503
+ _globals['_LINKARTIFACTRESULT']._serialized_end=7523
+ _globals['_LINKARTIFACTREQUEST']._serialized_start=7526
+ _globals['_LINKARTIFACTREQUEST']._serialized_end=7766
+ _globals['_LINKARTIFACTRESPONSE']._serialized_start=7768
+ _globals['_LINKARTIFACTRESPONSE']._serialized_end=7859
+ _globals['_TBRECORD']._serialized_start=7861
+ _globals['_TBRECORD']._serialized_end=7965
+ _globals['_TBRESULT']._serialized_start=7967
+ _globals['_TBRESULT']._serialized_end=7977
+ _globals['_ALERTRECORD']._serialized_start=7979
+ _globals['_ALERTRECORD']._serialized_end=8104
+ _globals['_ALERTRESULT']._serialized_start=8106
+ _globals['_ALERTRESULT']._serialized_end=8119
+ _globals['_REQUEST']._serialized_start=8122
+ _globals['_REQUEST']._serialized_end=10418
+ _globals['_RESPONSE']._serialized_start=10421
+ _globals['_RESPONSE']._serialized_end=12293
+ _globals['_DEFERREQUEST']._serialized_start=12296
+ _globals['_DEFERREQUEST']._serialized_end=12616
+ _globals['_DEFERREQUEST_DEFERSTATE']._serialized_start=12369
+ _globals['_DEFERREQUEST_DEFERSTATE']._serialized_end=12616
+ _globals['_PAUSEREQUEST']._serialized_start=12618
+ _globals['_PAUSEREQUEST']._serialized_end=12678
+ _globals['_PAUSERESPONSE']._serialized_start=12680
+ _globals['_PAUSERESPONSE']._serialized_end=12695
+ _globals['_RESUMEREQUEST']._serialized_start=12697
+ _globals['_RESUMEREQUEST']._serialized_end=12758
+ _globals['_RESUMERESPONSE']._serialized_start=12760
+ _globals['_RESUMERESPONSE']._serialized_end=12776
+ _globals['_LOGINREQUEST']._serialized_start=12778
+ _globals['_LOGINREQUEST']._serialized_end=12855
+ _globals['_LOGINRESPONSE']._serialized_start=12857
+ _globals['_LOGINRESPONSE']._serialized_end=12895
+ _globals['_GETSUMMARYREQUEST']._serialized_start=12897
+ _globals['_GETSUMMARYREQUEST']._serialized_end=12962
+ _globals['_GETSUMMARYRESPONSE']._serialized_start=12964
+ _globals['_GETSUMMARYRESPONSE']._serialized_end=13027
+ _globals['_GETSYSTEMMETRICSREQUEST']._serialized_start=13029
+ _globals['_GETSYSTEMMETRICSREQUEST']._serialized_end=13100
+ _globals['_SYSTEMMETRICSAMPLE']._serialized_start=13102
+ _globals['_SYSTEMMETRICSAMPLE']._serialized_end=13184
+ _globals['_SYSTEMMETRICSBUFFER']._serialized_start=13186
+ _globals['_SYSTEMMETRICSBUFFER']._serialized_end=13259
+ _globals['_GETSYSTEMMETRICSRESPONSE']._serialized_start=13262
+ _globals['_GETSYSTEMMETRICSRESPONSE']._serialized_end=13464
+ _globals['_GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY']._serialized_start=13375
+ _globals['_GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY']._serialized_end=13464
+ _globals['_STATUSREQUEST']._serialized_start=13466
+ _globals['_STATUSREQUEST']._serialized_end=13527
+ _globals['_STATUSRESPONSE']._serialized_start=13529
+ _globals['_STATUSRESPONSE']._serialized_end=13570
+ _globals['_STOPSTATUSREQUEST']._serialized_start=13572
+ _globals['_STOPSTATUSREQUEST']._serialized_end=13637
+ _globals['_STOPSTATUSRESPONSE']._serialized_start=13639
+ _globals['_STOPSTATUSRESPONSE']._serialized_end=13684
+ _globals['_NETWORKSTATUSREQUEST']._serialized_start=13686
+ _globals['_NETWORKSTATUSREQUEST']._serialized_end=13754
+ _globals['_NETWORKSTATUSRESPONSE']._serialized_start=13756
+ _globals['_NETWORKSTATUSRESPONSE']._serialized_end=13836
+ _globals['_HTTPRESPONSE']._serialized_start=13838
+ _globals['_HTTPRESPONSE']._serialized_end=13906
+ _globals['_INTERNALMESSAGESREQUEST']._serialized_start=13908
+ _globals['_INTERNALMESSAGESREQUEST']._serialized_end=13979
+ _globals['_INTERNALMESSAGESRESPONSE']._serialized_start=13981
+ _globals['_INTERNALMESSAGESRESPONSE']._serialized_end=14059
+ _globals['_INTERNALMESSAGES']._serialized_start=14061
+ _globals['_INTERNALMESSAGES']._serialized_end=14096
+ _globals['_POLLEXITREQUEST']._serialized_start=14098
+ _globals['_POLLEXITREQUEST']._serialized_end=14161
+ _globals['_POLLEXITRESPONSE']._serialized_start=14164
+ _globals['_POLLEXITRESPONSE']._serialized_end=14409
+ _globals['_OPERATIONSTATSREQUEST']._serialized_start=14411
+ _globals['_OPERATIONSTATSREQUEST']._serialized_end=14480
+ _globals['_OPERATIONSTATSRESPONSE']._serialized_start=14482
+ _globals['_OPERATIONSTATSRESPONSE']._serialized_end=14563
+ _globals['_OPERATIONSTATS']._serialized_start=14565
+ _globals['_OPERATIONSTATS']._serialized_end=14654
+ _globals['_OPERATION']._serialized_start=14657
+ _globals['_OPERATION']._serialized_end=14792
+ _globals['_SENDERMARKREQUEST']._serialized_start=14794
+ _globals['_SENDERMARKREQUEST']._serialized_end=14813
+ _globals['_SYNCFINISHREQUEST']._serialized_start=14815
+ _globals['_SYNCFINISHREQUEST']._serialized_end=14834
+ _globals['_SYNCRESPONSE']._serialized_start=14836
+ _globals['_SYNCRESPONSE']._serialized_end=14905
+ _globals['_SENDERREADREQUEST']._serialized_start=14907
+ _globals['_SENDERREADREQUEST']._serialized_end=14970
+ _globals['_STATUSREPORTREQUEST']._serialized_start=14972
+ _globals['_STATUSREPORTREQUEST']._serialized_end=15081
+ _globals['_SUMMARYRECORDREQUEST']._serialized_start=15083
+ _globals['_SUMMARYRECORDREQUEST']._serialized_end=15153
+ _globals['_TELEMETRYRECORDREQUEST']._serialized_start=15155
+ _globals['_TELEMETRYRECORDREQUEST']._serialized_end=15231
+ _globals['_SERVERINFOREQUEST']._serialized_start=15233
+ _globals['_SERVERINFOREQUEST']._serialized_end=15298
+ _globals['_SERVERINFORESPONSE']._serialized_start=15300
+ _globals['_SERVERINFORESPONSE']._serialized_end=15424
+ _globals['_SERVERMESSAGES']._serialized_start=15426
+ _globals['_SERVERMESSAGES']._serialized_end=15487
+ _globals['_SERVERMESSAGE']._serialized_start=15489
+ _globals['_SERVERMESSAGE']._serialized_end=15590
+ _globals['_FILECOUNTS']._serialized_start=15592
+ _globals['_FILECOUNTS']._serialized_end=15691
+ _globals['_FILEPUSHERSTATS']._serialized_start=15693
+ _globals['_FILEPUSHERSTATS']._serialized_end=15778
+ _globals['_FILESUPLOADED']._serialized_start=15780
+ _globals['_FILESUPLOADED']._serialized_end=15810
+ _globals['_FILETRANSFERINFOREQUEST']._serialized_start=15813
+ _globals['_FILETRANSFERINFOREQUEST']._serialized_end=16057
+ _globals['_FILETRANSFERINFOREQUEST_TRANSFERTYPE']._serialized_start=16017
+ _globals['_FILETRANSFERINFOREQUEST_TRANSFERTYPE']._serialized_end=16057
+ _globals['_LOCALINFO']._serialized_start=16059
+ _globals['_LOCALINFO']._serialized_end=16108
+ _globals['_SHUTDOWNREQUEST']._serialized_start=16110
+ _globals['_SHUTDOWNREQUEST']._serialized_end=16173
+ _globals['_SHUTDOWNRESPONSE']._serialized_start=16175
+ _globals['_SHUTDOWNRESPONSE']._serialized_end=16193
+ _globals['_ATTACHREQUEST']._serialized_start=16195
+ _globals['_ATTACHREQUEST']._serialized_end=16275
+ _globals['_ATTACHRESPONSE']._serialized_start=16277
+ _globals['_ATTACHRESPONSE']._serialized_end=16375
+ _globals['_TESTINJECTREQUEST']._serialized_start=16378
+ _globals['_TESTINJECTREQUEST']._serialized_end=16719
+ _globals['_TESTINJECTRESPONSE']._serialized_start=16721
+ _globals['_TESTINJECTRESPONSE']._serialized_end=16741
+ _globals['_HISTORYACTION']._serialized_start=16743
+ _globals['_HISTORYACTION']._serialized_end=16773
+ _globals['_PARTIALHISTORYREQUEST']._serialized_start=16776
+ _globals['_PARTIALHISTORYREQUEST']._serialized_end=16978
+ _globals['_PARTIALHISTORYRESPONSE']._serialized_start=16980
+ _globals['_PARTIALHISTORYRESPONSE']._serialized_end=17004
+ _globals['_SAMPLEDHISTORYREQUEST']._serialized_start=17006
+ _globals['_SAMPLEDHISTORYREQUEST']._serialized_end=17075
+ _globals['_SAMPLEDHISTORYITEM']._serialized_start=17077
+ _globals['_SAMPLEDHISTORYITEM']._serialized_end=17172
+ _globals['_SAMPLEDHISTORYRESPONSE']._serialized_start=17174
+ _globals['_SAMPLEDHISTORYRESPONSE']._serialized_end=17248
+ _globals['_RUNSTATUSREQUEST']._serialized_start=17250
+ _globals['_RUNSTATUSREQUEST']._serialized_end=17314
+ _globals['_RUNSTATUSRESPONSE']._serialized_start=17316
+ _globals['_RUNSTATUSRESPONSE']._serialized_end=17436
+ _globals['_RUNSTARTREQUEST']._serialized_start=17438
+ _globals['_RUNSTARTREQUEST']._serialized_end=17541
+ _globals['_RUNSTARTRESPONSE']._serialized_start=17543
+ _globals['_RUNSTARTRESPONSE']._serialized_end=17561
+ _globals['_RUNFINISHWITHOUTEXITREQUEST']._serialized_start=17563
+ _globals['_RUNFINISHWITHOUTEXITREQUEST']._serialized_end=17638
+ _globals['_RUNFINISHWITHOUTEXITRESPONSE']._serialized_start=17640
+ _globals['_RUNFINISHWITHOUTEXITRESPONSE']._serialized_end=17670
+ _globals['_CHECKVERSIONREQUEST']._serialized_start=17672
+ _globals['_CHECKVERSIONREQUEST']._serialized_end=17764
+ _globals['_CHECKVERSIONRESPONSE']._serialized_start=17766
+ _globals['_CHECKVERSIONRESPONSE']._serialized_end=17859
+ _globals['_JOBINFOREQUEST']._serialized_start=17861
+ _globals['_JOBINFOREQUEST']._serialized_end=17923
+ _globals['_JOBINFORESPONSE']._serialized_start=17925
+ _globals['_JOBINFORESPONSE']._serialized_end=17979
+ _globals['_LOGARTIFACTREQUEST']._serialized_start=17982
+ _globals['_LOGARTIFACTREQUEST']._serialized_end=18141
+ _globals['_LOGARTIFACTRESPONSE']._serialized_start=18143
+ _globals['_LOGARTIFACTRESPONSE']._serialized_end=18208
+ _globals['_DOWNLOADARTIFACTREQUEST']._serialized_start=18211
+ _globals['_DOWNLOADARTIFACTREQUEST']._serialized_end=18401
+ _globals['_DOWNLOADARTIFACTRESPONSE']._serialized_start=18403
+ _globals['_DOWNLOADARTIFACTRESPONSE']._serialized_end=18452
+ _globals['_KEEPALIVEREQUEST']._serialized_start=18454
+ _globals['_KEEPALIVEREQUEST']._serialized_end=18518
+ _globals['_KEEPALIVERESPONSE']._serialized_start=18520
+ _globals['_KEEPALIVERESPONSE']._serialized_end=18539
+ _globals['_ARTIFACTINFO']._serialized_start=18541
+ _globals['_ARTIFACTINFO']._serialized_end=18654
+ _globals['_GITINFO']._serialized_start=18656
+ _globals['_GITINFO']._serialized_end=18697
+ _globals['_GITSOURCE']._serialized_start=18700
+ _globals['_GITSOURCE']._serialized_end=18835
+ _globals['_IMAGESOURCE']._serialized_start=18837
+ _globals['_IMAGESOURCE']._serialized_end=18865
+ _globals['_SOURCE']._serialized_start=18868
+ _globals['_SOURCE']._serialized_end=19008
+ _globals['_JOBSOURCE']._serialized_start=19010
+ _globals['_JOBSOURCE']._serialized_end=19117
+ _globals['_PARTIALJOBARTIFACT']._serialized_start=19119
+ _globals['_PARTIALJOBARTIFACT']._serialized_end=19205
+ _globals['_USEARTIFACTRECORD']._serialized_start=19208
+ _globals['_USEARTIFACTRECORD']._serialized_end=19365
+ _globals['_USEARTIFACTRESULT']._serialized_start=19367
+ _globals['_USEARTIFACTRESULT']._serialized_end=19386
+ _globals['_CANCELREQUEST']._serialized_start=19388
+ _globals['_CANCELREQUEST']._serialized_end=19470
+ _globals['_CANCELRESPONSE']._serialized_start=19472
+ _globals['_CANCELRESPONSE']._serialized_end=19488
+ _globals['_PROBESYSTEMINFOREQUEST']._serialized_start=19490
+ _globals['_PROBESYSTEMINFOREQUEST']._serialized_end=19514
+ _globals['_DISKINFO']._serialized_start=19516
+ _globals['_DISKINFO']._serialized_end=19555
+ _globals['_MEMORYINFO']._serialized_start=19557
+ _globals['_MEMORYINFO']._serialized_end=19584
+ _globals['_CPUINFO']._serialized_start=19586
+ _globals['_CPUINFO']._serialized_end=19633
+ _globals['_APPLEINFO']._serialized_start=19636
+ _globals['_APPLEINFO']._serialized_end=19790
+ _globals['_GPUNVIDIAINFO']._serialized_start=19792
+ _globals['_GPUNVIDIAINFO']._serialized_end=19899
+ _globals['_GPUAMDINFO']._serialized_start=19902
+ _globals['_GPUAMDINFO']._serialized_end=20167
+ _globals['_TRAINIUMINFO']._serialized_start=20169
+ _globals['_TRAINIUMINFO']._serialized_end=20279
+ _globals['_TPUINFO']._serialized_start=20281
+ _globals['_TPUINFO']._serialized_end=20362
+ _globals['_COREWEAVEINFO']._serialized_start=20364
+ _globals['_COREWEAVEINFO']._serialized_end=20433
+ _globals['_ENVIRONMENTRECORD']._serialized_start=20436
+ _globals['_ENVIRONMENTRECORD']._serialized_end=21628
+ _globals['_ENVIRONMENTRECORD_DISKENTRY']._serialized_start=21513
+ _globals['_ENVIRONMENTRECORD_DISKENTRY']._serialized_end=21582
+ _globals['_ENVIRONMENTRECORD_SLURMENTRY']._serialized_start=21584
+ _globals['_ENVIRONMENTRECORD_SLURMENTRY']._serialized_end=21628
+ _globals['_PYTHONPACKAGESREQUEST']._serialized_start=21631
+ _globals['_PYTHONPACKAGESREQUEST']._serialized_end=21772
+ _globals['_PYTHONPACKAGESREQUEST_PYTHONPACKAGE']._serialized_start=21726
+ _globals['_PYTHONPACKAGESREQUEST_PYTHONPACKAGE']._serialized_end=21772
+ _globals['_JOBINPUTPATH']._serialized_start=21774
+ _globals['_JOBINPUTPATH']._serialized_end=21802
+ _globals['_JOBINPUTSOURCE']._serialized_start=21805
+ _globals['_JOBINPUTSOURCE']._serialized_end=22019
+ _globals['_JOBINPUTSOURCE_RUNCONFIGSOURCE']._serialized_start=21958
+ _globals['_JOBINPUTSOURCE_RUNCONFIGSOURCE']._serialized_end=21975
+ _globals['_JOBINPUTSOURCE_CONFIGFILESOURCE']._serialized_start=21977
+ _globals['_JOBINPUTSOURCE_CONFIGFILESOURCE']._serialized_end=22009
+ _globals['_JOBINPUTREQUEST']._serialized_start=22022
+ _globals['_JOBINPUTREQUEST']._serialized_end=22221
+ _globals['_SERVERFEATUREREQUEST']._serialized_start=22223
+ _globals['_SERVERFEATUREREQUEST']._serialized_end=22339
+ _globals['_SERVERFEATURERESPONSE']._serialized_start=22341
+ _globals['_SERVERFEATURERESPONSE']._serialized_end=22416
+ _globals['_SERVERFEATUREITEM']._serialized_start=22418
+ _globals['_SERVERFEATUREITEM']._serialized_end=22468
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v6/wandb_server_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v6/wandb_server_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3627c757281aca6766c6a99d545822a3c1db45c
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v6/wandb_server_pb2.py
@@ -0,0 +1,75 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# NO CHECKED-IN PROTOBUF GENCODE
+# source: wandb/proto/wandb_server.proto
+# Protobuf Python Version: 6.31.1
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import runtime_version as _runtime_version
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+_runtime_version.ValidateProtobufRuntimeVersion(
+ _runtime_version.Domain.PUBLIC,
+ 6,
+ 31,
+ 1,
+ '',
+ 'wandb/proto/wandb_server.proto'
+)
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2
+from wandb.proto import wandb_internal_pb2 as wandb_dot_proto_dot_wandb__internal__pb2
+from wandb.proto import wandb_settings_pb2 as wandb_dot_proto_dot_wandb__settings__pb2
+from wandb.proto import wandb_sync_pb2 as wandb_dot_proto_dot_wandb__sync__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1ewandb/proto/wandb_server.proto\x12\x0ewandb_internal\x1a\x1cwandb/proto/wandb_base.proto\x1a wandb/proto/wandb_internal.proto\x1a wandb/proto/wandb_settings.proto\x1a\x1cwandb/proto/wandb_sync.proto\"k\n\x19ServerAuthenticateRequest\x12\x0f\n\x07\x61pi_key\x18\x01 \x01(\t\x12\x10\n\x08\x62\x61se_url\x18\x02 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"w\n\x1aServerAuthenticateResponse\x12\x16\n\x0e\x64\x65\x66\x61ult_entity\x18\x01 \x01(\t\x12\x14\n\x0c\x65rror_status\x18\x02 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"D\n\x15ServerShutdownRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x18\n\x16ServerShutdownResponse\"B\n\x13ServerStatusRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x16\n\x14ServerStatusResponse\"r\n\x17ServerInformInitRequest\x12*\n\x08settings\x18\x01 \x01(\x0b\x32\x18.wandb_internal.Settings\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1a\n\x18ServerInformInitResponse\"H\n\x19ServerInformFinishRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1c\n\x1aServerInformFinishResponse\"H\n\x19ServerInformAttachRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"u\n\x1aServerInformAttachResponse\x12*\n\x08settings\x18\x01 \x01(\x0b\x32\x18.wandb_internal.Settings\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"H\n\x19ServerInformDetachRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1c\n\x1aServerInformDetachResponse\"]\n\x1bServerInformTeardownRequest\x12\x11\n\texit_code\x18\x01 \x01(\x05\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1e\n\x1cServerInformTeardownResponse\"\xee\x05\n\rServerRequest\x12\x12\n\nrequest_id\x18\n \x01(\t\x12\x30\n\x0erecord_publish\x18\x01 \x01(\x0b\x32\x16.wandb_internal.RecordH\x00\x12\x34\n\x12record_communicate\x18\x02 \x01(\x0b\x32\x16.wandb_internal.RecordH\x00\x12>\n\x0binform_init\x18\x03 \x01(\x0b\x32\'.wandb_internal.ServerInformInitRequestH\x00\x12\x42\n\rinform_finish\x18\x04 \x01(\x0b\x32).wandb_internal.ServerInformFinishRequestH\x00\x12\x42\n\rinform_attach\x18\x05 \x01(\x0b\x32).wandb_internal.ServerInformAttachRequestH\x00\x12\x42\n\rinform_detach\x18\x06 \x01(\x0b\x32).wandb_internal.ServerInformDetachRequestH\x00\x12\x46\n\x0finform_teardown\x18\x07 \x01(\x0b\x32+.wandb_internal.ServerInformTeardownRequestH\x00\x12\x41\n\x0c\x61uthenticate\x18\t \x01(\x0b\x32).wandb_internal.ServerAuthenticateRequestH\x00\x12:\n\tinit_sync\x18\x0b \x01(\x0b\x32%.wandb_internal.ServerInitSyncRequestH\x00\x12\x31\n\x04sync\x18\x0c \x01(\x0b\x32!.wandb_internal.ServerSyncRequestH\x00\x12>\n\x0bsync_status\x18\r \x01(\x0b\x32\'.wandb_internal.ServerSyncStatusRequestH\x00\x42\x15\n\x13server_request_typeJ\x04\x08\x08\x10\t\"\x98\x06\n\x0eServerResponse\x12\x12\n\nrequest_id\x18\n \x01(\t\x12\x34\n\x12result_communicate\x18\x02 \x01(\x0b\x32\x16.wandb_internal.ResultH\x00\x12H\n\x14inform_init_response\x18\x03 \x01(\x0b\x32(.wandb_internal.ServerInformInitResponseH\x00\x12L\n\x16inform_finish_response\x18\x04 \x01(\x0b\x32*.wandb_internal.ServerInformFinishResponseH\x00\x12L\n\x16inform_attach_response\x18\x05 \x01(\x0b\x32*.wandb_internal.ServerInformAttachResponseH\x00\x12L\n\x16inform_detach_response\x18\x06 \x01(\x0b\x32*.wandb_internal.ServerInformDetachResponseH\x00\x12P\n\x18inform_teardown_response\x18\x07 \x01(\x0b\x32,.wandb_internal.ServerInformTeardownResponseH\x00\x12K\n\x15\x61uthenticate_response\x18\t \x01(\x0b\x32*.wandb_internal.ServerAuthenticateResponseH\x00\x12\x44\n\x12init_sync_response\x18\x0b \x01(\x0b\x32&.wandb_internal.ServerInitSyncResponseH\x00\x12;\n\rsync_response\x18\x0c \x01(\x0b\x32\".wandb_internal.ServerSyncResponseH\x00\x12H\n\x14sync_status_response\x18\r \x01(\x0b\x32(.wandb_internal.ServerSyncStatusResponseH\x00\x42\x16\n\x14server_response_typeJ\x04\x08\x08\x10\tB\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_server_pb2', _globals)
+if not _descriptor._USE_C_DESCRIPTORS:
+ _globals['DESCRIPTOR']._loaded_options = None
+ _globals['DESCRIPTOR']._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _globals['_SERVERAUTHENTICATEREQUEST']._serialized_start=178
+ _globals['_SERVERAUTHENTICATEREQUEST']._serialized_end=285
+ _globals['_SERVERAUTHENTICATERESPONSE']._serialized_start=287
+ _globals['_SERVERAUTHENTICATERESPONSE']._serialized_end=406
+ _globals['_SERVERSHUTDOWNREQUEST']._serialized_start=408
+ _globals['_SERVERSHUTDOWNREQUEST']._serialized_end=476
+ _globals['_SERVERSHUTDOWNRESPONSE']._serialized_start=478
+ _globals['_SERVERSHUTDOWNRESPONSE']._serialized_end=502
+ _globals['_SERVERSTATUSREQUEST']._serialized_start=504
+ _globals['_SERVERSTATUSREQUEST']._serialized_end=570
+ _globals['_SERVERSTATUSRESPONSE']._serialized_start=572
+ _globals['_SERVERSTATUSRESPONSE']._serialized_end=594
+ _globals['_SERVERINFORMINITREQUEST']._serialized_start=596
+ _globals['_SERVERINFORMINITREQUEST']._serialized_end=710
+ _globals['_SERVERINFORMINITRESPONSE']._serialized_start=712
+ _globals['_SERVERINFORMINITRESPONSE']._serialized_end=738
+ _globals['_SERVERINFORMFINISHREQUEST']._serialized_start=740
+ _globals['_SERVERINFORMFINISHREQUEST']._serialized_end=812
+ _globals['_SERVERINFORMFINISHRESPONSE']._serialized_start=814
+ _globals['_SERVERINFORMFINISHRESPONSE']._serialized_end=842
+ _globals['_SERVERINFORMATTACHREQUEST']._serialized_start=844
+ _globals['_SERVERINFORMATTACHREQUEST']._serialized_end=916
+ _globals['_SERVERINFORMATTACHRESPONSE']._serialized_start=918
+ _globals['_SERVERINFORMATTACHRESPONSE']._serialized_end=1035
+ _globals['_SERVERINFORMDETACHREQUEST']._serialized_start=1037
+ _globals['_SERVERINFORMDETACHREQUEST']._serialized_end=1109
+ _globals['_SERVERINFORMDETACHRESPONSE']._serialized_start=1111
+ _globals['_SERVERINFORMDETACHRESPONSE']._serialized_end=1139
+ _globals['_SERVERINFORMTEARDOWNREQUEST']._serialized_start=1141
+ _globals['_SERVERINFORMTEARDOWNREQUEST']._serialized_end=1234
+ _globals['_SERVERINFORMTEARDOWNRESPONSE']._serialized_start=1236
+ _globals['_SERVERINFORMTEARDOWNRESPONSE']._serialized_end=1266
+ _globals['_SERVERREQUEST']._serialized_start=1269
+ _globals['_SERVERREQUEST']._serialized_end=2019
+ _globals['_SERVERRESPONSE']._serialized_start=2022
+ _globals['_SERVERRESPONSE']._serialized_end=2814
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v6/wandb_settings_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v6/wandb_settings_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..10b7eb749bcdb22937557c130fee5dd3d92d0faf
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v6/wandb_settings_pb2.py
@@ -0,0 +1,58 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# NO CHECKED-IN PROTOBUF GENCODE
+# source: wandb/proto/wandb_settings.proto
+# Protobuf Python Version: 6.31.1
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import runtime_version as _runtime_version
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+_runtime_version.ValidateProtobufRuntimeVersion(
+ _runtime_version.Domain.PUBLIC,
+ 6,
+ 31,
+ 1,
+ '',
+ 'wandb/proto/wandb_settings.proto'
+)
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from google.protobuf import wrappers_pb2 as google_dot_protobuf_dot_wrappers__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n wandb/proto/wandb_settings.proto\x12\x0ewandb_internal\x1a\x1egoogle/protobuf/wrappers.proto\" \n\x0fListStringValue\x12\r\n\x05value\x18\x01 \x03(\t\"\x1d\n\x0cListIntValue\x12\r\n\x05value\x18\x01 \x03(\x05\"\x8a\x01\n\x17MapStringKeyStringValue\x12\x41\n\x05value\x18\x01 \x03(\x0b\x32\x32.wandb_internal.MapStringKeyStringValue.ValueEntry\x1a,\n\nValueEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xcb\x01\n#MapStringKeyMapStringKeyStringValue\x12M\n\x05value\x18\x01 \x03(\x0b\x32>.wandb_internal.MapStringKeyMapStringKeyStringValue.ValueEntry\x1aU\n\nValueEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x36\n\x05value\x18\x02 \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue:\x02\x38\x01\"\x9a\x01\n\x12OpenMetricsFilters\x12\x33\n\x08sequence\x18\x01 \x01(\x0b\x32\x1f.wandb_internal.ListStringValueH\x00\x12\x46\n\x07mapping\x18\x02 \x01(\x0b\x32\x33.wandb_internal.MapStringKeyMapStringKeyStringValueH\x00\x42\x07\n\x05value\"7\n\tRunMoment\x12\x0b\n\x03run\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x01\x12\x0e\n\x06metric\x18\x03 \x01(\t\"\xc2M\n\x08Settings\x12-\n\x07\x61pi_key\x18\x37 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12:\n\x13identity_token_file\x18\xaa\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x37\n\x10\x63redentials_file\x18\xab\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x39\n\x14insecure_disable_ssl\x18\xb9\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12,\n\x08_offline\x18\x1e \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12*\n\x06x_sync\x18\x1f \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x30\n\tsync_file\x18\x86\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x07_shared\x18\xa2\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12,\n\x06run_id\x18k \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12-\n\x07run_url\x18q \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12-\n\x07project\x18\x61 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x06\x65ntity\x18\x45 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x33\n\x0corganization\x18\xbc\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0cx_start_time\x18) \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12.\n\x08root_dir\x18i \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12-\n\x07log_dir\x18U \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0clog_internal\x18V \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0cignore_globs\x18N \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12.\n\x08\x62\x61se_url\x18\x39 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12=\n\x17x_file_stream_max_bytes\x18\xac\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x46\n\x1fx_file_stream_transmit_interval\x18\xaf\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x45\n\x14x_extra_http_headers\x18\x0e \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12=\n\x17x_file_stream_retry_max\x18\x93\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12K\n$x_file_stream_retry_wait_min_seconds\x18\x94\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12K\n$x_file_stream_retry_wait_max_seconds\x18\x95\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x43\n\x1dx_file_stream_timeout_seconds\x18\x0f \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x42\n\x1cx_file_stream_max_line_bytes\x18\xb2\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12?\n\x19x_file_transfer_retry_max\x18\x96\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12M\n&x_file_transfer_retry_wait_min_seconds\x18\x97\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12M\n&x_file_transfer_retry_wait_max_seconds\x18\x98\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x46\n\x1fx_file_transfer_timeout_seconds\x18\x99\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x39\n\x13x_graphql_retry_max\x18\x9a\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12G\n x_graphql_retry_wait_min_seconds\x18\x9b\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12G\n x_graphql_retry_wait_max_seconds\x18\x9c\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12@\n\x19x_graphql_timeout_seconds\x18\x9d\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x31\n\nhttp_proxy\x18\xa8\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0bhttps_proxy\x18\xa9\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12;\n\tx_proxies\x18\xc8\x01 \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12-\n\x07program\x18_ \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0fprogram_relpath\x18` \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x37\n\x10_code_path_local\x18\xa3\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x36\n\x0fprogram_abspath\x18\x9f\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x05_args\x18\x01 \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12)\n\x03_os\x18 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x06\x64ocker\x18\x43 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0cx_executable\x18\r \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12-\n\x07_python\x18\" \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x30\n\tcolab_url\x18\xa0\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12*\n\x04host\x18M \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x08username\x18\x8d\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12+\n\x05\x65mail\x18\x44 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x06resume\x18\x66 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x0bresume_from\x18\xa7\x01 \x01(\x0b\x32\x19.wandb_internal.RunMoment\x12-\n\tfork_from\x18\xa4\x01 \x01(\x0b\x32\x19.wandb_internal.RunMoment\x12\x38\n\x14\x64isable_job_creation\x18\x41 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x30\n\tsweep_url\x18\x83\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12;\n\x16x_disable_update_check\x18\xa5\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x32\n\x0ex_disable_meta\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12-\n\tsave_code\x18s \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\x0b\x64isable_git\x18? \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12;\n\x16x_disable_machine_info\x18\x9e\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x33\n\x0fx_disable_stats\x18\n \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x39\n\x13x_stats_buffer_size\x18\xa1\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12@\n\x19x_stats_sampling_interval\x18\xae\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x30\n\x0bx_stats_pid\x18* \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12<\n\x12x_stats_disk_paths\x18\x92\x01 \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12H\n\"x_stats_neuron_monitor_config_path\x18. \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12<\n\x15x_stats_dcgm_exporter\x18\xbb\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12O\n\x1ex_stats_open_metrics_endpoints\x18/ \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12H\n\x1cx_stats_open_metrics_filters\x18\x30 \x01(\x0b\x32\".wandb_internal.OpenMetricsFilters\x12S\n!x_stats_open_metrics_http_headers\x18\xb8\x01 \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12=\n\x16x_stats_gpu_device_ids\x18\xba\x01 \x01(\x0b\x32\x1c.wandb_internal.ListIntValue\x12\x37\n\x11x_stats_cpu_count\x18\xc2\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12?\n\x19x_stats_cpu_logical_count\x18\xc3\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x37\n\x11x_stats_gpu_count\x18\xc4\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x37\n\x10x_stats_gpu_type\x18\xc5\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12?\n\x1ax_stats_track_process_tree\x18\xc6\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12.\n\x07x_label\x18\xb5\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\tx_primary\x18\xb6\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12:\n\x15x_update_finish_state\x18\xb7\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12<\n\x17\x61llow_offline_artifacts\x18\xb1\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12-\n\x07\x63onsole\x18< \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x36\n\x11\x63onsole_multipart\x18\xa6\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x35\n\x10sync_tensorboard\x18\xb3\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x42\n\x1dx_server_side_derived_summary\x18\xbd\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x46\n!x_server_side_expand_glob_metrics\x18\xbe\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12;\n\x16x_skip_transaction_log\x18\xbf\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12J\n#x_stats_coreweave_metadata_base_url\x18\xc0\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12J\n#x_stats_coreweave_metadata_endpoint\x18\xc1\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x0b_aws_lambda\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x33\n\x0fx_cli_only_mode\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12*\n\x06_colab\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x34\n\x10x_disable_viewer\x18\x0b \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x39\n\x15x_flow_control_custom\x18\x10 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12;\n\x17x_flow_control_disabled\x18\x11 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12>\n\x18x_internal_check_process\x18\x12 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12,\n\x08_ipython\x18\x14 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12,\n\x08_jupyter\x18\x15 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x34\n\x0ex_jupyter_root\x18\x16 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12+\n\x07_kaggle\x18\x17 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12=\n\x18x_live_policy_rate_limit\x18\x18 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12<\n\x17x_live_policy_wait_time\x18\x19 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x30\n\x0bx_log_level\x18\x1a \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x35\n\x10x_network_buffer\x18\x1b \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12)\n\x05_noop\x18\x1c \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12-\n\t_notebook\x18\x1d \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\t_platform\x18! \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x38\n\x12x_runqueue_item_id\x18# \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x37\n\x13x_save_requirements\x18% \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x39\n\x13x_service_transport\x18& \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x34\n\x0ex_service_wait\x18\' \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x35\n\x0f_start_datetime\x18( \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x33\n\r_tmp_code_dir\x18\x31 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x08_windows\x18\x34 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x34\n\x10\x61llow_val_change\x18\x35 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\tanonymous\x18\x36 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12P\n\x1f\x61zure_account_url_to_access_key\x18\x38 \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12.\n\x08\x63ode_dir\x18: \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0c\x63onfig_paths\x18; \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12\x30\n\ndeployment\x18= \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x30\n\x0c\x64isable_code\x18> \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x31\n\rdisable_hints\x18@ \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12,\n\x08\x64isabled\x18\x42 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12)\n\x05\x66orce\x18G \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x30\n\ngit_commit\x18H \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x30\n\ngit_remote\x18I \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x34\n\x0egit_remote_url\x18J \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x08git_root\x18K \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x36\n\x11heartbeat_seconds\x18L \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x32\n\x0cinit_timeout\x18O \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12,\n\x08is_local\x18P \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x30\n\njob_source\x18Q \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x31\n\rlabel_disable\x18R \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12*\n\x06launch\x18S \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x38\n\x12launch_config_path\x18T \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12:\n\x14log_symlink_internal\x18W \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x36\n\x10log_symlink_user\x18X \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x08log_user\x18Y \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x33\n\rlogin_timeout\x18Z \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12*\n\x04mode\x18\\ \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x33\n\rnotebook_name\x18] \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x31\n\x0bproject_url\x18\x62 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12)\n\x05quiet\x18\x63 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12+\n\x07relogin\x18\x65 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x32\n\x0cresume_fname\x18g \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12+\n\x07resumed\x18h \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\trun_group\x18j \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0crun_job_type\x18l \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x08run_mode\x18m \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x08run_name\x18n \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\trun_notes\x18o \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x31\n\x08run_tags\x18p \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12\x35\n\x11sagemaker_disable\x18r \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x35\n\x0fsettings_system\x18t \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x38\n\x12settings_workspace\x18u \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x0bshow_colors\x18v \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12.\n\nshow_emoji\x18w \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\x0bshow_errors\x18x \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12-\n\tshow_info\x18y \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x31\n\rshow_warnings\x18z \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12*\n\x06silent\x18{ \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x32\n\x0cstart_method\x18| \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12*\n\x06strict\x18} \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x33\n\x0esummary_errors\x18~ \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x34\n\x0fsummary_timeout\x18\x7f \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x36\n\x10summary_warnings\x18\x80\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12/\n\x08sweep_id\x18\x81\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x37\n\x10sweep_param_path\x18\x82\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x07symlink\x18\x84\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\x08sync_dir\x18\x85\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12:\n\x13sync_symlink_latest\x18\x87\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12J\n%table_raise_on_max_row_limit_exceeded\x18\x8a\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\x08timespec\x18\x8b\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x07tmp_dir\x18\x8c\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x30\n\twandb_dir\x18\x8e\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0ex_jupyter_name\x18\x8f\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0ex_jupyter_path\x18\x90\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x08job_name\x18\x91\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValueJ\x04\x08\x03\x10\x04J\x04\x08\x06\x10\x07J\x04\x08\x08\x10\tJ\x04\x08\t\x10\nJ\x04\x08\x0c\x10\rJ\x04\x08\x13\x10\x14J\x04\x08$\x10%J\x04\x08+\x10,J\x04\x08,\x10-J\x04\x08-\x10.J\x04\x08\x32\x10\x33J\x04\x08\x33\x10\x34J\x04\x08\x46\x10GJ\x04\x08[\x10\\J\x04\x08^\x10_J\x04\x08\x64\x10\x65J\x06\x08\x88\x01\x10\x89\x01J\x06\x08\x89\x01\x10\x8a\x01J\x06\x08\xad\x01\x10\xae\x01J\x06\x08\xb0\x01\x10\xb1\x01J\x06\x08\xb4\x01\x10\xb5\x01\x42\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_settings_pb2', _globals)
+if not _descriptor._USE_C_DESCRIPTORS:
+ _globals['DESCRIPTOR']._loaded_options = None
+ _globals['DESCRIPTOR']._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _globals['_MAPSTRINGKEYSTRINGVALUE_VALUEENTRY']._loaded_options = None
+ _globals['_MAPSTRINGKEYSTRINGVALUE_VALUEENTRY']._serialized_options = b'8\001'
+ _globals['_MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY']._loaded_options = None
+ _globals['_MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY']._serialized_options = b'8\001'
+ _globals['_LISTSTRINGVALUE']._serialized_start=84
+ _globals['_LISTSTRINGVALUE']._serialized_end=116
+ _globals['_LISTINTVALUE']._serialized_start=118
+ _globals['_LISTINTVALUE']._serialized_end=147
+ _globals['_MAPSTRINGKEYSTRINGVALUE']._serialized_start=150
+ _globals['_MAPSTRINGKEYSTRINGVALUE']._serialized_end=288
+ _globals['_MAPSTRINGKEYSTRINGVALUE_VALUEENTRY']._serialized_start=244
+ _globals['_MAPSTRINGKEYSTRINGVALUE_VALUEENTRY']._serialized_end=288
+ _globals['_MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE']._serialized_start=291
+ _globals['_MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE']._serialized_end=494
+ _globals['_MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY']._serialized_start=409
+ _globals['_MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY']._serialized_end=494
+ _globals['_OPENMETRICSFILTERS']._serialized_start=497
+ _globals['_OPENMETRICSFILTERS']._serialized_end=651
+ _globals['_RUNMOMENT']._serialized_start=653
+ _globals['_RUNMOMENT']._serialized_end=708
+ _globals['_SETTINGS']._serialized_start=711
+ _globals['_SETTINGS']._serialized_end=10633
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v6/wandb_sync_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v6/wandb_sync_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b36690cd36ec7ef422b146efd945d4fec43dc1f
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v6/wandb_sync_pb2.py
@@ -0,0 +1,53 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# NO CHECKED-IN PROTOBUF GENCODE
+# source: wandb/proto/wandb_sync.proto
+# Protobuf Python Version: 6.31.1
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import runtime_version as _runtime_version
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+_runtime_version.ValidateProtobufRuntimeVersion(
+ _runtime_version.Domain.PUBLIC,
+ 6,
+ 31,
+ 1,
+ '',
+ 'wandb/proto/wandb_sync.proto'
+)
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from wandb.proto import wandb_internal_pb2 as wandb_dot_proto_dot_wandb__internal__pb2
+from wandb.proto import wandb_settings_pb2 as wandb_dot_proto_dot_wandb__settings__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1cwandb/proto/wandb_sync.proto\x12\x0ewandb_internal\x1a wandb/proto/wandb_internal.proto\x1a wandb/proto/wandb_settings.proto\"Q\n\x15ServerInitSyncRequest\x12\x0c\n\x04path\x18\x01 \x03(\t\x12*\n\x08settings\x18\x02 \x01(\x0b\x32\x18.wandb_internal.Settings\"$\n\x16ServerInitSyncResponse\x12\n\n\x02id\x18\x01 \x01(\t\"4\n\x11ServerSyncRequest\x12\n\n\x02id\x18\x01 \x01(\t\x12\x13\n\x0bparallelism\x18\x02 \x01(\r\"I\n\x12ServerSyncResponse\x12\x33\n\x08messages\x18\x01 \x03(\x0b\x32!.wandb_internal.ServerSyncMessage\"%\n\x17ServerSyncStatusRequest\x12\n\n\x02id\x18\x01 \x01(\t\"\x82\x01\n\x18ServerSyncStatusResponse\x12-\n\x05stats\x18\x01 \x01(\x0b\x32\x1e.wandb_internal.OperationStats\x12\x37\n\x0cnew_messages\x18\x02 \x03(\x0b\x32!.wandb_internal.ServerSyncMessage\"\xaa\x01\n\x11ServerSyncMessage\x12<\n\x08severity\x18\x01 \x01(\x0e\x32*.wandb_internal.ServerSyncMessage.Severity\x12\x0f\n\x07\x63ontent\x18\x02 \x01(\t\"F\n\x08Severity\x12\x13\n\x0fSEVERITY_NOTSET\x10\x00\x12\x11\n\rSEVERITY_INFO\x10\x14\x12\x12\n\x0eSEVERITY_ERROR\x10(B\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_sync_pb2', _globals)
+if not _descriptor._USE_C_DESCRIPTORS:
+ _globals['DESCRIPTOR']._loaded_options = None
+ _globals['DESCRIPTOR']._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _globals['_SERVERINITSYNCREQUEST']._serialized_start=116
+ _globals['_SERVERINITSYNCREQUEST']._serialized_end=197
+ _globals['_SERVERINITSYNCRESPONSE']._serialized_start=199
+ _globals['_SERVERINITSYNCRESPONSE']._serialized_end=235
+ _globals['_SERVERSYNCREQUEST']._serialized_start=237
+ _globals['_SERVERSYNCREQUEST']._serialized_end=289
+ _globals['_SERVERSYNCRESPONSE']._serialized_start=291
+ _globals['_SERVERSYNCRESPONSE']._serialized_end=364
+ _globals['_SERVERSYNCSTATUSREQUEST']._serialized_start=366
+ _globals['_SERVERSYNCSTATUSREQUEST']._serialized_end=403
+ _globals['_SERVERSYNCSTATUSRESPONSE']._serialized_start=406
+ _globals['_SERVERSYNCSTATUSRESPONSE']._serialized_end=536
+ _globals['_SERVERSYNCMESSAGE']._serialized_start=539
+ _globals['_SERVERSYNCMESSAGE']._serialized_end=709
+ _globals['_SERVERSYNCMESSAGE_SEVERITY']._serialized_start=639
+ _globals['_SERVERSYNCMESSAGE_SEVERITY']._serialized_end=709
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v6/wandb_telemetry_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v6/wandb_telemetry_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f54564560142f4c8f8d14494cc40f6b129146b9
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/v6/wandb_telemetry_pb2.py
@@ -0,0 +1,52 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# NO CHECKED-IN PROTOBUF GENCODE
+# source: wandb/proto/wandb_telemetry.proto
+# Protobuf Python Version: 6.31.1
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import runtime_version as _runtime_version
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+_runtime_version.ValidateProtobufRuntimeVersion(
+ _runtime_version.Domain.PUBLIC,
+ 6,
+ 31,
+ 1,
+ '',
+ 'wandb/proto/wandb_telemetry.proto'
+)
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n!wandb/proto/wandb_telemetry.proto\x12\x0ewandb_internal\x1a\x1cwandb/proto/wandb_base.proto\"\xdb\x03\n\x0fTelemetryRecord\x12-\n\x0cimports_init\x18\x01 \x01(\x0b\x32\x17.wandb_internal.Imports\x12/\n\x0eimports_finish\x18\x02 \x01(\x0b\x32\x17.wandb_internal.Imports\x12(\n\x07\x66\x65\x61ture\x18\x03 \x01(\x0b\x32\x17.wandb_internal.Feature\x12\x16\n\x0epython_version\x18\x04 \x01(\t\x12\x13\n\x0b\x63li_version\x18\x05 \x01(\t\x12\x1b\n\x13huggingface_version\x18\x06 \x01(\t\x12 \n\x03\x65nv\x18\x08 \x01(\x0b\x32\x13.wandb_internal.Env\x12%\n\x05label\x18\t \x01(\x0b\x32\x16.wandb_internal.Labels\x12.\n\ndeprecated\x18\n \x01(\x0b\x32\x1a.wandb_internal.Deprecated\x12&\n\x06issues\x18\x0b \x01(\x0b\x32\x16.wandb_internal.Issues\x12\x14\n\x0c\x63ore_version\x18\x0c \x01(\t\x12\x10\n\x08platform\x18\r \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x11\n\x0fTelemetryResult\"\xa8\x0e\n\x07Imports\x12\r\n\x05torch\x18\x01 \x01(\x08\x12\r\n\x05keras\x18\x02 \x01(\x08\x12\x12\n\ntensorflow\x18\x03 \x01(\x08\x12\x0e\n\x06\x66\x61stai\x18\x04 \x01(\x08\x12\x0f\n\x07sklearn\x18\x05 \x01(\x08\x12\x0f\n\x07xgboost\x18\x06 \x01(\x08\x12\x10\n\x08\x63\x61tboost\x18\x07 \x01(\x08\x12\x10\n\x08lightgbm\x18\x08 \x01(\x08\x12\x19\n\x11pytorch_lightning\x18\t \x01(\x08\x12\x0e\n\x06ignite\x18\n \x01(\x08\x12\x14\n\x0ctransformers\x18\x0b \x01(\x08\x12\x0b\n\x03jax\x18\x0c \x01(\x08\x12\x10\n\x08metaflow\x18\r \x01(\x08\x12\x10\n\x08\x61llennlp\x18\x0e \x01(\x08\x12\x11\n\tautogluon\x18\x0f \x01(\x08\x12\x11\n\tautokeras\x18\x10 \x01(\x08\x12\x10\n\x08\x63\x61talyst\x18\x12 \x01(\x08\x12\x10\n\x08\x64\x65\x65pchem\x18\x15 \x01(\x08\x12\x0f\n\x07\x64\x65\x65pctr\x18\x16 \x01(\x08\x12\x0f\n\x07pycaret\x18\x1c \x01(\x08\x12\x14\n\x0cpytorchvideo\x18\x1d \x01(\x08\x12\x0b\n\x03ray\x18\x1e \x01(\x08\x12\x1a\n\x12simpletransformers\x18\x1f \x01(\x08\x12\x0e\n\x06skorch\x18 \x01(\x08\x12\r\n\x05spacy\x18! \x01(\x08\x12\r\n\x05\x66lash\x18\" \x01(\x08\x12\x0e\n\x06optuna\x18# \x01(\x08\x12\x0f\n\x07recbole\x18$ \x01(\x08\x12\x0c\n\x04mmcv\x18% \x01(\x08\x12\r\n\x05mmdet\x18& \x01(\x08\x12\x11\n\ttorchdrug\x18\' \x01(\x08\x12\x11\n\ttorchtext\x18( \x01(\x08\x12\x13\n\x0btorchvision\x18) \x01(\x08\x12\r\n\x05\x65legy\x18* \x01(\x08\x12\x12\n\ndetectron2\x18+ \x01(\x08\x12\r\n\x05\x66lair\x18, \x01(\x08\x12\x0c\n\x04\x66lax\x18- \x01(\x08\x12\x0c\n\x04syft\x18. \x01(\x08\x12\x0b\n\x03TTS\x18/ \x01(\x08\x12\r\n\x05monai\x18\x30 \x01(\x08\x12\x17\n\x0fhuggingface_hub\x18\x31 \x01(\x08\x12\r\n\x05hydra\x18\x32 \x01(\x08\x12\x10\n\x08\x64\x61tasets\x18\x33 \x01(\x08\x12\x0e\n\x06sacred\x18\x34 \x01(\x08\x12\x0e\n\x06joblib\x18\x35 \x01(\x08\x12\x0c\n\x04\x64\x61sk\x18\x36 \x01(\x08\x12\x11\n\tpaddleocr\x18\x38 \x01(\x08\x12\r\n\x05ppdet\x18\x39 \x01(\x08\x12\x11\n\tpaddleseg\x18: \x01(\x08\x12\x11\n\tpaddlenlp\x18; \x01(\x08\x12\r\n\x05mmseg\x18< \x01(\x08\x12\r\n\x05mmocr\x18= \x01(\x08\x12\r\n\x05mmcls\x18> \x01(\x08\x12\x0c\n\x04timm\x18? \x01(\x08\x12\x0f\n\x07\x66\x61irseq\x18@ \x01(\x08\x12\x12\n\ndeepchecks\x18\x41 \x01(\x08\x12\x10\n\x08\x63omposer\x18\x42 \x01(\x08\x12\x10\n\x08sparseml\x18\x43 \x01(\x08\x12\x10\n\x08\x61nomalib\x18\x44 \x01(\x08\x12\r\n\x05zenml\x18\x45 \x01(\x08\x12\x12\n\ncolossalai\x18\x46 \x01(\x08\x12\x12\n\naccelerate\x18G \x01(\x08\x12\x0e\n\x06merlin\x18H \x01(\x08\x12\x0f\n\x07nanodet\x18I \x01(\x08\x12#\n\x1bsegmentation_models_pytorch\x18J \x01(\x08\x12\x1d\n\x15sentence_transformers\x18K \x01(\x08\x12\x0b\n\x03\x64gl\x18L \x01(\x08\x12\x17\n\x0ftorch_geometric\x18M \x01(\x08\x12\x0c\n\x04jina\x18N \x01(\x08\x12\x0e\n\x06kornia\x18O \x01(\x08\x12\x16\n\x0e\x61lbumentations\x18P \x01(\x08\x12\x10\n\x08keras_cv\x18Q \x01(\x08\x12\x10\n\x08mmengine\x18R \x01(\x08\x12\x11\n\tdiffusers\x18S \x01(\x08\x12\x0b\n\x03trl\x18T \x01(\x08\x12\x0c\n\x04trlx\x18U \x01(\x08\x12\x11\n\tlangchain\x18V \x01(\x08\x12\x13\n\x0bllama_index\x18W \x01(\x08\x12\x15\n\rstability_sdk\x18X \x01(\x08\x12\x0f\n\x07prefect\x18Y \x01(\x08\x12\x13\n\x0bprefect_ray\x18Z \x01(\x08\x12\x10\n\x08pinecone\x18[ \x01(\x08\x12\x10\n\x08\x63hromadb\x18\\ \x01(\x08\x12\x10\n\x08weaviate\x18] \x01(\x08\x12\x13\n\x0bpromptlayer\x18^ \x01(\x08\x12\x0e\n\x06openai\x18_ \x01(\x08\x12\x0e\n\x06\x63ohere\x18` \x01(\x08\x12\x11\n\tanthropic\x18\x61 \x01(\x08\x12\x0c\n\x04peft\x18\x62 \x01(\x08\x12\x0f\n\x07optimum\x18\x63 \x01(\x08\x12\x10\n\x08\x65valuate\x18\x64 \x01(\x08\x12\x10\n\x08langflow\x18\x65 \x01(\x08\x12\x12\n\nkeras_core\x18\x66 \x01(\x08\x12\x18\n\x10lightning_fabric\x18g \x01(\x08\x12\x1c\n\x14\x63urated_transformers\x18h \x01(\x08\x12\x0e\n\x06orjson\x18i \x01(\x08\x12\x11\n\tlightning\x18j \x01(\x08\x12\x0c\n\x04\x64spy\x18k \x01(\x08J\x04\x08\x11\x10\x12J\x04\x08\x13\x10\x14J\x04\x08\x14\x10\x15J\x04\x08\x17\x10\x18J\x04\x08\x18\x10\x19J\x04\x08\x19\x10\x1aJ\x04\x08\x1a\x10\x1bJ\x04\x08\x1b\x10\x1cJ\x04\x08\x37\x10\x38\"\xac\r\n\x07\x46\x65\x61ture\x12\r\n\x05watch\x18\x01 \x01(\x08\x12\x0e\n\x06\x66inish\x18\x02 \x01(\x08\x12\x0c\n\x04save\x18\x03 \x01(\x08\x12\x0f\n\x07offline\x18\x04 \x01(\x08\x12\x0f\n\x07resumed\x18\x05 \x01(\x08\x12\x0c\n\x04grpc\x18\x06 \x01(\x08\x12\x0e\n\x06metric\x18\x07 \x01(\x08\x12\r\n\x05keras\x18\x08 \x01(\x08\x12\x11\n\tsagemaker\x18\t \x01(\x08\x12\x1c\n\x14\x61rtifact_incremental\x18\n \x01(\x08\x12\x10\n\x08metaflow\x18\x0b \x01(\x08\x12\x0f\n\x07prodigy\x18\x0c \x01(\x08\x12\x15\n\rset_init_name\x18\r \x01(\x08\x12\x13\n\x0bset_init_id\x18\x0e \x01(\x08\x12\x15\n\rset_init_tags\x18\x0f \x01(\x08\x12\x17\n\x0fset_init_config\x18\x10 \x01(\x08\x12\x14\n\x0cset_run_name\x18\x11 \x01(\x08\x12\x14\n\x0cset_run_tags\x18\x12 \x01(\x08\x12\x17\n\x0fset_config_item\x18\x13 \x01(\x08\x12\x0e\n\x06launch\x18\x14 \x01(\x08\x12\x1c\n\x14torch_profiler_trace\x18\x15 \x01(\x08\x12\x0b\n\x03sb3\x18\x16 \x01(\x08\x12\x17\n\x0finit_return_run\x18\x18 \x01(\x08\x12\x1f\n\x17lightgbm_wandb_callback\x18\x19 \x01(\x08\x12\x1c\n\x14lightgbm_log_summary\x18\x1a \x01(\x08\x12\x1f\n\x17\x63\x61tboost_wandb_callback\x18\x1b \x01(\x08\x12\x1c\n\x14\x63\x61tboost_log_summary\x18\x1c \x01(\x08\x12\x17\n\x0ftensorboard_log\x18\x1d \x01(\x08\x12\x16\n\x0e\x65stimator_hook\x18\x1e \x01(\x08\x12\x1e\n\x16xgboost_wandb_callback\x18\x1f \x01(\x08\x12\"\n\x1axgboost_old_wandb_callback\x18 \x01(\x08\x12\x0e\n\x06\x61ttach\x18! \x01(\x08\x12\x19\n\x11tensorboard_patch\x18\" \x01(\x08\x12\x18\n\x10tensorboard_sync\x18# \x01(\x08\x12\x15\n\rkfp_wandb_log\x18$ \x01(\x08\x12\x1b\n\x13maybe_run_overwrite\x18% \x01(\x08\x12\x1c\n\x14keras_metrics_logger\x18& \x01(\x08\x12\x1e\n\x16keras_model_checkpoint\x18\' \x01(\x08\x12!\n\x19keras_wandb_eval_callback\x18( \x01(\x08\x12\x1d\n\x15\x66low_control_overflow\x18) \x01(\x08\x12\x0c\n\x04sync\x18* \x01(\x08\x12\x1d\n\x15\x66low_control_disabled\x18+ \x01(\x08\x12\x1b\n\x13\x66low_control_custom\x18, \x01(\x08\x12\x14\n\x0copen_metrics\x18. \x01(\x08\x12\x1a\n\x12ultralytics_yolov8\x18/ \x01(\x08\x12\x17\n\x0fimporter_mlflow\x18\x30 \x01(\x08\x12\x15\n\rsync_tfevents\x18\x31 \x01(\x08\x12\x15\n\rasync_uploads\x18\x32 \x01(\x08\x12\x16\n\x0eopenai_autolog\x18\x33 \x01(\x08\x12\x18\n\x10langchain_tracer\x18\x34 \x01(\x08\x12\x16\n\x0e\x63ohere_autolog\x18\x35 \x01(\x08\x12\x1b\n\x13hf_pipeline_autolog\x18\x36 \x01(\x08\x12\r\n\x05lib_c\x18\x38 \x01(\x08\x12\x0f\n\x07lib_cpp\x18\x39 \x01(\x08\x12\x19\n\x11openai_finetuning\x18: \x01(\x08\x12\x19\n\x11\x64iffusers_autolog\x18; \x01(\x08\x12\x1f\n\x17lightning_fabric_logger\x18< \x01(\x08\x12\x14\n\x0cset_step_log\x18= \x01(\x08\x12\x13\n\x0bset_summary\x18> \x01(\x08\x12\x16\n\x0emetric_summary\x18? \x01(\x08\x12\x13\n\x0bmetric_goal\x18@ \x01(\x08\x12\x15\n\rmetric_hidden\x18\x41 \x01(\x08\x12\x18\n\x10metric_step_sync\x18\x42 \x01(\x08\x12\x13\n\x0bshared_mode\x18\x43 \x01(\x08\x12#\n\x1bserver_side_derived_summary\x18\x44 \x01(\x08\x12\x1b\n\x13user_provided_label\x18\x45 \x01(\x08\x12\x1e\n\x16\x64\x63gm_profiling_enabled\x18\x46 \x01(\x08\x12\x11\n\tfork_mode\x18G \x01(\x08\x12\x13\n\x0brewind_mode\x18H \x01(\x08\x12\x15\n\rdspy_callback\x18I \x01(\x08J\x04\x08\x17\x10\x18J\x04\x08-\x10.J\x04\x08\x37\x10\x38\"\xc9\x01\n\x03\x45nv\x12\x0f\n\x07jupyter\x18\x01 \x01(\x08\x12\x0e\n\x06kaggle\x18\x02 \x01(\x08\x12\x0f\n\x07windows\x18\x03 \x01(\x08\x12\x0e\n\x06m1_gpu\x18\x04 \x01(\x08\x12\x10\n\x08trainium\x18\n \x01(\x08\x12\x0b\n\x03pex\x18\x0b \x01(\x08\x12\r\n\x05\x63olab\x18\x0c \x01(\x08\x12\x0f\n\x07ipython\x18\r \x01(\x08\x12\x12\n\naws_lambda\x18\x0e \x01(\x08\x12\x0f\n\x07\x61md_gpu\x18\x0f \x01(\x08J\x04\x08\x05\x10\x06J\x04\x08\x06\x10\x07J\x04\x08\x07\x10\x08J\x04\x08\x08\x10\tJ\x04\x08\t\x10\n\"H\n\x06Labels\x12\x13\n\x0b\x63ode_string\x18\x01 \x01(\t\x12\x13\n\x0brepo_string\x18\x02 \x01(\t\x12\x14\n\x0c\x63ode_version\x18\x03 \x01(\t\"\xc2\x06\n\nDeprecated\x12!\n\x19keras_callback__data_type\x18\x01 \x01(\x08\x12\r\n\x05plots\x18\x05 \x01(\x08\x12!\n\x19init__config_include_keys\x18\x07 \x01(\x08\x12!\n\x19init__config_exclude_keys\x18\x08 \x01(\x08\x12\"\n\x1akeras_callback__save_model\x18\t \x01(\x08\x12\x18\n\x10langchain_tracer\x18\n \x01(\x08\x12\x1a\n\x12\x61rtifact__get_path\x18\x0b \x01(\x08\x12#\n\x1b\x61rtifactmanifestentry__name\x18\x0c \x01(\x08\x12\x1e\n\x16\x61pi__artifact_versions\x18\r \x01(\x08\x12(\n artifact_collection__change_type\x18\x0e \x01(\x08\x12\x1f\n\x17run__define_metric_copy\x18\x0f \x01(\x08\x12\x14\n\x0crun_disabled\x18\x10 \x01(\x08\x12\x16\n\x0ekeras_callback\x18\x11 \x01(\x08\x12$\n\x1crun__define_metric_best_goal\x18\x12 \x01(\x08\x12\x19\n\x11run__finish_quiet\x18\x13 \x01(\x08\x12\x18\n\x10run__reinit_bool\x18\x14 \x01(\x08\x12\x14\n\x0crun__get_url\x18\x15 \x01(\x08\x12\x19\n\x11run__project_name\x18\x16 \x01(\x08\x12\x1c\n\x14run__get_project_url\x18\x17 \x01(\x08\x12\x1a\n\x12run__get_sweep_url\x18\x18 \x01(\x08\x12 \n\x18run__use_artifact_use_as\x18\x19 \x01(\x08\x12\x18\n\x10\x61rtifact__use_as\x18\x1a \x01(\x08\x12\x1d\n\x15\x61rtifact__init_use_as\x18\x1b \x01(\x08\x12\"\n\x1a\x62\x65ta__workflows__log_model\x18\x1c \x01(\x08\x12\"\n\x1a\x62\x65ta__workflows__use_model\x18\x1d \x01(\x08\x12#\n\x1b\x62\x65ta__workflows__link_model\x18\x1e \x01(\x08J\x04\x08\x02\x10\x03J\x04\x08\x03\x10\x04J\x04\x08\x04\x10\x05J\x04\x08\x06\x10\x07\"|\n\x06Issues\x12%\n\x1dsettings__validation_warnings\x18\x01 \x01(\x08\x12!\n\x19settings__unexpected_args\x18\x02 \x01(\x08\x12(\n settings__preprocessing_warnings\x18\x03 \x01(\x08\x42\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_telemetry_pb2', _globals)
+if not _descriptor._USE_C_DESCRIPTORS:
+ _globals['DESCRIPTOR']._loaded_options = None
+ _globals['DESCRIPTOR']._serialized_options = b'Z\031core/pkg/service_go_proto'
+ _globals['_TELEMETRYRECORD']._serialized_start=84
+ _globals['_TELEMETRYRECORD']._serialized_end=559
+ _globals['_TELEMETRYRESULT']._serialized_start=561
+ _globals['_TELEMETRYRESULT']._serialized_end=578
+ _globals['_IMPORTS']._serialized_start=581
+ _globals['_IMPORTS']._serialized_end=2413
+ _globals['_FEATURE']._serialized_start=2416
+ _globals['_FEATURE']._serialized_end=4124
+ _globals['_ENV']._serialized_start=4127
+ _globals['_ENV']._serialized_end=4328
+ _globals['_LABELS']._serialized_start=4330
+ _globals['_LABELS']._serialized_end=4402
+ _globals['_DEPRECATED']._serialized_start=4405
+ _globals['_DEPRECATED']._serialized_end=5239
+ _globals['_ISSUES']._serialized_start=5241
+ _globals['_ISSUES']._serialized_end=5365
+# @@protoc_insertion_point(module_scope)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_api_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_api_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..40b7e8a2d01173ec5433da8361fd9ae280956df5
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_api_pb2.py
@@ -0,0 +1,18 @@
+import google.protobuf
+
+protobuf_version = google.protobuf.__version__[0]
+
+if protobuf_version == "3":
+ from wandb.proto.v3.wandb_api_pb2 import *
+elif protobuf_version == "4":
+ from wandb.proto.v4.wandb_api_pb2 import *
+elif protobuf_version == "5":
+ from wandb.proto.v5.wandb_api_pb2 import *
+elif protobuf_version == "6":
+ from wandb.proto.v6.wandb_api_pb2 import *
+else:
+ raise ImportError(
+ "Failed to import protobufs for protobuf version"
+ f" {google.protobuf.__version__}. `wandb` only works with major"
+ " versions 3, 4, 5, and 6 of the protobuf package.",
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_base_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_base_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b2ae6b240436e0da0d94ffda7c4a150d24dc54f
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_base_pb2.py
@@ -0,0 +1,12 @@
+import google.protobuf
+
+protobuf_version = google.protobuf.__version__[0]
+
+if protobuf_version == "3":
+ from wandb.proto.v3.wandb_base_pb2 import *
+elif protobuf_version == "4":
+ from wandb.proto.v4.wandb_base_pb2 import *
+elif protobuf_version == "5":
+ from wandb.proto.v5.wandb_base_pb2 import *
+elif protobuf_version == "6":
+ from wandb.proto.v6.wandb_base_pb2 import *
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_deprecated.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_deprecated.py
new file mode 100644
index 0000000000000000000000000000000000000000..4365dfa31f2364b6132344c9d411f78b48ce693c
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_deprecated.py
@@ -0,0 +1,59 @@
+# Generated by wandb/proto/wandb_internal_codegen.py. DO NOT EDIT!
+
+from typing import Literal
+DEPRECATED_FEATURES = Literal[
+ "keras_callback__data_type",
+ "plots",
+ "init__config_include_keys",
+ "init__config_exclude_keys",
+ "keras_callback__save_model",
+ "langchain_tracer",
+ "artifact__get_path",
+ "artifactmanifestentry__name",
+ "api__artifact_versions",
+ "artifact_collection__change_type",
+ "run__define_metric_copy",
+ "run_disabled",
+ "keras_callback",
+ "run__define_metric_best_goal",
+ "run__finish_quiet",
+ "run__reinit_bool",
+ "run__get_url",
+ "run__project_name",
+ "run__get_project_url",
+ "run__get_sweep_url",
+ "run__use_artifact_use_as",
+ "artifact__use_as",
+ "artifact__init_use_as",
+ "beta__workflows__log_model",
+ "beta__workflows__use_model",
+ "beta__workflows__link_model",
+]
+
+class Deprecated:
+ keras_callback__data_type: DEPRECATED_FEATURES = "keras_callback__data_type"
+ plots: DEPRECATED_FEATURES = "plots"
+ init__config_include_keys: DEPRECATED_FEATURES = "init__config_include_keys"
+ init__config_exclude_keys: DEPRECATED_FEATURES = "init__config_exclude_keys"
+ keras_callback__save_model: DEPRECATED_FEATURES = "keras_callback__save_model"
+ langchain_tracer: DEPRECATED_FEATURES = "langchain_tracer"
+ artifact__get_path: DEPRECATED_FEATURES = "artifact__get_path"
+ artifactmanifestentry__name: DEPRECATED_FEATURES = "artifactmanifestentry__name"
+ api__artifact_versions: DEPRECATED_FEATURES = "api__artifact_versions"
+ artifact_collection__change_type: DEPRECATED_FEATURES = "artifact_collection__change_type"
+ run__define_metric_copy: DEPRECATED_FEATURES = "run__define_metric_copy"
+ run_disabled: DEPRECATED_FEATURES = "run_disabled"
+ keras_callback: DEPRECATED_FEATURES = "keras_callback"
+ run__define_metric_best_goal: DEPRECATED_FEATURES = "run__define_metric_best_goal"
+ run__finish_quiet: DEPRECATED_FEATURES = "run__finish_quiet"
+ run__reinit_bool: DEPRECATED_FEATURES = "run__reinit_bool"
+ run__get_url: DEPRECATED_FEATURES = "run__get_url"
+ run__project_name: DEPRECATED_FEATURES = "run__project_name"
+ run__get_project_url: DEPRECATED_FEATURES = "run__get_project_url"
+ run__get_sweep_url: DEPRECATED_FEATURES = "run__get_sweep_url"
+ run__use_artifact_use_as: DEPRECATED_FEATURES = "run__use_artifact_use_as"
+ artifact__use_as: DEPRECATED_FEATURES = "artifact__use_as"
+ artifact__init_use_as: DEPRECATED_FEATURES = "artifact__init_use_as"
+ beta__workflows__log_model: DEPRECATED_FEATURES = "beta__workflows__log_model"
+ beta__workflows__use_model: DEPRECATED_FEATURES = "beta__workflows__use_model"
+ beta__workflows__link_model: DEPRECATED_FEATURES = "beta__workflows__link_model"
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_generate_deprecated.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_generate_deprecated.py
new file mode 100644
index 0000000000000000000000000000000000000000..23240018155a6bdf1f933439382c4aefc9d479a5
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_generate_deprecated.py
@@ -0,0 +1,30 @@
+#!/usr/bin/env python
+
+
+def generate_deprecated_class_definition() -> None:
+ """Generate a class definition listing the deprecated features.
+ This is to allow static checks to ensure that proper field names are used.
+ """
+ from wandb.proto.wandb_telemetry_pb2 import Deprecated # type: ignore[import]
+
+ deprecated_features = Deprecated.DESCRIPTOR.fields_by_name.keys()
+
+ code: str = (
+ "# Generated by wandb/proto/wandb_internal_codegen.py. DO NOT EDIT!\n\n"
+ "from typing import Literal\n"
+ "DEPRECATED_FEATURES = Literal[\n"
+ + ",\n".join(f' "{feature}"' for feature in deprecated_features)
+ + ",\n"
+ + "]\n\n"
+ "class Deprecated:\n"
+ + "".join(
+ [
+ f' {feature}: DEPRECATED_FEATURES = "{feature}"\n'
+ for feature in deprecated_features
+ ]
+ )
+ )
+ with open("wandb_deprecated.py", "w") as f:
+ f.write(code)
+
+generate_deprecated_class_definition()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_generate_proto.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_generate_proto.py
new file mode 100644
index 0000000000000000000000000000000000000000..71ac23beca489552886b4f6e0feecbd29b00bff3
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_generate_proto.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+
+import importlib.metadata
+import os
+import pathlib
+
+import grpc_tools # type: ignore
+from grpc_tools import protoc # type: ignore
+from packaging import version
+
+
+def get_pip_package_version(package_name: str) -> str:
+ try:
+ return importlib.metadata.version(package_name)
+ except importlib.metadata.PackageNotFoundError:
+ raise ValueError(f"Package `{package_name}` not found")
+
+protobuf_version = version.Version(get_pip_package_version("protobuf"))
+
+proto_root = os.path.join(os.path.dirname(grpc_tools.__file__), "_proto")
+tmp_out: pathlib.Path = pathlib.Path(f"wandb/proto/v{protobuf_version.major}/")
+
+os.chdir("../..")
+for proto_file in [
+ "wandb_base.proto",
+ "wandb_internal.proto",
+ "wandb_settings.proto",
+ "wandb_telemetry.proto",
+ "wandb_server.proto",
+ "wandb_sync.proto",
+ "wandb_api.proto",
+]:
+ ret = protoc.main(
+ (
+ "",
+ "-I",
+ proto_root,
+ "-I",
+ ".",
+ f"--python_out={tmp_out}",
+ f"--mypy_out={tmp_out}",
+ f"wandb/proto/{proto_file}",
+ )
+ )
+ assert not ret
+
+# clean up tmp dirs
+for p in (tmp_out / "wandb" / "proto").glob("*pb2*"):
+ p.rename(tmp_out / p.name)
+os.rmdir(tmp_out / "wandb" / "proto")
+os.rmdir(tmp_out / "wandb")
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_internal_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_internal_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..97cbe72e2148955f2aaa357053905e81ccfc5825
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_internal_pb2.py
@@ -0,0 +1,18 @@
+import google.protobuf
+
+protobuf_version = google.protobuf.__version__[0]
+
+if protobuf_version == "3":
+ from wandb.proto.v3.wandb_internal_pb2 import *
+elif protobuf_version == "4":
+ from wandb.proto.v4.wandb_internal_pb2 import *
+elif protobuf_version == "5":
+ from wandb.proto.v5.wandb_internal_pb2 import *
+elif protobuf_version == "6":
+ from wandb.proto.v6.wandb_internal_pb2 import *
+else:
+ raise ImportError(
+ "Failed to import protobufs for protobuf version"
+ f" {google.protobuf.__version__}. `wandb` only works with major"
+ " versions 3, 4, 5, and 6 of the protobuf package.",
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_server_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_server_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..d30616eb0902a99ce4180d7760a975b3e4383bc7
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_server_pb2.py
@@ -0,0 +1,12 @@
+import google.protobuf
+
+protobuf_version = google.protobuf.__version__[0]
+
+if protobuf_version == "3":
+ from wandb.proto.v3.wandb_server_pb2 import *
+elif protobuf_version == "4":
+ from wandb.proto.v4.wandb_server_pb2 import *
+elif protobuf_version == "5":
+ from wandb.proto.v5.wandb_server_pb2 import *
+elif protobuf_version == "6":
+ from wandb.proto.v6.wandb_server_pb2 import *
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_settings_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_settings_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..0600cc522c3e7dae1222d19779652da44010a100
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_settings_pb2.py
@@ -0,0 +1,12 @@
+import google.protobuf
+
+protobuf_version = google.protobuf.__version__[0]
+
+if protobuf_version == "3":
+ from wandb.proto.v3.wandb_settings_pb2 import *
+elif protobuf_version == "4":
+ from wandb.proto.v4.wandb_settings_pb2 import *
+elif protobuf_version == "5":
+ from wandb.proto.v5.wandb_settings_pb2 import *
+elif protobuf_version == "6":
+ from wandb.proto.v6.wandb_settings_pb2 import *
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_sync_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_sync_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..119b214a76c18efe2e96d4b4e23c2a500a17b94f
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_sync_pb2.py
@@ -0,0 +1,12 @@
+import google.protobuf
+
+protobuf_version = google.protobuf.__version__[0]
+
+if protobuf_version == "3":
+ from wandb.proto.v3.wandb_sync_pb2 import *
+elif protobuf_version == "4":
+ from wandb.proto.v4.wandb_sync_pb2 import *
+elif protobuf_version == "5":
+ from wandb.proto.v5.wandb_sync_pb2 import *
+elif protobuf_version == "6":
+ from wandb.proto.v6.wandb_sync_pb2 import *
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_telemetry_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_telemetry_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..19c81ce3f03a8906b4108f3f9f5d602d2b84f792
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/proto/wandb_telemetry_pb2.py
@@ -0,0 +1,12 @@
+import google.protobuf
+
+protobuf_version = google.protobuf.__version__[0]
+
+if protobuf_version == "3":
+ from wandb.proto.v3.wandb_telemetry_pb2 import *
+elif protobuf_version == "4":
+ from wandb.proto.v4.wandb_telemetry_pb2 import *
+elif protobuf_version == "5":
+ from wandb.proto.v5.wandb_telemetry_pb2 import *
+elif protobuf_version == "6":
+ from wandb.proto.v6.wandb_telemetry_pb2 import *
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/py.typed b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..94e25e9daca3c691b28af748aa8b21ea84be5707
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/__init__.py
@@ -0,0 +1,37 @@
+"""W&B SDK module."""
+
+__all__ = (
+ "Config",
+ "Settings",
+ "Summary",
+ "Artifact",
+ "AlertLevel",
+ "init",
+ "setup",
+ "_attach",
+ "_sync",
+ "login",
+ "require",
+ "finish",
+ "teardown",
+ "_watch",
+ "_unwatch",
+ "sweep",
+ "controller",
+ "helper",
+)
+
+from . import wandb_helper as helper
+from .artifacts.artifact import Artifact
+from .wandb_alerts import AlertLevel
+from .wandb_config import Config
+from .wandb_init import _attach, init
+from .wandb_login import login
+from .wandb_require import require
+from .wandb_run import finish
+from .wandb_settings import Settings
+from .wandb_setup import setup, teardown
+from .wandb_summary import Summary
+from .wandb_sweep import controller, sweep
+from .wandb_sync import _sync
+from .wandb_watch import _unwatch, _watch
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_factories.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_factories.py
new file mode 100644
index 0000000000000000000000000000000000000000..de611fc971d2438a861d6640f6af187463aa9ca3
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_factories.py
@@ -0,0 +1,22 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from wandb import env
+
+from .storage_layout import StorageLayout
+from .storage_policies import WandbStoragePolicy
+
+if TYPE_CHECKING:
+ from .storage_policy import StoragePolicy
+
+
+def make_storage_policy(storage_region: str | None = None) -> StoragePolicy:
+ """A factory function that returns the default StoragePolicy for the current environment."""
+ layout = StorageLayout.V1 if env.get_use_v1_artifacts() else StorageLayout.V2
+ config = {"storageLayout": layout}
+ # Only set storage region if is not None for backward compatibility
+ # Validation such as non empty string is done in WandbStoragePolicy.__init__
+ if storage_region is not None:
+ config["storageRegion"] = storage_region
+ return WandbStoragePolicy.from_config(config)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf792389c7dab0bf6fa2e0418ce9dfc1f9501817
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/__init__.py
@@ -0,0 +1,208 @@
+# Generated by ariadne-codegen
+
+__all__ = [
+ "ADD_ALIASES_GQL",
+ "ARTIFACT_BY_ID_GQL",
+ "ARTIFACT_BY_NAME_GQL",
+ "ARTIFACT_COLLECTION_MEMBERSHIP_FILES_GQL",
+ "ARTIFACT_COLLECTION_MEMBERSHIP_FILE_URLS_GQL",
+ "ARTIFACT_CREATED_BY_GQL",
+ "ARTIFACT_FILE_URLS_GQL",
+ "ARTIFACT_TYPE_GQL",
+ "ARTIFACT_USED_BY_GQL",
+ "ARTIFACT_VERSION_FILES_GQL",
+ "ARTIFACT_VIA_MEMBERSHIP_BY_NAME_GQL",
+ "CREATE_ARTIFACT_COLLECTION_TAG_ASSIGNMENTS_GQL",
+ "DELETE_ALIASES_GQL",
+ "DELETE_ARTIFACT_COLLECTION_TAG_ASSIGNMENTS_GQL",
+ "DELETE_ARTIFACT_GQL",
+ "DELETE_ARTIFACT_PORTFOLIO_GQL",
+ "DELETE_ARTIFACT_SEQUENCE_GQL",
+ "FETCH_ARTIFACT_MANIFEST_GQL",
+ "FETCH_LINKED_ARTIFACTS_GQL",
+ "FETCH_REGISTRIES_GQL",
+ "LINK_ARTIFACT_GQL",
+ "MOVE_ARTIFACT_COLLECTION_GQL",
+ "PROJECT_ARTIFACTS_GQL",
+ "PROJECT_ARTIFACT_COLLECTIONS_GQL",
+ "PROJECT_ARTIFACT_COLLECTION_GQL",
+ "PROJECT_ARTIFACT_TYPES_GQL",
+ "PROJECT_ARTIFACT_TYPE_GQL",
+ "REGISTRY_COLLECTIONS_GQL",
+ "REGISTRY_VERSIONS_GQL",
+ "RUN_INPUT_ARTIFACTS_GQL",
+ "RUN_OUTPUT_ARTIFACTS_GQL",
+ "TYPE_INFO_GQL",
+ "UNLINK_ARTIFACT_GQL",
+ "UPDATE_ARTIFACT_GQL",
+ "UPDATE_ARTIFACT_PORTFOLIO_GQL",
+ "UPDATE_ARTIFACT_SEQUENCE_GQL",
+ "DeleteArtifactSequence",
+ "DeleteArtifactPortfolio",
+ "UpdateArtifactSequence",
+ "UpdateArtifactPortfolio",
+ "MoveArtifactCollection",
+ "CreateArtifactCollectionTagAssignments",
+ "DeleteArtifactCollectionTagAssignments",
+ "ProjectArtifactCollections",
+ "ProjectArtifactCollection",
+ "ArtifactVersionFiles",
+ "ArtifactCollectionMembershipFiles",
+ "ArtifactCollectionMembershipFileUrls",
+ "ArtifactFileUrls",
+ "ProjectArtifactTypes",
+ "ProjectArtifactType",
+ "ProjectArtifacts",
+ "RunOutputArtifacts",
+ "RunInputArtifacts",
+ "FetchLinkedArtifacts",
+ "FetchArtifactManifest",
+ "ArtifactByID",
+ "ArtifactByName",
+ "ArtifactViaMembershipByName",
+ "ArtifactUsedBy",
+ "ArtifactCreatedBy",
+ "ArtifactType",
+ "AddAliases",
+ "DeleteAliases",
+ "UpdateArtifact",
+ "DeleteArtifact",
+ "LinkArtifact",
+ "UnlinkArtifact",
+ "TypeInfo",
+ "RegistryVersions",
+ "RegistryCollections",
+ "FetchRegistries",
+ "ArtifactAliasInput",
+ "ArtifactCollectionAliasInput",
+ "LinkArtifactInput",
+ "TagInput",
+ "ArtifactCollectionsFragment",
+ "ArtifactFragment",
+ "ArtifactFragmentWithoutAliases",
+ "ArtifactPortfolioTypeFields",
+ "ArtifactSequenceTypeFields",
+ "ArtifactTypeFragment",
+ "ArtifactTypesFragment",
+ "ArtifactsFragment",
+ "FileUrlsFragment",
+ "FilesFragment",
+ "MembershipWithArtifact",
+ "RegistriesPage",
+ "RegistryCollectionsPage",
+ "RegistryFragment",
+ "RegistryVersionsPage",
+ "RunInputArtifactConnectionFragment",
+ "RunOutputArtifactConnectionFragment",
+ "TypeInfoFragment",
+ "ArtifactCollectionState",
+ "ArtifactCollectionType",
+ "ArtifactState",
+]
+from .add_aliases import AddAliases
+from .artifact_by_id import ArtifactByID
+from .artifact_by_name import ArtifactByName
+from .artifact_collection_membership_file_urls import (
+ ArtifactCollectionMembershipFileUrls,
+)
+from .artifact_collection_membership_files import ArtifactCollectionMembershipFiles
+from .artifact_created_by import ArtifactCreatedBy
+from .artifact_file_urls import ArtifactFileUrls
+from .artifact_type import ArtifactType
+from .artifact_used_by import ArtifactUsedBy
+from .artifact_version_files import ArtifactVersionFiles
+from .artifact_via_membership_by_name import ArtifactViaMembershipByName
+from .create_artifact_collection_tag_assignments import (
+ CreateArtifactCollectionTagAssignments,
+)
+from .delete_aliases import DeleteAliases
+from .delete_artifact import DeleteArtifact
+from .delete_artifact_collection_tag_assignments import (
+ DeleteArtifactCollectionTagAssignments,
+)
+from .delete_artifact_portfolio import DeleteArtifactPortfolio
+from .delete_artifact_sequence import DeleteArtifactSequence
+from .enums import ArtifactCollectionState, ArtifactCollectionType, ArtifactState
+from .fetch_artifact_manifest import FetchArtifactManifest
+from .fetch_linked_artifacts import FetchLinkedArtifacts
+from .fetch_registries import FetchRegistries
+from .fragments import (
+ ArtifactCollectionsFragment,
+ ArtifactFragment,
+ ArtifactFragmentWithoutAliases,
+ ArtifactPortfolioTypeFields,
+ ArtifactSequenceTypeFields,
+ ArtifactsFragment,
+ ArtifactTypeFragment,
+ ArtifactTypesFragment,
+ FilesFragment,
+ FileUrlsFragment,
+ MembershipWithArtifact,
+ RegistriesPage,
+ RegistryCollectionsPage,
+ RegistryFragment,
+ RegistryVersionsPage,
+ RunInputArtifactConnectionFragment,
+ RunOutputArtifactConnectionFragment,
+ TypeInfoFragment,
+)
+from .input_types import (
+ ArtifactAliasInput,
+ ArtifactCollectionAliasInput,
+ LinkArtifactInput,
+ TagInput,
+)
+from .link_artifact import LinkArtifact
+from .move_artifact_collection import MoveArtifactCollection
+from .operations import (
+ ADD_ALIASES_GQL,
+ ARTIFACT_BY_ID_GQL,
+ ARTIFACT_BY_NAME_GQL,
+ ARTIFACT_COLLECTION_MEMBERSHIP_FILE_URLS_GQL,
+ ARTIFACT_COLLECTION_MEMBERSHIP_FILES_GQL,
+ ARTIFACT_CREATED_BY_GQL,
+ ARTIFACT_FILE_URLS_GQL,
+ ARTIFACT_TYPE_GQL,
+ ARTIFACT_USED_BY_GQL,
+ ARTIFACT_VERSION_FILES_GQL,
+ ARTIFACT_VIA_MEMBERSHIP_BY_NAME_GQL,
+ CREATE_ARTIFACT_COLLECTION_TAG_ASSIGNMENTS_GQL,
+ DELETE_ALIASES_GQL,
+ DELETE_ARTIFACT_COLLECTION_TAG_ASSIGNMENTS_GQL,
+ DELETE_ARTIFACT_GQL,
+ DELETE_ARTIFACT_PORTFOLIO_GQL,
+ DELETE_ARTIFACT_SEQUENCE_GQL,
+ FETCH_ARTIFACT_MANIFEST_GQL,
+ FETCH_LINKED_ARTIFACTS_GQL,
+ FETCH_REGISTRIES_GQL,
+ LINK_ARTIFACT_GQL,
+ MOVE_ARTIFACT_COLLECTION_GQL,
+ PROJECT_ARTIFACT_COLLECTION_GQL,
+ PROJECT_ARTIFACT_COLLECTIONS_GQL,
+ PROJECT_ARTIFACT_TYPE_GQL,
+ PROJECT_ARTIFACT_TYPES_GQL,
+ PROJECT_ARTIFACTS_GQL,
+ REGISTRY_COLLECTIONS_GQL,
+ REGISTRY_VERSIONS_GQL,
+ RUN_INPUT_ARTIFACTS_GQL,
+ RUN_OUTPUT_ARTIFACTS_GQL,
+ TYPE_INFO_GQL,
+ UNLINK_ARTIFACT_GQL,
+ UPDATE_ARTIFACT_GQL,
+ UPDATE_ARTIFACT_PORTFOLIO_GQL,
+ UPDATE_ARTIFACT_SEQUENCE_GQL,
+)
+from .project_artifact_collection import ProjectArtifactCollection
+from .project_artifact_collections import ProjectArtifactCollections
+from .project_artifact_type import ProjectArtifactType
+from .project_artifact_types import ProjectArtifactTypes
+from .project_artifacts import ProjectArtifacts
+from .registry_collections import RegistryCollections
+from .registry_versions import RegistryVersions
+from .run_input_artifacts import RunInputArtifacts
+from .run_output_artifacts import RunOutputArtifacts
+from .type_info import TypeInfo
+from .unlink_artifact import UnlinkArtifact
+from .update_artifact import UpdateArtifact
+from .update_artifact_portfolio import UpdateArtifactPortfolio
+from .update_artifact_sequence import UpdateArtifactSequence
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/add_aliases.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/add_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..14b288fdde8f9057dd43263a952d777568da7aa4
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/add_aliases.py
@@ -0,0 +1,21 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+
+class AddAliases(GQLBase):
+ add_aliases: Optional[AddAliasesAddAliases] = Field(alias="addAliases")
+
+
+class AddAliasesAddAliases(GQLBase):
+ success: bool
+
+
+AddAliases.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_by_id.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_by_id.py
new file mode 100644
index 0000000000000000000000000000000000000000..03733c876a68960cd87d18754e0a65ca50706760
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_by_id.py
@@ -0,0 +1,17 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from wandb._pydantic import GQLBase
+
+from .fragments import ArtifactFragment
+
+
+class ArtifactByID(GQLBase):
+ artifact: Optional[ArtifactFragment]
+
+
+ArtifactByID.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_by_name.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_by_name.py
new file mode 100644
index 0000000000000000000000000000000000000000..af0e1c2a577e884e322e1aca731b7e6a63a3418b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_by_name.py
@@ -0,0 +1,22 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from wandb._pydantic import GQLBase
+
+from .fragments import ArtifactFragment
+
+
+class ArtifactByName(GQLBase):
+ project: Optional[ArtifactByNameProject]
+
+
+class ArtifactByNameProject(GQLBase):
+ artifact: Optional[ArtifactFragment]
+
+
+ArtifactByName.model_rebuild()
+ArtifactByNameProject.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_collection_membership_file_urls.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_collection_membership_file_urls.py
new file mode 100644
index 0000000000000000000000000000000000000000..75976dfd6154901ceb4d2c807c9e592904865876
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_collection_membership_file_urls.py
@@ -0,0 +1,43 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Literal, Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase, Typename
+
+from .fragments import FileUrlsFragment
+
+
+class ArtifactCollectionMembershipFileUrls(GQLBase):
+ project: Optional[ArtifactCollectionMembershipFileUrlsProject]
+
+
+class ArtifactCollectionMembershipFileUrlsProject(GQLBase):
+ artifact_collection: Optional[
+ ArtifactCollectionMembershipFileUrlsProjectArtifactCollection
+ ] = Field(alias="artifactCollection")
+
+
+class ArtifactCollectionMembershipFileUrlsProjectArtifactCollection(GQLBase):
+ typename__: Typename[
+ Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"]
+ ]
+ artifact_membership: Optional[
+ ArtifactCollectionMembershipFileUrlsProjectArtifactCollectionArtifactMembership
+ ] = Field(alias="artifactMembership")
+
+
+class ArtifactCollectionMembershipFileUrlsProjectArtifactCollectionArtifactMembership(
+ GQLBase
+):
+ files: Optional[FileUrlsFragment]
+
+
+ArtifactCollectionMembershipFileUrls.model_rebuild()
+ArtifactCollectionMembershipFileUrlsProject.model_rebuild()
+ArtifactCollectionMembershipFileUrlsProjectArtifactCollection.model_rebuild()
+ArtifactCollectionMembershipFileUrlsProjectArtifactCollectionArtifactMembership.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_collection_membership_files.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_collection_membership_files.py
new file mode 100644
index 0000000000000000000000000000000000000000..87dc90d69600c9d4e06c3254412ae72aaaca3d8f
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_collection_membership_files.py
@@ -0,0 +1,43 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Literal, Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase, Typename
+
+from .fragments import FilesFragment
+
+
+class ArtifactCollectionMembershipFiles(GQLBase):
+ project: Optional[ArtifactCollectionMembershipFilesProject]
+
+
+class ArtifactCollectionMembershipFilesProject(GQLBase):
+ artifact_collection: Optional[
+ ArtifactCollectionMembershipFilesProjectArtifactCollection
+ ] = Field(alias="artifactCollection")
+
+
+class ArtifactCollectionMembershipFilesProjectArtifactCollection(GQLBase):
+ typename__: Typename[
+ Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"]
+ ]
+ artifact_membership: Optional[
+ ArtifactCollectionMembershipFilesProjectArtifactCollectionArtifactMembership
+ ] = Field(alias="artifactMembership")
+
+
+class ArtifactCollectionMembershipFilesProjectArtifactCollectionArtifactMembership(
+ GQLBase
+):
+ files: Optional[FilesFragment]
+
+
+ArtifactCollectionMembershipFiles.model_rebuild()
+ArtifactCollectionMembershipFilesProject.model_rebuild()
+ArtifactCollectionMembershipFilesProjectArtifactCollection.model_rebuild()
+ArtifactCollectionMembershipFilesProjectArtifactCollectionArtifactMembership.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_created_by.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_created_by.py
new file mode 100644
index 0000000000000000000000000000000000000000..dac6bb502242b464fff0ce131eac6befdac6e74d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_created_by.py
@@ -0,0 +1,47 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Literal, Optional, Union
+
+from pydantic import Field
+from typing_extensions import Annotated
+
+from wandb._pydantic import GQLBase, Typename
+
+
+class ArtifactCreatedBy(GQLBase):
+ artifact: Optional[ArtifactCreatedByArtifact]
+
+
+class ArtifactCreatedByArtifact(GQLBase):
+ created_by: Optional[
+ Annotated[
+ Union[
+ ArtifactCreatedByArtifactCreatedByRun,
+ ArtifactCreatedByArtifactCreatedByUser,
+ ],
+ Field(discriminator="typename__"),
+ ]
+ ] = Field(alias="createdBy")
+
+
+class ArtifactCreatedByArtifactCreatedByRun(GQLBase):
+ typename__: Typename[Literal["Run"]]
+ name: str
+ project: Optional[ArtifactCreatedByArtifactCreatedByRunProject]
+
+
+class ArtifactCreatedByArtifactCreatedByRunProject(GQLBase):
+ name: str
+ entity_name: str = Field(alias="entityName")
+
+
+class ArtifactCreatedByArtifactCreatedByUser(GQLBase):
+ typename__: Typename[Literal["User"]]
+
+
+ArtifactCreatedBy.model_rebuild()
+ArtifactCreatedByArtifact.model_rebuild()
+ArtifactCreatedByArtifactCreatedByRun.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_file_urls.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_file_urls.py
new file mode 100644
index 0000000000000000000000000000000000000000..5cbeae303340e06d3b5d2340f2b37ff410bbe2ae
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_file_urls.py
@@ -0,0 +1,22 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from wandb._pydantic import GQLBase
+
+from .fragments import FileUrlsFragment
+
+
+class ArtifactFileUrls(GQLBase):
+ artifact: Optional[ArtifactFileUrlsArtifact]
+
+
+class ArtifactFileUrlsArtifact(GQLBase):
+ files: Optional[FileUrlsFragment]
+
+
+ArtifactFileUrls.model_rebuild()
+ArtifactFileUrlsArtifact.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_type.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_type.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b73d5a9360fbdb209b4c235b26f9c8841e60666
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_type.py
@@ -0,0 +1,31 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+
+class ArtifactType(GQLBase):
+ project: Optional[ArtifactTypeProject]
+
+
+class ArtifactTypeProject(GQLBase):
+ artifact: Optional[ArtifactTypeProjectArtifact]
+
+
+class ArtifactTypeProjectArtifact(GQLBase):
+ artifact_type: ArtifactTypeProjectArtifactArtifactType = Field(alias="artifactType")
+
+
+class ArtifactTypeProjectArtifactArtifactType(GQLBase):
+ name: str
+
+
+ArtifactType.model_rebuild()
+ArtifactTypeProject.model_rebuild()
+ArtifactTypeProjectArtifact.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_used_by.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_used_by.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf1aaa5216d75de2c0c5df8d75eb01a861a32cbb
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_used_by.py
@@ -0,0 +1,43 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import List, Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+
+class ArtifactUsedBy(GQLBase):
+ artifact: Optional[ArtifactUsedByArtifact]
+
+
+class ArtifactUsedByArtifact(GQLBase):
+ used_by: ArtifactUsedByArtifactUsedBy = Field(alias="usedBy")
+
+
+class ArtifactUsedByArtifactUsedBy(GQLBase):
+ edges: List[ArtifactUsedByArtifactUsedByEdges]
+
+
+class ArtifactUsedByArtifactUsedByEdges(GQLBase):
+ node: ArtifactUsedByArtifactUsedByEdgesNode
+
+
+class ArtifactUsedByArtifactUsedByEdgesNode(GQLBase):
+ name: str
+ project: Optional[ArtifactUsedByArtifactUsedByEdgesNodeProject]
+
+
+class ArtifactUsedByArtifactUsedByEdgesNodeProject(GQLBase):
+ name: str
+ entity_name: str = Field(alias="entityName")
+
+
+ArtifactUsedBy.model_rebuild()
+ArtifactUsedByArtifact.model_rebuild()
+ArtifactUsedByArtifactUsedBy.model_rebuild()
+ArtifactUsedByArtifactUsedByEdges.model_rebuild()
+ArtifactUsedByArtifactUsedByEdgesNode.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_version_files.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_version_files.py
new file mode 100644
index 0000000000000000000000000000000000000000..c35018dccf3ae1ab003644345ffcebfc8530526d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_version_files.py
@@ -0,0 +1,36 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+from .fragments import FilesFragment
+
+
+class ArtifactVersionFiles(GQLBase):
+ project: Optional[ArtifactVersionFilesProject]
+
+
+class ArtifactVersionFilesProject(GQLBase):
+ artifact_type: Optional[ArtifactVersionFilesProjectArtifactType] = Field(
+ alias="artifactType"
+ )
+
+
+class ArtifactVersionFilesProjectArtifactType(GQLBase):
+ artifact: Optional[ArtifactVersionFilesProjectArtifactTypeArtifact]
+
+
+class ArtifactVersionFilesProjectArtifactTypeArtifact(GQLBase):
+ files: Optional[FilesFragment]
+
+
+ArtifactVersionFiles.model_rebuild()
+ArtifactVersionFilesProject.model_rebuild()
+ArtifactVersionFilesProjectArtifactType.model_rebuild()
+ArtifactVersionFilesProjectArtifactTypeArtifact.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_via_membership_by_name.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_via_membership_by_name.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e9f6c3f626f96c182c6eb378caa336c826cc16a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_via_membership_by_name.py
@@ -0,0 +1,26 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+from .fragments import MembershipWithArtifact
+
+
+class ArtifactViaMembershipByName(GQLBase):
+ project: Optional[ArtifactViaMembershipByNameProject]
+
+
+class ArtifactViaMembershipByNameProject(GQLBase):
+ artifact_collection_membership: Optional[MembershipWithArtifact] = Field(
+ alias="artifactCollectionMembership"
+ )
+
+
+ArtifactViaMembershipByName.model_rebuild()
+ArtifactViaMembershipByNameProject.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/create_artifact_collection_tag_assignments.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/create_artifact_collection_tag_assignments.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c625cc843e0c16934d8b59f95c646e79ea09756
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/create_artifact_collection_tag_assignments.py
@@ -0,0 +1,36 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import List, Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase, GQLId
+
+
+class CreateArtifactCollectionTagAssignments(GQLBase):
+ create_artifact_collection_tag_assignments: Optional[
+ CreateArtifactCollectionTagAssignmentsCreateArtifactCollectionTagAssignments
+ ] = Field(alias="createArtifactCollectionTagAssignments")
+
+
+class CreateArtifactCollectionTagAssignmentsCreateArtifactCollectionTagAssignments(
+ GQLBase
+):
+ tags: List[
+ CreateArtifactCollectionTagAssignmentsCreateArtifactCollectionTagAssignmentsTags
+ ]
+
+
+class CreateArtifactCollectionTagAssignmentsCreateArtifactCollectionTagAssignmentsTags(
+ GQLBase
+):
+ id: GQLId
+ name: str
+ tag_category_name: str = Field(alias="tagCategoryName")
+
+
+CreateArtifactCollectionTagAssignments.model_rebuild()
+CreateArtifactCollectionTagAssignmentsCreateArtifactCollectionTagAssignments.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_aliases.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1aa3e1973e943f254b02907a34da58f951eadb4
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_aliases.py
@@ -0,0 +1,21 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+
+class DeleteAliases(GQLBase):
+ delete_aliases: Optional[DeleteAliasesDeleteAliases] = Field(alias="deleteAliases")
+
+
+class DeleteAliasesDeleteAliases(GQLBase):
+ success: bool
+
+
+DeleteAliases.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d0d55b27f3487d9aea8ef6d84b700a123de842a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact.py
@@ -0,0 +1,28 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase, GQLId
+
+
+class DeleteArtifact(GQLBase):
+ delete_artifact: Optional[DeleteArtifactDeleteArtifact] = Field(
+ alias="deleteArtifact"
+ )
+
+
+class DeleteArtifactDeleteArtifact(GQLBase):
+ artifact: DeleteArtifactDeleteArtifactArtifact
+
+
+class DeleteArtifactDeleteArtifactArtifact(GQLBase):
+ id: GQLId
+
+
+DeleteArtifact.model_rebuild()
+DeleteArtifactDeleteArtifact.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact_collection_tag_assignments.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact_collection_tag_assignments.py
new file mode 100644
index 0000000000000000000000000000000000000000..d89d18340cd4a4cb17d09af8edef4e72c278151c
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact_collection_tag_assignments.py
@@ -0,0 +1,25 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+
+class DeleteArtifactCollectionTagAssignments(GQLBase):
+ delete_artifact_collection_tag_assignments: Optional[
+ DeleteArtifactCollectionTagAssignmentsDeleteArtifactCollectionTagAssignments
+ ] = Field(alias="deleteArtifactCollectionTagAssignments")
+
+
+class DeleteArtifactCollectionTagAssignmentsDeleteArtifactCollectionTagAssignments(
+ GQLBase
+):
+ success: bool
+
+
+DeleteArtifactCollectionTagAssignments.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact_portfolio.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact_portfolio.py
new file mode 100644
index 0000000000000000000000000000000000000000..91b88aed6108959893e101955baf75840f9eaba0
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact_portfolio.py
@@ -0,0 +1,35 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Literal, Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase, Typename
+
+from .enums import ArtifactCollectionState
+
+
+class DeleteArtifactPortfolio(GQLBase):
+ delete_artifact_portfolio: Optional[
+ DeleteArtifactPortfolioDeleteArtifactPortfolio
+ ] = Field(alias="deleteArtifactPortfolio")
+
+
+class DeleteArtifactPortfolioDeleteArtifactPortfolio(GQLBase):
+ artifact_collection: DeleteArtifactPortfolioDeleteArtifactPortfolioArtifactCollection = Field(
+ alias="artifactCollection"
+ )
+
+
+class DeleteArtifactPortfolioDeleteArtifactPortfolioArtifactCollection(GQLBase):
+ typename__: Typename[
+ Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"]
+ ]
+ state: ArtifactCollectionState
+
+
+DeleteArtifactPortfolio.model_rebuild()
+DeleteArtifactPortfolioDeleteArtifactPortfolio.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact_sequence.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact_sequence.py
new file mode 100644
index 0000000000000000000000000000000000000000..85eeca9bfb32f452b6281733fbfcf5ef5b4f0700
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact_sequence.py
@@ -0,0 +1,35 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Literal, Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase, Typename
+
+from .enums import ArtifactCollectionState
+
+
+class DeleteArtifactSequence(GQLBase):
+ delete_artifact_sequence: Optional[DeleteArtifactSequenceDeleteArtifactSequence] = (
+ Field(alias="deleteArtifactSequence")
+ )
+
+
+class DeleteArtifactSequenceDeleteArtifactSequence(GQLBase):
+ artifact_collection: DeleteArtifactSequenceDeleteArtifactSequenceArtifactCollection = Field(
+ alias="artifactCollection"
+ )
+
+
+class DeleteArtifactSequenceDeleteArtifactSequenceArtifactCollection(GQLBase):
+ typename__: Typename[
+ Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"]
+ ]
+ state: ArtifactCollectionState
+
+
+DeleteArtifactSequence.model_rebuild()
+DeleteArtifactSequenceDeleteArtifactSequence.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/enums.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/enums.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4131d8362f5b1e0d8a2d0fba641ce1affe713d8
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/enums.py
@@ -0,0 +1,22 @@
+# Generated by ariadne-codegen
+# Source: core/api/graphql/schemas/schema-latest.graphql
+
+from __future__ import annotations
+
+from enum import Enum
+
+
+class ArtifactCollectionType(str, Enum):
+ SEQUENCE = "SEQUENCE"
+ PORTFOLIO = "PORTFOLIO"
+
+
+class ArtifactState(str, Enum):
+ PENDING = "PENDING"
+ COMMITTED = "COMMITTED"
+ DELETED = "DELETED"
+
+
+class ArtifactCollectionState(str, Enum):
+ READY = "READY"
+ DELETED = "DELETED"
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_artifact_manifest.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_artifact_manifest.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4536f88f7f586deb4d705afd240a74531faa78b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_artifact_manifest.py
@@ -0,0 +1,38 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+
+class FetchArtifactManifest(GQLBase):
+ project: Optional[FetchArtifactManifestProject]
+
+
+class FetchArtifactManifestProject(GQLBase):
+ artifact: Optional[FetchArtifactManifestProjectArtifact]
+
+
+class FetchArtifactManifestProjectArtifact(GQLBase):
+ current_manifest: Optional[FetchArtifactManifestProjectArtifactCurrentManifest] = (
+ Field(alias="currentManifest")
+ )
+
+
+class FetchArtifactManifestProjectArtifactCurrentManifest(GQLBase):
+ file: FetchArtifactManifestProjectArtifactCurrentManifestFile
+
+
+class FetchArtifactManifestProjectArtifactCurrentManifestFile(GQLBase):
+ direct_url: str = Field(alias="directUrl")
+
+
+FetchArtifactManifest.model_rebuild()
+FetchArtifactManifestProject.model_rebuild()
+FetchArtifactManifestProjectArtifact.model_rebuild()
+FetchArtifactManifestProjectArtifactCurrentManifest.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_linked_artifacts.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_linked_artifacts.py
new file mode 100644
index 0000000000000000000000000000000000000000..2617735522a65f6b37c76d80952fe3d3b1065495
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_linked_artifacts.py
@@ -0,0 +1,67 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import List, Literal, Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase, Typename
+
+
+class FetchLinkedArtifacts(GQLBase):
+ artifact: Optional[FetchLinkedArtifactsArtifact]
+
+
+class FetchLinkedArtifactsArtifact(GQLBase):
+ artifact_memberships: FetchLinkedArtifactsArtifactArtifactMemberships = Field(
+ alias="artifactMemberships"
+ )
+
+
+class FetchLinkedArtifactsArtifactArtifactMemberships(GQLBase):
+ edges: List[FetchLinkedArtifactsArtifactArtifactMembershipsEdges]
+
+
+class FetchLinkedArtifactsArtifactArtifactMembershipsEdges(GQLBase):
+ node: Optional[FetchLinkedArtifactsArtifactArtifactMembershipsEdgesNode]
+
+
+class FetchLinkedArtifactsArtifactArtifactMembershipsEdgesNode(GQLBase):
+ aliases: List[FetchLinkedArtifactsArtifactArtifactMembershipsEdgesNodeAliases]
+ version_index: Optional[int] = Field(alias="versionIndex")
+ artifact_collection: Optional[
+ FetchLinkedArtifactsArtifactArtifactMembershipsEdgesNodeArtifactCollection
+ ] = Field(alias="artifactCollection")
+
+
+class FetchLinkedArtifactsArtifactArtifactMembershipsEdgesNodeAliases(GQLBase):
+ alias: str
+
+
+class FetchLinkedArtifactsArtifactArtifactMembershipsEdgesNodeArtifactCollection(
+ GQLBase
+):
+ project: Optional[
+ FetchLinkedArtifactsArtifactArtifactMembershipsEdgesNodeArtifactCollectionProject
+ ]
+ name: str
+ typename__: Typename[
+ Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"]
+ ]
+
+
+class FetchLinkedArtifactsArtifactArtifactMembershipsEdgesNodeArtifactCollectionProject(
+ GQLBase
+):
+ entity_name: str = Field(alias="entityName")
+ name: str
+
+
+FetchLinkedArtifacts.model_rebuild()
+FetchLinkedArtifactsArtifact.model_rebuild()
+FetchLinkedArtifactsArtifactArtifactMemberships.model_rebuild()
+FetchLinkedArtifactsArtifactArtifactMembershipsEdges.model_rebuild()
+FetchLinkedArtifactsArtifactArtifactMembershipsEdgesNode.model_rebuild()
+FetchLinkedArtifactsArtifactArtifactMembershipsEdgesNodeArtifactCollection.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_registries.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_registries.py
new file mode 100644
index 0000000000000000000000000000000000000000..5fd77f4ce2012f0c43328714d9dbd68ad3b17d9a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_registries.py
@@ -0,0 +1,32 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+from .fragments import RegistriesPage
+
+
+class FetchRegistries(GQLBase):
+ organization: Optional[FetchRegistriesOrganization]
+
+
+class FetchRegistriesOrganization(GQLBase):
+ org_entity: Optional[FetchRegistriesOrganizationOrgEntity] = Field(
+ alias="orgEntity"
+ )
+
+
+class FetchRegistriesOrganizationOrgEntity(GQLBase):
+ name: str
+ projects: Optional[RegistriesPage]
+
+
+FetchRegistries.model_rebuild()
+FetchRegistriesOrganization.model_rebuild()
+FetchRegistriesOrganizationOrgEntity.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/fragments.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/fragments.py
new file mode 100644
index 0000000000000000000000000000000000000000..d88cba67c6f7f052c8c95e4273b1e0cb1ba83c68
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/fragments.py
@@ -0,0 +1,524 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Any, List, Literal, Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase, GQLId, Typename
+
+from .enums import ArtifactState
+
+
+class ArtifactCollectionsFragment(GQLBase):
+ page_info: ArtifactCollectionsFragmentPageInfo = Field(alias="pageInfo")
+ total_count: int = Field(alias="totalCount")
+ edges: List[ArtifactCollectionsFragmentEdges]
+
+
+class ArtifactCollectionsFragmentEdges(GQLBase):
+ node: Optional[ArtifactCollectionsFragmentEdgesNode]
+ cursor: str
+
+
+class ArtifactCollectionsFragmentEdgesNode(GQLBase):
+ typename__: Typename[
+ Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"]
+ ]
+ id: GQLId
+ name: str
+ description: Optional[str]
+ created_at: str = Field(alias="createdAt")
+
+
+class ArtifactCollectionsFragmentPageInfo(GQLBase):
+ end_cursor: Optional[str] = Field(alias="endCursor")
+ has_next_page: bool = Field(alias="hasNextPage")
+
+
+class ArtifactFragmentAliases(GQLBase):
+ artifact_collection: Optional[ArtifactFragmentAliasesArtifactCollection] = Field(
+ alias="artifactCollection"
+ )
+ alias: str
+
+
+class ArtifactFragmentAliasesArtifactCollection(GQLBase):
+ typename__: Typename[
+ Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"]
+ ]
+ project: Optional[ArtifactFragmentAliasesArtifactCollectionProject]
+ name: str
+
+
+class ArtifactFragmentAliasesArtifactCollectionProject(GQLBase):
+ entity_name: str = Field(alias="entityName")
+ name: str
+
+
+class ArtifactFragmentWithoutAliases(GQLBase):
+ id: GQLId
+ artifact_sequence: ArtifactFragmentWithoutAliasesArtifactSequence = Field(
+ alias="artifactSequence"
+ )
+ version_index: Optional[int] = Field(alias="versionIndex")
+ artifact_type: ArtifactFragmentWithoutAliasesArtifactType = Field(
+ alias="artifactType"
+ )
+ description: Optional[str]
+ metadata: Optional[Any]
+ ttl_duration_seconds: Optional[Any] = Field(
+ alias="ttlDurationSeconds", default=None
+ )
+ ttl_is_inherited: Optional[bool] = Field(alias="ttlIsInherited", default=None)
+ tags: Optional[List[ArtifactFragmentWithoutAliasesTags]] = None
+ history_step: Optional[Any] = Field(alias="historyStep", default=None)
+ state: ArtifactState
+ current_manifest: Optional[ArtifactFragmentWithoutAliasesCurrentManifest] = Field(
+ alias="currentManifest"
+ )
+ commit_hash: Optional[str] = Field(alias="commitHash")
+ file_count: Any = Field(alias="fileCount")
+ created_at: str = Field(alias="createdAt")
+ updated_at: Optional[str] = Field(alias="updatedAt")
+
+
+class ArtifactFragmentWithoutAliasesArtifactSequence(GQLBase):
+ project: Optional[ArtifactFragmentWithoutAliasesArtifactSequenceProject]
+ name: str
+
+
+class ArtifactFragmentWithoutAliasesArtifactSequenceProject(GQLBase):
+ entity_name: str = Field(alias="entityName")
+ name: str
+
+
+class ArtifactFragmentWithoutAliasesArtifactType(GQLBase):
+ name: str
+
+
+class ArtifactFragmentWithoutAliasesCurrentManifest(GQLBase):
+ file: ArtifactFragmentWithoutAliasesCurrentManifestFile
+
+
+class ArtifactFragmentWithoutAliasesCurrentManifestFile(GQLBase):
+ direct_url: str = Field(alias="directUrl")
+
+
+class ArtifactFragmentWithoutAliasesTags(GQLBase):
+ name: str
+
+
+class ArtifactPortfolioTypeFields(GQLBase):
+ typename__: Typename[Literal["ArtifactPortfolio"]] = "ArtifactPortfolio"
+ id: GQLId
+ name: str
+
+
+class ArtifactSequenceTypeFields(GQLBase):
+ typename__: Typename[Literal["ArtifactSequence"]] = "ArtifactSequence"
+ id: GQLId
+ name: str
+
+
+class ArtifactTypeFragment(GQLBase):
+ typename__: Typename[Literal["ArtifactType"]] = "ArtifactType"
+ id: GQLId
+ name: str
+ description: Optional[str]
+ created_at: str = Field(alias="createdAt")
+
+
+class ArtifactTypesFragment(GQLBase):
+ edges: List[ArtifactTypesFragmentEdges]
+ page_info: ArtifactTypesFragmentPageInfo = Field(alias="pageInfo")
+
+
+class ArtifactTypesFragmentEdges(GQLBase):
+ node: Optional[ArtifactTypeFragment]
+ cursor: str
+
+
+class ArtifactTypesFragmentPageInfo(GQLBase):
+ end_cursor: Optional[str] = Field(alias="endCursor")
+ has_next_page: bool = Field(alias="hasNextPage")
+
+
+class ArtifactsFragment(GQLBase):
+ total_count: int = Field(alias="totalCount")
+ edges: List[ArtifactsFragmentEdges]
+ page_info: ArtifactsFragmentPageInfo = Field(alias="pageInfo")
+
+
+class ArtifactsFragmentEdges(GQLBase):
+ node: ArtifactFragment
+ version: str
+ cursor: str
+
+
+class ArtifactsFragmentPageInfo(GQLBase):
+ end_cursor: Optional[str] = Field(alias="endCursor")
+ has_next_page: bool = Field(alias="hasNextPage")
+
+
+class FileUrlsFragment(GQLBase):
+ page_info: FileUrlsFragmentPageInfo = Field(alias="pageInfo")
+ edges: List[FileUrlsFragmentEdges]
+
+
+class FileUrlsFragmentEdges(GQLBase):
+ node: Optional[FileUrlsFragmentEdgesNode]
+
+
+class FileUrlsFragmentEdgesNode(GQLBase):
+ name: str
+ direct_url: str = Field(alias="directUrl")
+
+
+class FileUrlsFragmentPageInfo(GQLBase):
+ has_next_page: bool = Field(alias="hasNextPage")
+ end_cursor: Optional[str] = Field(alias="endCursor")
+
+
+class FilesFragment(GQLBase):
+ edges: List[FilesFragmentEdges]
+ page_info: FilesFragmentPageInfo = Field(alias="pageInfo")
+
+
+class FilesFragmentEdges(GQLBase):
+ node: Optional[FilesFragmentEdgesNode]
+ cursor: str
+
+
+class FilesFragmentEdgesNode(GQLBase):
+ id: GQLId
+ name: str
+ url: Optional[str]
+ size_bytes: Any = Field(alias="sizeBytes")
+ storage_path: Optional[str] = Field(alias="storagePath", default=None)
+ mimetype: Optional[str]
+ updated_at: Optional[str] = Field(alias="updatedAt")
+ digest: Optional[str]
+ md_5: Optional[str] = Field(alias="md5")
+ direct_url: str = Field(alias="directUrl")
+
+
+class FilesFragmentPageInfo(GQLBase):
+ end_cursor: Optional[str] = Field(alias="endCursor")
+ has_next_page: bool = Field(alias="hasNextPage")
+
+
+class MembershipWithArtifact(GQLBase):
+ id: GQLId
+ artifact_collection: Optional[MembershipWithArtifactArtifactCollection] = Field(
+ alias="artifactCollection"
+ )
+ artifact: Optional[ArtifactFragment]
+
+
+class MembershipWithArtifactArtifactCollection(GQLBase):
+ typename__: Typename[
+ Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"]
+ ]
+ id: GQLId
+ name: str
+ project: Optional[MembershipWithArtifactArtifactCollectionProject]
+
+
+class MembershipWithArtifactArtifactCollectionProject(GQLBase):
+ id: GQLId
+ entity_name: str = Field(alias="entityName")
+ name: str
+
+
+class RegistriesPage(GQLBase):
+ page_info: RegistriesPagePageInfo = Field(alias="pageInfo")
+ edges: List[RegistriesPageEdges]
+
+
+class RegistriesPageEdges(GQLBase):
+ node: Optional[RegistryFragment]
+
+
+class RegistriesPagePageInfo(GQLBase):
+ end_cursor: Optional[str] = Field(alias="endCursor")
+ has_next_page: bool = Field(alias="hasNextPage")
+
+
+class RegistryCollectionsPage(GQLBase):
+ total_count: int = Field(alias="totalCount")
+ page_info: RegistryCollectionsPagePageInfo = Field(alias="pageInfo")
+ edges: List[RegistryCollectionsPageEdges]
+
+
+class RegistryCollectionsPageEdges(GQLBase):
+ cursor: str
+ node: Optional[RegistryCollectionsPageEdgesNode]
+
+
+class RegistryCollectionsPageEdgesNode(GQLBase):
+ typename__: Typename[
+ Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"]
+ ]
+ id: GQLId
+ name: str
+ description: Optional[str]
+ created_at: str = Field(alias="createdAt")
+ tags: RegistryCollectionsPageEdgesNodeTags
+ project: Optional[RegistryCollectionsPageEdgesNodeProject]
+ default_artifact_type: RegistryCollectionsPageEdgesNodeDefaultArtifactType = Field(
+ alias="defaultArtifactType"
+ )
+ aliases: RegistryCollectionsPageEdgesNodeAliases
+
+
+class RegistryCollectionsPageEdgesNodeAliases(GQLBase):
+ edges: List[RegistryCollectionsPageEdgesNodeAliasesEdges]
+
+
+class RegistryCollectionsPageEdgesNodeAliasesEdges(GQLBase):
+ node: Optional[RegistryCollectionsPageEdgesNodeAliasesEdgesNode]
+
+
+class RegistryCollectionsPageEdgesNodeAliasesEdgesNode(GQLBase):
+ alias: str
+
+
+class RegistryCollectionsPageEdgesNodeDefaultArtifactType(GQLBase):
+ name: str
+
+
+class RegistryCollectionsPageEdgesNodeProject(GQLBase):
+ name: str
+ entity: RegistryCollectionsPageEdgesNodeProjectEntity
+
+
+class RegistryCollectionsPageEdgesNodeProjectEntity(GQLBase):
+ name: str
+
+
+class RegistryCollectionsPageEdgesNodeTags(GQLBase):
+ edges: List[RegistryCollectionsPageEdgesNodeTagsEdges]
+
+
+class RegistryCollectionsPageEdgesNodeTagsEdges(GQLBase):
+ node: RegistryCollectionsPageEdgesNodeTagsEdgesNode
+
+
+class RegistryCollectionsPageEdgesNodeTagsEdgesNode(GQLBase):
+ name: str
+
+
+class RegistryCollectionsPagePageInfo(GQLBase):
+ end_cursor: Optional[str] = Field(alias="endCursor")
+ has_next_page: bool = Field(alias="hasNextPage")
+
+
+class RegistryFragment(GQLBase):
+ id: GQLId
+ allow_all_artifact_types_in_registry: bool = Field(
+ alias="allowAllArtifactTypesInRegistry"
+ )
+ artifact_types: RegistryFragmentArtifactTypes = Field(alias="artifactTypes")
+ name: str
+ description: Optional[str]
+ created_at: str = Field(alias="createdAt")
+ updated_at: Optional[str] = Field(alias="updatedAt")
+ access: Optional[str]
+
+
+class RegistryFragmentArtifactTypes(GQLBase):
+ edges: List[RegistryFragmentArtifactTypesEdges]
+
+
+class RegistryFragmentArtifactTypesEdges(GQLBase):
+ node: Optional[RegistryFragmentArtifactTypesEdgesNode]
+
+
+class RegistryFragmentArtifactTypesEdgesNode(GQLBase):
+ name: str
+
+
+class RegistryVersionsPage(GQLBase):
+ page_info: RegistryVersionsPagePageInfo = Field(alias="pageInfo")
+ edges: List[RegistryVersionsPageEdges]
+
+
+class RegistryVersionsPageEdges(GQLBase):
+ node: Optional[RegistryVersionsPageEdgesNode]
+
+
+class RegistryVersionsPageEdgesNode(GQLBase):
+ artifact_collection: Optional[RegistryVersionsPageEdgesNodeArtifactCollection] = (
+ Field(alias="artifactCollection")
+ )
+ version_index: Optional[int] = Field(alias="versionIndex")
+ artifact: Optional[ArtifactFragmentWithoutAliases]
+ aliases: List[RegistryVersionsPageEdgesNodeAliases]
+
+
+class RegistryVersionsPageEdgesNodeAliases(GQLBase):
+ alias: str
+
+
+class RegistryVersionsPageEdgesNodeArtifactCollection(GQLBase):
+ typename__: Typename[
+ Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"]
+ ]
+ project: Optional[RegistryVersionsPageEdgesNodeArtifactCollectionProject]
+ name: str
+
+
+class RegistryVersionsPageEdgesNodeArtifactCollectionProject(GQLBase):
+ name: str
+ entity: RegistryVersionsPageEdgesNodeArtifactCollectionProjectEntity
+
+
+class RegistryVersionsPageEdgesNodeArtifactCollectionProjectEntity(GQLBase):
+ name: str
+
+
+class RegistryVersionsPagePageInfo(GQLBase):
+ end_cursor: Optional[str] = Field(alias="endCursor")
+ has_next_page: bool = Field(alias="hasNextPage")
+
+
+class RunInputArtifactConnectionFragment(GQLBase):
+ total_count: int = Field(alias="totalCount")
+ edges: List[RunInputArtifactConnectionFragmentEdges]
+ page_info: RunInputArtifactConnectionFragmentPageInfo = Field(alias="pageInfo")
+
+
+class RunInputArtifactConnectionFragmentEdges(GQLBase):
+ node: Optional[ArtifactFragment]
+ cursor: str
+
+
+class RunInputArtifactConnectionFragmentPageInfo(GQLBase):
+ end_cursor: Optional[str] = Field(alias="endCursor")
+ has_next_page: bool = Field(alias="hasNextPage")
+
+
+class RunOutputArtifactConnectionFragment(GQLBase):
+ total_count: int = Field(alias="totalCount")
+ edges: List[RunOutputArtifactConnectionFragmentEdges]
+ page_info: RunOutputArtifactConnectionFragmentPageInfo = Field(alias="pageInfo")
+
+
+class RunOutputArtifactConnectionFragmentEdges(GQLBase):
+ node: Optional[ArtifactFragment]
+ cursor: str
+
+
+class RunOutputArtifactConnectionFragmentPageInfo(GQLBase):
+ end_cursor: Optional[str] = Field(alias="endCursor")
+ has_next_page: bool = Field(alias="hasNextPage")
+
+
+class TypeInfoFragment(GQLBase):
+ name: Optional[str]
+ fields: Optional[List[TypeInfoFragmentFields]]
+ input_fields: Optional[List[TypeInfoFragmentInputFields]] = Field(
+ alias="inputFields"
+ )
+
+
+class TypeInfoFragmentFields(GQLBase):
+ name: str
+ args: List[TypeInfoFragmentFieldsArgs]
+
+
+class TypeInfoFragmentFieldsArgs(GQLBase):
+ name: str
+
+
+class TypeInfoFragmentInputFields(GQLBase):
+ name: str
+
+
+class ArtifactFragment(ArtifactFragmentWithoutAliases):
+ aliases: Optional[List[ArtifactFragmentAliases]] = None
+
+
+ArtifactCollectionsFragment.model_rebuild()
+ArtifactCollectionsFragmentEdges.model_rebuild()
+ArtifactCollectionsFragmentEdgesNode.model_rebuild()
+ArtifactCollectionsFragmentPageInfo.model_rebuild()
+ArtifactFragmentAliases.model_rebuild()
+ArtifactFragmentAliasesArtifactCollection.model_rebuild()
+ArtifactFragmentAliasesArtifactCollectionProject.model_rebuild()
+ArtifactFragmentWithoutAliases.model_rebuild()
+ArtifactFragmentWithoutAliasesArtifactSequence.model_rebuild()
+ArtifactFragmentWithoutAliasesArtifactSequenceProject.model_rebuild()
+ArtifactFragmentWithoutAliasesArtifactType.model_rebuild()
+ArtifactFragmentWithoutAliasesCurrentManifest.model_rebuild()
+ArtifactFragmentWithoutAliasesCurrentManifestFile.model_rebuild()
+ArtifactFragmentWithoutAliasesTags.model_rebuild()
+ArtifactPortfolioTypeFields.model_rebuild()
+ArtifactSequenceTypeFields.model_rebuild()
+ArtifactTypeFragment.model_rebuild()
+ArtifactTypesFragment.model_rebuild()
+ArtifactTypesFragmentEdges.model_rebuild()
+ArtifactTypesFragmentPageInfo.model_rebuild()
+ArtifactsFragment.model_rebuild()
+ArtifactsFragmentEdges.model_rebuild()
+ArtifactsFragmentPageInfo.model_rebuild()
+FileUrlsFragment.model_rebuild()
+FileUrlsFragmentEdges.model_rebuild()
+FileUrlsFragmentEdgesNode.model_rebuild()
+FileUrlsFragmentPageInfo.model_rebuild()
+FilesFragment.model_rebuild()
+FilesFragmentEdges.model_rebuild()
+FilesFragmentEdgesNode.model_rebuild()
+FilesFragmentPageInfo.model_rebuild()
+MembershipWithArtifact.model_rebuild()
+MembershipWithArtifactArtifactCollection.model_rebuild()
+MembershipWithArtifactArtifactCollectionProject.model_rebuild()
+RegistriesPage.model_rebuild()
+RegistriesPageEdges.model_rebuild()
+RegistriesPagePageInfo.model_rebuild()
+RegistryCollectionsPage.model_rebuild()
+RegistryCollectionsPageEdges.model_rebuild()
+RegistryCollectionsPageEdgesNode.model_rebuild()
+RegistryCollectionsPageEdgesNodeAliases.model_rebuild()
+RegistryCollectionsPageEdgesNodeAliasesEdges.model_rebuild()
+RegistryCollectionsPageEdgesNodeAliasesEdgesNode.model_rebuild()
+RegistryCollectionsPageEdgesNodeDefaultArtifactType.model_rebuild()
+RegistryCollectionsPageEdgesNodeProject.model_rebuild()
+RegistryCollectionsPageEdgesNodeProjectEntity.model_rebuild()
+RegistryCollectionsPageEdgesNodeTags.model_rebuild()
+RegistryCollectionsPageEdgesNodeTagsEdges.model_rebuild()
+RegistryCollectionsPageEdgesNodeTagsEdgesNode.model_rebuild()
+RegistryCollectionsPagePageInfo.model_rebuild()
+RegistryFragment.model_rebuild()
+RegistryFragmentArtifactTypes.model_rebuild()
+RegistryFragmentArtifactTypesEdges.model_rebuild()
+RegistryFragmentArtifactTypesEdgesNode.model_rebuild()
+RegistryVersionsPage.model_rebuild()
+RegistryVersionsPageEdges.model_rebuild()
+RegistryVersionsPageEdgesNode.model_rebuild()
+RegistryVersionsPageEdgesNodeAliases.model_rebuild()
+RegistryVersionsPageEdgesNodeArtifactCollection.model_rebuild()
+RegistryVersionsPageEdgesNodeArtifactCollectionProject.model_rebuild()
+RegistryVersionsPageEdgesNodeArtifactCollectionProjectEntity.model_rebuild()
+RegistryVersionsPagePageInfo.model_rebuild()
+RunInputArtifactConnectionFragment.model_rebuild()
+RunInputArtifactConnectionFragmentEdges.model_rebuild()
+RunInputArtifactConnectionFragmentPageInfo.model_rebuild()
+RunOutputArtifactConnectionFragment.model_rebuild()
+RunOutputArtifactConnectionFragmentEdges.model_rebuild()
+RunOutputArtifactConnectionFragmentPageInfo.model_rebuild()
+TypeInfoFragment.model_rebuild()
+TypeInfoFragmentFields.model_rebuild()
+TypeInfoFragmentFieldsArgs.model_rebuild()
+TypeInfoFragmentInputFields.model_rebuild()
+ArtifactFragment.model_rebuild()
+ArtifactFragmentWithoutAliases.model_rebuild()
+ArtifactTypeFragment.model_rebuild()
+RegistryFragment.model_rebuild()
+ArtifactFragment.model_rebuild()
+ArtifactFragment.model_rebuild()
+ArtifactFragment.model_rebuild()
+ArtifactFragment.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/input_types.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/input_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b3f1b971142127810c96b52b222453b00382935
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/input_types.py
@@ -0,0 +1,46 @@
+# Generated by ariadne-codegen
+# Source: core/api/graphql/schemas/schema-latest.graphql
+
+from __future__ import annotations
+
+from typing import Any, List, Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase, GQLId
+
+
+class ArtifactAliasInput(GQLBase):
+ artifact_collection_name: str = Field(alias="artifactCollectionName")
+ alias: str
+
+
+class LinkArtifactInput(GQLBase):
+ artifact_id: Optional[GQLId] = Field(alias="artifactID", default=None)
+ artifact_portfolio_id: Optional[GQLId] = Field(
+ alias="artifactPortfolioID", default=None
+ )
+ artifact_portfolio_name: Optional[str] = Field(
+ alias="artifactPortfolioName", default=None
+ )
+ entity_name: Optional[str] = Field(alias="entityName", default=None)
+ project_name: Optional[str] = Field(alias="projectName", default=None)
+ aliases: Optional[List[ArtifactAliasInput]] = None
+ client_id: Optional[GQLId] = Field(alias="clientID", default=None)
+ client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None)
+
+
+class ArtifactCollectionAliasInput(GQLBase):
+ alias: str
+ entity_name: str = Field(alias="entityName")
+ project_name: str = Field(alias="projectName")
+ artifact_collection_name: str = Field(alias="artifactCollectionName")
+
+
+class TagInput(GQLBase):
+ tag_category_name: Optional[str] = Field(alias="tagCategoryName", default=None)
+ tag_name: str = Field(alias="tagName")
+ attributes: Optional[Any] = None
+
+
+LinkArtifactInput.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/link_artifact.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/link_artifact.py
new file mode 100644
index 0000000000000000000000000000000000000000..378a803cee92ba77d4fa39992591199c23b6ed7a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/link_artifact.py
@@ -0,0 +1,27 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+from .fragments import MembershipWithArtifact
+
+
+class LinkArtifact(GQLBase):
+ link_artifact: Optional[LinkArtifactLinkArtifact] = Field(alias="linkArtifact")
+
+
+class LinkArtifactLinkArtifact(GQLBase):
+ version_index: Optional[int] = Field(alias="versionIndex")
+ artifact_membership: Optional[MembershipWithArtifact] = Field(
+ alias="artifactMembership", default=None
+ )
+
+
+LinkArtifact.model_rebuild()
+LinkArtifactLinkArtifact.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/move_artifact_collection.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/move_artifact_collection.py
new file mode 100644
index 0000000000000000000000000000000000000000..31c142e24ace6a111ffc6c53aefe192d9a3c293b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/move_artifact_collection.py
@@ -0,0 +1,35 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Literal, Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase, GQLId, Typename
+
+
+class MoveArtifactCollection(GQLBase):
+ move_artifact_sequence: Optional[MoveArtifactCollectionMoveArtifactSequence] = (
+ Field(alias="moveArtifactSequence")
+ )
+
+
+class MoveArtifactCollectionMoveArtifactSequence(GQLBase):
+ artifact_collection: Optional[
+ MoveArtifactCollectionMoveArtifactSequenceArtifactCollection
+ ] = Field(alias="artifactCollection")
+
+
+class MoveArtifactCollectionMoveArtifactSequenceArtifactCollection(GQLBase):
+ typename__: Typename[
+ Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"]
+ ]
+ id: GQLId
+ name: str
+ description: Optional[str]
+
+
+MoveArtifactCollection.model_rebuild()
+MoveArtifactCollectionMoveArtifactSequence.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/operations.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/operations.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4710cc833f1a48b65eeb97b532942d64595fb23
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/operations.py
@@ -0,0 +1,1253 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+__all__ = [
+ "ADD_ALIASES_GQL",
+ "ARTIFACT_BY_ID_GQL",
+ "ARTIFACT_BY_NAME_GQL",
+ "ARTIFACT_COLLECTION_MEMBERSHIP_FILES_GQL",
+ "ARTIFACT_COLLECTION_MEMBERSHIP_FILE_URLS_GQL",
+ "ARTIFACT_CREATED_BY_GQL",
+ "ARTIFACT_FILE_URLS_GQL",
+ "ARTIFACT_TYPE_GQL",
+ "ARTIFACT_USED_BY_GQL",
+ "ARTIFACT_VERSION_FILES_GQL",
+ "ARTIFACT_VIA_MEMBERSHIP_BY_NAME_GQL",
+ "CREATE_ARTIFACT_COLLECTION_TAG_ASSIGNMENTS_GQL",
+ "DELETE_ALIASES_GQL",
+ "DELETE_ARTIFACT_COLLECTION_TAG_ASSIGNMENTS_GQL",
+ "DELETE_ARTIFACT_GQL",
+ "DELETE_ARTIFACT_PORTFOLIO_GQL",
+ "DELETE_ARTIFACT_SEQUENCE_GQL",
+ "FETCH_ARTIFACT_MANIFEST_GQL",
+ "FETCH_LINKED_ARTIFACTS_GQL",
+ "FETCH_REGISTRIES_GQL",
+ "LINK_ARTIFACT_GQL",
+ "MOVE_ARTIFACT_COLLECTION_GQL",
+ "PROJECT_ARTIFACTS_GQL",
+ "PROJECT_ARTIFACT_COLLECTIONS_GQL",
+ "PROJECT_ARTIFACT_COLLECTION_GQL",
+ "PROJECT_ARTIFACT_TYPES_GQL",
+ "PROJECT_ARTIFACT_TYPE_GQL",
+ "REGISTRY_COLLECTIONS_GQL",
+ "REGISTRY_VERSIONS_GQL",
+ "RUN_INPUT_ARTIFACTS_GQL",
+ "RUN_OUTPUT_ARTIFACTS_GQL",
+ "TYPE_INFO_GQL",
+ "UNLINK_ARTIFACT_GQL",
+ "UPDATE_ARTIFACT_GQL",
+ "UPDATE_ARTIFACT_PORTFOLIO_GQL",
+ "UPDATE_ARTIFACT_SEQUENCE_GQL",
+]
+
+DELETE_ARTIFACT_SEQUENCE_GQL = """
+mutation DeleteArtifactSequence($id: ID!) {
+ deleteArtifactSequence(input: {artifactSequenceID: $id}) {
+ artifactCollection {
+ __typename
+ state
+ }
+ }
+}
+"""
+
+DELETE_ARTIFACT_PORTFOLIO_GQL = """
+mutation DeleteArtifactPortfolio($id: ID!) {
+ deleteArtifactPortfolio(input: {artifactPortfolioID: $id}) {
+ artifactCollection {
+ __typename
+ state
+ }
+ }
+}
+"""
+
+UPDATE_ARTIFACT_SEQUENCE_GQL = """
+mutation UpdateArtifactSequence($id: ID!, $name: String, $description: String) {
+ updateArtifactSequence(
+ input: {artifactSequenceID: $id, name: $name, description: $description}
+ ) {
+ artifactCollection {
+ __typename
+ id
+ name
+ description
+ }
+ }
+}
+"""
+
+UPDATE_ARTIFACT_PORTFOLIO_GQL = """
+mutation UpdateArtifactPortfolio($id: ID!, $name: String, $description: String) {
+ updateArtifactPortfolio(
+ input: {artifactPortfolioID: $id, name: $name, description: $description}
+ ) {
+ artifactCollection {
+ __typename
+ id
+ name
+ description
+ }
+ }
+}
+"""
+
+MOVE_ARTIFACT_COLLECTION_GQL = """
+mutation MoveArtifactCollection($artifactSequenceID: ID!, $destinationArtifactTypeName: String!) {
+ moveArtifactSequence(
+ input: {artifactSequenceID: $artifactSequenceID, destinationArtifactTypeName: $destinationArtifactTypeName}
+ ) {
+ artifactCollection {
+ __typename
+ id
+ name
+ description
+ }
+ }
+}
+"""
+
+CREATE_ARTIFACT_COLLECTION_TAG_ASSIGNMENTS_GQL = """
+mutation CreateArtifactCollectionTagAssignments($entityName: String!, $projectName: String!, $artifactCollectionName: String!, $tags: [TagInput!]!) {
+ createArtifactCollectionTagAssignments(
+ input: {entityName: $entityName, projectName: $projectName, artifactCollectionName: $artifactCollectionName, tags: $tags}
+ ) {
+ tags {
+ id
+ name
+ tagCategoryName
+ }
+ }
+}
+"""
+
+DELETE_ARTIFACT_COLLECTION_TAG_ASSIGNMENTS_GQL = """
+mutation DeleteArtifactCollectionTagAssignments($entityName: String!, $projectName: String!, $artifactCollectionName: String!, $tags: [TagInput!]!) {
+ deleteArtifactCollectionTagAssignments(
+ input: {entityName: $entityName, projectName: $projectName, artifactCollectionName: $artifactCollectionName, tags: $tags}
+ ) {
+ success
+ }
+}
+"""
+
+PROJECT_ARTIFACT_COLLECTIONS_GQL = """
+query ProjectArtifactCollections($entityName: String!, $projectName: String!, $artifactTypeName: String!, $cursor: String) {
+ project(name: $projectName, entityName: $entityName) {
+ artifactType(name: $artifactTypeName) {
+ artifactCollections: artifactCollections(after: $cursor) {
+ ...ArtifactCollectionsFragment
+ }
+ }
+ }
+}
+
+fragment ArtifactCollectionsFragment on ArtifactCollectionConnection {
+ pageInfo {
+ endCursor
+ hasNextPage
+ }
+ totalCount
+ edges {
+ node {
+ __typename
+ id
+ name
+ description
+ createdAt
+ }
+ cursor
+ }
+}
+"""
+
+PROJECT_ARTIFACT_COLLECTION_GQL = """
+query ProjectArtifactCollection($entityName: String!, $projectName: String!, $artifactTypeName: String!, $artifactCollectionName: String!, $cursor: String, $perPage: Int = 1000) {
+ project(name: $projectName, entityName: $entityName) {
+ artifactType(name: $artifactTypeName) {
+ artifactCollection: artifactCollection(name: $artifactCollectionName) {
+ __typename
+ id
+ name
+ description
+ createdAt
+ tags {
+ edges {
+ node {
+ id
+ name
+ }
+ }
+ }
+ aliases(after: $cursor, first: $perPage) {
+ edges {
+ node {
+ alias
+ }
+ cursor
+ }
+ pageInfo {
+ endCursor
+ hasNextPage
+ }
+ }
+ }
+ artifactSequence(name: $artifactCollectionName) {
+ __typename
+ }
+ }
+ }
+}
+"""
+
+ARTIFACT_VERSION_FILES_GQL = """
+query ArtifactVersionFiles($entityName: String!, $projectName: String!, $artifactTypeName: String!, $artifactName: String!, $fileNames: [String!], $fileCursor: String, $fileLimit: Int = 50) {
+ project(name: $projectName, entityName: $entityName) {
+ artifactType(name: $artifactTypeName) {
+ artifact(name: $artifactName) {
+ files(names: $fileNames, after: $fileCursor, first: $fileLimit) {
+ ...FilesFragment
+ }
+ }
+ }
+ }
+}
+
+fragment FilesFragment on FileConnection {
+ edges {
+ node {
+ id
+ name: displayName
+ url
+ sizeBytes
+ storagePath @include(if: true)
+ mimetype
+ updatedAt
+ digest
+ md5
+ directUrl
+ }
+ cursor
+ }
+ pageInfo {
+ endCursor
+ hasNextPage
+ }
+}
+"""
+
+ARTIFACT_COLLECTION_MEMBERSHIP_FILES_GQL = """
+query ArtifactCollectionMembershipFiles($entityName: String!, $projectName: String!, $artifactName: String!, $artifactVersionIndex: String!, $fileNames: [String!], $fileCursor: String, $fileLimit: Int = 50) {
+ project(name: $projectName, entityName: $entityName) {
+ artifactCollection(name: $artifactName) {
+ __typename
+ artifactMembership(aliasName: $artifactVersionIndex) {
+ files(names: $fileNames, after: $fileCursor, first: $fileLimit) {
+ ...FilesFragment
+ }
+ }
+ }
+ }
+}
+
+fragment FilesFragment on FileConnection {
+ edges {
+ node {
+ id
+ name: displayName
+ url
+ sizeBytes
+ storagePath @include(if: true)
+ mimetype
+ updatedAt
+ digest
+ md5
+ directUrl
+ }
+ cursor
+ }
+ pageInfo {
+ endCursor
+ hasNextPage
+ }
+}
+"""
+
+ARTIFACT_COLLECTION_MEMBERSHIP_FILE_URLS_GQL = """
+query ArtifactCollectionMembershipFileUrls($entityName: String!, $projectName: String!, $artifactName: String!, $artifactVersionIndex: String!, $cursor: String, $perPage: Int) {
+ project(name: $projectName, entityName: $entityName) {
+ artifactCollection(name: $artifactName) {
+ __typename
+ artifactMembership(aliasName: $artifactVersionIndex) {
+ files(after: $cursor, first: $perPage) {
+ ...FileUrlsFragment
+ }
+ }
+ }
+ }
+}
+
+fragment FileUrlsFragment on FileConnection {
+ pageInfo {
+ hasNextPage
+ endCursor
+ }
+ edges {
+ node {
+ name
+ directUrl
+ }
+ }
+}
+"""
+
+ARTIFACT_FILE_URLS_GQL = """
+query ArtifactFileUrls($id: ID!, $cursor: String, $perPage: Int) {
+ artifact(id: $id) {
+ files(after: $cursor, first: $perPage) {
+ ...FileUrlsFragment
+ }
+ }
+}
+
+fragment FileUrlsFragment on FileConnection {
+ pageInfo {
+ hasNextPage
+ endCursor
+ }
+ edges {
+ node {
+ name
+ directUrl
+ }
+ }
+}
+"""
+
+PROJECT_ARTIFACT_TYPES_GQL = """
+query ProjectArtifactTypes($entityName: String!, $projectName: String!, $cursor: String) {
+ project(name: $projectName, entityName: $entityName) {
+ artifactTypes(after: $cursor) {
+ ...ArtifactTypesFragment
+ }
+ }
+}
+
+fragment ArtifactTypeFragment on ArtifactType {
+ __typename
+ id
+ name
+ description
+ createdAt
+}
+
+fragment ArtifactTypesFragment on ArtifactTypeConnection {
+ edges {
+ node {
+ ...ArtifactTypeFragment
+ }
+ cursor
+ }
+ pageInfo {
+ endCursor
+ hasNextPage
+ }
+}
+"""
+
+PROJECT_ARTIFACT_TYPE_GQL = """
+query ProjectArtifactType($entityName: String!, $projectName: String!, $artifactTypeName: String!) {
+ project(name: $projectName, entityName: $entityName) {
+ artifactType(name: $artifactTypeName) {
+ ...ArtifactTypeFragment
+ }
+ }
+}
+
+fragment ArtifactTypeFragment on ArtifactType {
+ __typename
+ id
+ name
+ description
+ createdAt
+}
+"""
+
+PROJECT_ARTIFACTS_GQL = """
+query ProjectArtifacts($project: String!, $entity: String!, $type: String!, $collection: String!, $cursor: String, $perPage: Int = 50, $order: String, $filters: JSONString) {
+ project(name: $project, entityName: $entity) {
+ artifactType(name: $type) {
+ artifactCollection: artifactCollection(name: $collection) {
+ __typename
+ name
+ artifacts(filters: $filters, after: $cursor, first: $perPage, order: $order) {
+ ...ArtifactsFragment
+ }
+ }
+ }
+ }
+}
+
+fragment ArtifactFragment on Artifact {
+ ...ArtifactFragmentWithoutAliases
+ aliases @include(if: true) {
+ artifactCollection {
+ __typename
+ project {
+ entityName
+ name
+ }
+ name
+ }
+ alias
+ }
+}
+
+fragment ArtifactFragmentWithoutAliases on Artifact {
+ id
+ artifactSequence {
+ project {
+ entityName
+ name
+ }
+ name
+ }
+ versionIndex
+ artifactType {
+ name
+ }
+ description
+ metadata
+ ttlDurationSeconds @include(if: true)
+ ttlIsInherited @include(if: true)
+ tags @include(if: true) {
+ name
+ }
+ historyStep @include(if: true)
+ state
+ currentManifest {
+ file {
+ directUrl
+ }
+ }
+ commitHash
+ fileCount
+ createdAt
+ updatedAt
+}
+
+fragment ArtifactsFragment on VersionedArtifactConnection {
+ totalCount
+ edges {
+ node {
+ ...ArtifactFragment
+ }
+ version
+ cursor
+ }
+ pageInfo {
+ endCursor
+ hasNextPage
+ }
+}
+"""
+
+RUN_OUTPUT_ARTIFACTS_GQL = """
+query RunOutputArtifacts($entity: String!, $project: String!, $runName: String!, $cursor: String, $perPage: Int) {
+ project(name: $project, entityName: $entity) {
+ run(name: $runName) {
+ outputArtifacts(after: $cursor, first: $perPage) {
+ ...RunOutputArtifactConnectionFragment
+ }
+ }
+ }
+}
+
+fragment ArtifactFragment on Artifact {
+ ...ArtifactFragmentWithoutAliases
+ aliases @include(if: true) {
+ artifactCollection {
+ __typename
+ project {
+ entityName
+ name
+ }
+ name
+ }
+ alias
+ }
+}
+
+fragment ArtifactFragmentWithoutAliases on Artifact {
+ id
+ artifactSequence {
+ project {
+ entityName
+ name
+ }
+ name
+ }
+ versionIndex
+ artifactType {
+ name
+ }
+ description
+ metadata
+ ttlDurationSeconds @include(if: true)
+ ttlIsInherited @include(if: true)
+ tags @include(if: true) {
+ name
+ }
+ historyStep @include(if: true)
+ state
+ currentManifest {
+ file {
+ directUrl
+ }
+ }
+ commitHash
+ fileCount
+ createdAt
+ updatedAt
+}
+
+fragment RunOutputArtifactConnectionFragment on ArtifactConnection {
+ totalCount
+ edges {
+ node {
+ ...ArtifactFragment
+ }
+ cursor
+ }
+ pageInfo {
+ endCursor
+ hasNextPage
+ }
+}
+"""
+
+RUN_INPUT_ARTIFACTS_GQL = """
+query RunInputArtifacts($entity: String!, $project: String!, $runName: String!, $cursor: String, $perPage: Int) {
+ project(name: $project, entityName: $entity) {
+ run(name: $runName) {
+ inputArtifacts(after: $cursor, first: $perPage) {
+ ...RunInputArtifactConnectionFragment
+ }
+ }
+ }
+}
+
+fragment ArtifactFragment on Artifact {
+ ...ArtifactFragmentWithoutAliases
+ aliases @include(if: true) {
+ artifactCollection {
+ __typename
+ project {
+ entityName
+ name
+ }
+ name
+ }
+ alias
+ }
+}
+
+fragment ArtifactFragmentWithoutAliases on Artifact {
+ id
+ artifactSequence {
+ project {
+ entityName
+ name
+ }
+ name
+ }
+ versionIndex
+ artifactType {
+ name
+ }
+ description
+ metadata
+ ttlDurationSeconds @include(if: true)
+ ttlIsInherited @include(if: true)
+ tags @include(if: true) {
+ name
+ }
+ historyStep @include(if: true)
+ state
+ currentManifest {
+ file {
+ directUrl
+ }
+ }
+ commitHash
+ fileCount
+ createdAt
+ updatedAt
+}
+
+fragment RunInputArtifactConnectionFragment on InputArtifactConnection {
+ totalCount
+ edges {
+ node {
+ ...ArtifactFragment
+ }
+ cursor
+ }
+ pageInfo {
+ endCursor
+ hasNextPage
+ }
+}
+"""
+
+FETCH_LINKED_ARTIFACTS_GQL = """
+query FetchLinkedArtifacts($artifactID: ID!) {
+ artifact(id: $artifactID) {
+ artifactMemberships {
+ edges {
+ node {
+ aliases {
+ alias
+ }
+ versionIndex
+ artifactCollection {
+ project {
+ entityName
+ name
+ }
+ name
+ __typename
+ }
+ }
+ }
+ }
+ }
+}
+"""
+
+FETCH_ARTIFACT_MANIFEST_GQL = """
+query FetchArtifactManifest($entityName: String!, $projectName: String!, $name: String!) {
+ project(entityName: $entityName, name: $projectName) {
+ artifact(name: $name) {
+ currentManifest {
+ file {
+ directUrl
+ }
+ }
+ }
+ }
+}
+"""
+
+ARTIFACT_BY_ID_GQL = """
+query ArtifactByID($id: ID!) {
+ artifact(id: $id) {
+ ...ArtifactFragment
+ }
+}
+
+fragment ArtifactFragment on Artifact {
+ ...ArtifactFragmentWithoutAliases
+ aliases @include(if: true) {
+ artifactCollection {
+ __typename
+ project {
+ entityName
+ name
+ }
+ name
+ }
+ alias
+ }
+}
+
+fragment ArtifactFragmentWithoutAliases on Artifact {
+ id
+ artifactSequence {
+ project {
+ entityName
+ name
+ }
+ name
+ }
+ versionIndex
+ artifactType {
+ name
+ }
+ description
+ metadata
+ ttlDurationSeconds @include(if: true)
+ ttlIsInherited @include(if: true)
+ tags @include(if: true) {
+ name
+ }
+ historyStep @include(if: true)
+ state
+ currentManifest {
+ file {
+ directUrl
+ }
+ }
+ commitHash
+ fileCount
+ createdAt
+ updatedAt
+}
+"""
+
+ARTIFACT_BY_NAME_GQL = """
+query ArtifactByName($entityName: String!, $projectName: String!, $name: String!, $enableTracking: Boolean) {
+ project(name: $projectName, entityName: $entityName) {
+ artifact(name: $name, enableTracking: $enableTracking) {
+ ...ArtifactFragment
+ }
+ }
+}
+
+fragment ArtifactFragment on Artifact {
+ ...ArtifactFragmentWithoutAliases
+ aliases @include(if: true) {
+ artifactCollection {
+ __typename
+ project {
+ entityName
+ name
+ }
+ name
+ }
+ alias
+ }
+}
+
+fragment ArtifactFragmentWithoutAliases on Artifact {
+ id
+ artifactSequence {
+ project {
+ entityName
+ name
+ }
+ name
+ }
+ versionIndex
+ artifactType {
+ name
+ }
+ description
+ metadata
+ ttlDurationSeconds @include(if: true)
+ ttlIsInherited @include(if: true)
+ tags @include(if: true) {
+ name
+ }
+ historyStep @include(if: true)
+ state
+ currentManifest {
+ file {
+ directUrl
+ }
+ }
+ commitHash
+ fileCount
+ createdAt
+ updatedAt
+}
+"""
+
+ARTIFACT_VIA_MEMBERSHIP_BY_NAME_GQL = """
+query ArtifactViaMembershipByName($entityName: String!, $projectName: String!, $name: String!) {
+ project(name: $projectName, entityName: $entityName) {
+ artifactCollectionMembership(name: $name) {
+ ...MembershipWithArtifact
+ }
+ }
+}
+
+fragment ArtifactFragment on Artifact {
+ ...ArtifactFragmentWithoutAliases
+ aliases @include(if: true) {
+ artifactCollection {
+ __typename
+ project {
+ entityName
+ name
+ }
+ name
+ }
+ alias
+ }
+}
+
+fragment ArtifactFragmentWithoutAliases on Artifact {
+ id
+ artifactSequence {
+ project {
+ entityName
+ name
+ }
+ name
+ }
+ versionIndex
+ artifactType {
+ name
+ }
+ description
+ metadata
+ ttlDurationSeconds @include(if: true)
+ ttlIsInherited @include(if: true)
+ tags @include(if: true) {
+ name
+ }
+ historyStep @include(if: true)
+ state
+ currentManifest {
+ file {
+ directUrl
+ }
+ }
+ commitHash
+ fileCount
+ createdAt
+ updatedAt
+}
+
+fragment MembershipWithArtifact on ArtifactCollectionMembership {
+ id
+ artifactCollection {
+ __typename
+ id
+ name
+ project {
+ id
+ entityName
+ name
+ }
+ }
+ artifact {
+ ...ArtifactFragment
+ }
+}
+"""
+
+ARTIFACT_USED_BY_GQL = """
+query ArtifactUsedBy($id: ID!) {
+ artifact(id: $id) {
+ usedBy {
+ edges {
+ node {
+ name
+ project {
+ name
+ entityName
+ }
+ }
+ }
+ }
+ }
+}
+"""
+
+ARTIFACT_CREATED_BY_GQL = """
+query ArtifactCreatedBy($id: ID!) {
+ artifact(id: $id) {
+ createdBy {
+ __typename
+ ... on Run {
+ name
+ project {
+ name
+ entityName
+ }
+ }
+ }
+ }
+}
+"""
+
+ARTIFACT_TYPE_GQL = """
+query ArtifactType($entityName: String, $projectName: String, $name: String!) {
+ project(name: $projectName, entityName: $entityName) {
+ artifact(name: $name) {
+ artifactType {
+ name
+ }
+ }
+ }
+}
+"""
+
+ADD_ALIASES_GQL = """
+mutation AddAliases($artifactID: ID!, $aliases: [ArtifactCollectionAliasInput!]!) {
+ addAliases(input: {artifactID: $artifactID, aliases: $aliases}) {
+ success
+ }
+}
+"""
+
+DELETE_ALIASES_GQL = """
+mutation DeleteAliases($artifactID: ID!, $aliases: [ArtifactCollectionAliasInput!]!) {
+ deleteAliases(input: {artifactID: $artifactID, aliases: $aliases}) {
+ success
+ }
+}
+"""
+
+UPDATE_ARTIFACT_GQL = """
+mutation UpdateArtifact($artifactID: ID!, $description: String, $metadata: JSONString, $ttlDurationSeconds: Int64, $tagsToAdd: [TagInput!], $tagsToDelete: [TagInput!], $aliases: [ArtifactAliasInput!]) {
+ updateArtifact(
+ input: {artifactID: $artifactID, description: $description, metadata: $metadata, ttlDurationSeconds: $ttlDurationSeconds, tagsToAdd: $tagsToAdd, tagsToDelete: $tagsToDelete, aliases: $aliases}
+ ) {
+ artifact {
+ ...ArtifactFragment
+ }
+ }
+}
+
+fragment ArtifactFragment on Artifact {
+ ...ArtifactFragmentWithoutAliases
+ aliases @include(if: true) {
+ artifactCollection {
+ __typename
+ project {
+ entityName
+ name
+ }
+ name
+ }
+ alias
+ }
+}
+
+fragment ArtifactFragmentWithoutAliases on Artifact {
+ id
+ artifactSequence {
+ project {
+ entityName
+ name
+ }
+ name
+ }
+ versionIndex
+ artifactType {
+ name
+ }
+ description
+ metadata
+ ttlDurationSeconds @include(if: true)
+ ttlIsInherited @include(if: true)
+ tags @include(if: true) {
+ name
+ }
+ historyStep @include(if: true)
+ state
+ currentManifest {
+ file {
+ directUrl
+ }
+ }
+ commitHash
+ fileCount
+ createdAt
+ updatedAt
+}
+"""
+
+DELETE_ARTIFACT_GQL = """
+mutation DeleteArtifact($artifactID: ID!, $deleteAliases: Boolean) {
+ deleteArtifact(input: {artifactID: $artifactID, deleteAliases: $deleteAliases}) {
+ artifact {
+ id
+ }
+ }
+}
+"""
+
+LINK_ARTIFACT_GQL = """
+mutation LinkArtifact($input: LinkArtifactInput!) {
+ linkArtifact(input: $input) {
+ versionIndex
+ artifactMembership @include(if: true) {
+ ...MembershipWithArtifact
+ }
+ }
+}
+
+fragment ArtifactFragment on Artifact {
+ ...ArtifactFragmentWithoutAliases
+ aliases @include(if: true) {
+ artifactCollection {
+ __typename
+ project {
+ entityName
+ name
+ }
+ name
+ }
+ alias
+ }
+}
+
+fragment ArtifactFragmentWithoutAliases on Artifact {
+ id
+ artifactSequence {
+ project {
+ entityName
+ name
+ }
+ name
+ }
+ versionIndex
+ artifactType {
+ name
+ }
+ description
+ metadata
+ ttlDurationSeconds @include(if: true)
+ ttlIsInherited @include(if: true)
+ tags @include(if: true) {
+ name
+ }
+ historyStep @include(if: true)
+ state
+ currentManifest {
+ file {
+ directUrl
+ }
+ }
+ commitHash
+ fileCount
+ createdAt
+ updatedAt
+}
+
+fragment MembershipWithArtifact on ArtifactCollectionMembership {
+ id
+ artifactCollection {
+ __typename
+ id
+ name
+ project {
+ id
+ entityName
+ name
+ }
+ }
+ artifact {
+ ...ArtifactFragment
+ }
+}
+"""
+
+UNLINK_ARTIFACT_GQL = """
+mutation UnlinkArtifact($artifactID: ID!, $artifactPortfolioID: ID!) {
+ unlinkArtifact(
+ input: {artifactID: $artifactID, artifactPortfolioID: $artifactPortfolioID}
+ ) {
+ artifactID
+ success
+ clientMutationId
+ }
+}
+"""
+
+TYPE_INFO_GQL = """
+query TypeInfo($name: String!) {
+ __type(name: $name) {
+ ...TypeInfoFragment
+ }
+}
+
+fragment TypeInfoFragment on __Type {
+ name
+ fields {
+ name
+ args {
+ name
+ }
+ }
+ inputFields {
+ name
+ }
+}
+"""
+
+REGISTRY_VERSIONS_GQL = """
+query RegistryVersions($organization: String!, $registryFilter: JSONString, $collectionFilter: JSONString, $artifactFilter: JSONString, $cursor: String, $perPage: Int) {
+ organization(name: $organization) {
+ orgEntity {
+ name
+ artifactMemberships(
+ projectFilters: $registryFilter
+ collectionFilters: $collectionFilter
+ filters: $artifactFilter
+ after: $cursor
+ first: $perPage
+ ) {
+ ...RegistryVersionsPage
+ }
+ }
+ }
+}
+
+fragment ArtifactFragmentWithoutAliases on Artifact {
+ id
+ artifactSequence {
+ project {
+ entityName
+ name
+ }
+ name
+ }
+ versionIndex
+ artifactType {
+ name
+ }
+ description
+ metadata
+ ttlDurationSeconds @include(if: true)
+ ttlIsInherited @include(if: true)
+ tags @include(if: true) {
+ name
+ }
+ historyStep @include(if: true)
+ state
+ currentManifest {
+ file {
+ directUrl
+ }
+ }
+ commitHash
+ fileCount
+ createdAt
+ updatedAt
+}
+
+fragment RegistryVersionsPage on ArtifactCollectionMembershipConnection {
+ pageInfo {
+ endCursor
+ hasNextPage
+ }
+ edges {
+ node {
+ artifactCollection {
+ __typename
+ project {
+ name
+ entity {
+ name
+ }
+ }
+ name
+ }
+ versionIndex
+ artifact {
+ ...ArtifactFragmentWithoutAliases
+ }
+ aliases {
+ alias
+ }
+ }
+ }
+}
+"""
+
+REGISTRY_COLLECTIONS_GQL = """
+query RegistryCollections($organization: String!, $registryFilter: JSONString, $collectionFilter: JSONString, $collectionTypes: [ArtifactCollectionType!], $cursor: String, $perPage: Int) {
+ organization(name: $organization) {
+ orgEntity {
+ name
+ artifactCollections(
+ projectFilters: $registryFilter
+ filters: $collectionFilter
+ collectionTypes: $collectionTypes
+ after: $cursor
+ first: $perPage
+ ) {
+ ...RegistryCollectionsPage
+ }
+ }
+ }
+}
+
+fragment RegistryCollectionsPage on ArtifactCollectionConnection {
+ totalCount
+ pageInfo {
+ endCursor
+ hasNextPage
+ }
+ edges {
+ cursor
+ node {
+ __typename
+ id
+ name
+ description
+ createdAt
+ tags {
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ project {
+ name
+ entity {
+ name
+ }
+ }
+ defaultArtifactType {
+ name
+ }
+ aliases {
+ edges {
+ node {
+ alias
+ }
+ }
+ }
+ }
+ }
+}
+"""
+
+FETCH_REGISTRIES_GQL = """
+query FetchRegistries($organization: String!, $filters: JSONString, $cursor: String, $perPage: Int) {
+ organization(name: $organization) {
+ orgEntity {
+ name
+ projects(filters: $filters, after: $cursor, first: $perPage) {
+ ...RegistriesPage
+ }
+ }
+ }
+}
+
+fragment RegistriesPage on ProjectConnection {
+ pageInfo {
+ endCursor
+ hasNextPage
+ }
+ edges {
+ node {
+ ...RegistryFragment
+ }
+ }
+}
+
+fragment RegistryFragment on Project {
+ id
+ allowAllArtifactTypesInRegistry
+ artifactTypes(includeAll: true) {
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ name
+ description
+ createdAt
+ updatedAt
+ access
+}
+"""
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_collection.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_collection.py
new file mode 100644
index 0000000000000000000000000000000000000000..12e2342db24aae84e79b87e287f0abb87d46453f
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_collection.py
@@ -0,0 +1,101 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import List, Literal, Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase, GQLId, Typename
+
+
+class ProjectArtifactCollection(GQLBase):
+ project: Optional[ProjectArtifactCollectionProject]
+
+
+class ProjectArtifactCollectionProject(GQLBase):
+ artifact_type: Optional[ProjectArtifactCollectionProjectArtifactType] = Field(
+ alias="artifactType"
+ )
+
+
+class ProjectArtifactCollectionProjectArtifactType(GQLBase):
+ artifact_collection: Optional[
+ ProjectArtifactCollectionProjectArtifactTypeArtifactCollection
+ ] = Field(alias="artifactCollection")
+ artifact_sequence: Optional[
+ ProjectArtifactCollectionProjectArtifactTypeArtifactSequence
+ ] = Field(alias="artifactSequence")
+
+
+class ProjectArtifactCollectionProjectArtifactTypeArtifactCollection(GQLBase):
+ typename__: Typename[
+ Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"]
+ ]
+ id: GQLId
+ name: str
+ description: Optional[str]
+ created_at: str = Field(alias="createdAt")
+ tags: ProjectArtifactCollectionProjectArtifactTypeArtifactCollectionTags
+ aliases: ProjectArtifactCollectionProjectArtifactTypeArtifactCollectionAliases
+
+
+class ProjectArtifactCollectionProjectArtifactTypeArtifactCollectionTags(GQLBase):
+ edges: List[ProjectArtifactCollectionProjectArtifactTypeArtifactCollectionTagsEdges]
+
+
+class ProjectArtifactCollectionProjectArtifactTypeArtifactCollectionTagsEdges(GQLBase):
+ node: ProjectArtifactCollectionProjectArtifactTypeArtifactCollectionTagsEdgesNode
+
+
+class ProjectArtifactCollectionProjectArtifactTypeArtifactCollectionTagsEdgesNode(
+ GQLBase
+):
+ id: GQLId
+ name: str
+
+
+class ProjectArtifactCollectionProjectArtifactTypeArtifactCollectionAliases(GQLBase):
+ edges: List[
+ ProjectArtifactCollectionProjectArtifactTypeArtifactCollectionAliasesEdges
+ ]
+ page_info: ProjectArtifactCollectionProjectArtifactTypeArtifactCollectionAliasesPageInfo = Field(
+ alias="pageInfo"
+ )
+
+
+class ProjectArtifactCollectionProjectArtifactTypeArtifactCollectionAliasesEdges(
+ GQLBase
+):
+ node: Optional[
+ ProjectArtifactCollectionProjectArtifactTypeArtifactCollectionAliasesEdgesNode
+ ]
+ cursor: str
+
+
+class ProjectArtifactCollectionProjectArtifactTypeArtifactCollectionAliasesEdgesNode(
+ GQLBase
+):
+ alias: str
+
+
+class ProjectArtifactCollectionProjectArtifactTypeArtifactCollectionAliasesPageInfo(
+ GQLBase
+):
+ end_cursor: Optional[str] = Field(alias="endCursor")
+ has_next_page: bool = Field(alias="hasNextPage")
+
+
+class ProjectArtifactCollectionProjectArtifactTypeArtifactSequence(GQLBase):
+ typename__: Typename[Literal["ArtifactSequence"]]
+
+
+ProjectArtifactCollection.model_rebuild()
+ProjectArtifactCollectionProject.model_rebuild()
+ProjectArtifactCollectionProjectArtifactType.model_rebuild()
+ProjectArtifactCollectionProjectArtifactTypeArtifactCollection.model_rebuild()
+ProjectArtifactCollectionProjectArtifactTypeArtifactCollectionTags.model_rebuild()
+ProjectArtifactCollectionProjectArtifactTypeArtifactCollectionTagsEdges.model_rebuild()
+ProjectArtifactCollectionProjectArtifactTypeArtifactCollectionAliases.model_rebuild()
+ProjectArtifactCollectionProjectArtifactTypeArtifactCollectionAliasesEdges.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_collections.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_collections.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6d113d0d0ce6f0f34f2c6689ca0309e373559e3
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_collections.py
@@ -0,0 +1,33 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+from .fragments import ArtifactCollectionsFragment
+
+
+class ProjectArtifactCollections(GQLBase):
+ project: Optional[ProjectArtifactCollectionsProject]
+
+
+class ProjectArtifactCollectionsProject(GQLBase):
+ artifact_type: Optional[ProjectArtifactCollectionsProjectArtifactType] = Field(
+ alias="artifactType"
+ )
+
+
+class ProjectArtifactCollectionsProjectArtifactType(GQLBase):
+ artifact_collections: Optional[ArtifactCollectionsFragment] = Field(
+ alias="artifactCollections"
+ )
+
+
+ProjectArtifactCollections.model_rebuild()
+ProjectArtifactCollectionsProject.model_rebuild()
+ProjectArtifactCollectionsProjectArtifactType.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_type.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_type.py
new file mode 100644
index 0000000000000000000000000000000000000000..34c3ed067fba86c70f0e8b1f579eac564675eeaa
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_type.py
@@ -0,0 +1,24 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+from .fragments import ArtifactTypeFragment
+
+
+class ProjectArtifactType(GQLBase):
+ project: Optional[ProjectArtifactTypeProject]
+
+
+class ProjectArtifactTypeProject(GQLBase):
+ artifact_type: Optional[ArtifactTypeFragment] = Field(alias="artifactType")
+
+
+ProjectArtifactType.model_rebuild()
+ProjectArtifactTypeProject.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_types.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..e722d692620f0c496239e7e2d4324bb7c1c38cf8
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_types.py
@@ -0,0 +1,24 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+from .fragments import ArtifactTypesFragment
+
+
+class ProjectArtifactTypes(GQLBase):
+ project: Optional[ProjectArtifactTypesProject]
+
+
+class ProjectArtifactTypesProject(GQLBase):
+ artifact_types: ArtifactTypesFragment = Field(alias="artifactTypes")
+
+
+ProjectArtifactTypes.model_rebuild()
+ProjectArtifactTypesProject.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifacts.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifacts.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ad46c3196e3bbf2de696e798debd23e8d9e3d72
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifacts.py
@@ -0,0 +1,42 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Literal, Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase, Typename
+
+from .fragments import ArtifactsFragment
+
+
+class ProjectArtifacts(GQLBase):
+ project: Optional[ProjectArtifactsProject]
+
+
+class ProjectArtifactsProject(GQLBase):
+ artifact_type: Optional[ProjectArtifactsProjectArtifactType] = Field(
+ alias="artifactType"
+ )
+
+
+class ProjectArtifactsProjectArtifactType(GQLBase):
+ artifact_collection: Optional[
+ ProjectArtifactsProjectArtifactTypeArtifactCollection
+ ] = Field(alias="artifactCollection")
+
+
+class ProjectArtifactsProjectArtifactTypeArtifactCollection(GQLBase):
+ typename__: Typename[
+ Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"]
+ ]
+ name: str
+ artifacts: Optional[ArtifactsFragment]
+
+
+ProjectArtifacts.model_rebuild()
+ProjectArtifactsProject.model_rebuild()
+ProjectArtifactsProjectArtifactType.model_rebuild()
+ProjectArtifactsProjectArtifactTypeArtifactCollection.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/registry_collections.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/registry_collections.py
new file mode 100644
index 0000000000000000000000000000000000000000..f23d185682412c1cfac57c0e2d685c2ed5e42cbf
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/registry_collections.py
@@ -0,0 +1,34 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+from .fragments import RegistryCollectionsPage
+
+
+class RegistryCollections(GQLBase):
+ organization: Optional[RegistryCollectionsOrganization]
+
+
+class RegistryCollectionsOrganization(GQLBase):
+ org_entity: Optional[RegistryCollectionsOrganizationOrgEntity] = Field(
+ alias="orgEntity"
+ )
+
+
+class RegistryCollectionsOrganizationOrgEntity(GQLBase):
+ name: str
+ artifact_collections: Optional[RegistryCollectionsPage] = Field(
+ alias="artifactCollections"
+ )
+
+
+RegistryCollections.model_rebuild()
+RegistryCollectionsOrganization.model_rebuild()
+RegistryCollectionsOrganizationOrgEntity.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/registry_versions.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/registry_versions.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac22e23387ba86f095933c4009dad14bfc920cf4
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/registry_versions.py
@@ -0,0 +1,34 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+from .fragments import RegistryVersionsPage
+
+
+class RegistryVersions(GQLBase):
+ organization: Optional[RegistryVersionsOrganization]
+
+
+class RegistryVersionsOrganization(GQLBase):
+ org_entity: Optional[RegistryVersionsOrganizationOrgEntity] = Field(
+ alias="orgEntity"
+ )
+
+
+class RegistryVersionsOrganizationOrgEntity(GQLBase):
+ name: str
+ artifact_memberships: Optional[RegistryVersionsPage] = Field(
+ alias="artifactMemberships"
+ )
+
+
+RegistryVersions.model_rebuild()
+RegistryVersionsOrganization.model_rebuild()
+RegistryVersionsOrganizationOrgEntity.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/run_input_artifacts.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/run_input_artifacts.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5e4ebe8cb850182b65f730bd616776af417d785
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/run_input_artifacts.py
@@ -0,0 +1,31 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+from .fragments import RunInputArtifactConnectionFragment
+
+
+class RunInputArtifacts(GQLBase):
+ project: Optional[RunInputArtifactsProject]
+
+
+class RunInputArtifactsProject(GQLBase):
+ run: Optional[RunInputArtifactsProjectRun]
+
+
+class RunInputArtifactsProjectRun(GQLBase):
+ input_artifacts: Optional[RunInputArtifactConnectionFragment] = Field(
+ alias="inputArtifacts"
+ )
+
+
+RunInputArtifacts.model_rebuild()
+RunInputArtifactsProject.model_rebuild()
+RunInputArtifactsProjectRun.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/run_output_artifacts.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/run_output_artifacts.py
new file mode 100644
index 0000000000000000000000000000000000000000..f423a77bff357560397d31e1b6b4124f14b4c4f0
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/run_output_artifacts.py
@@ -0,0 +1,31 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+from .fragments import RunOutputArtifactConnectionFragment
+
+
+class RunOutputArtifacts(GQLBase):
+ project: Optional[RunOutputArtifactsProject]
+
+
+class RunOutputArtifactsProject(GQLBase):
+ run: Optional[RunOutputArtifactsProjectRun]
+
+
+class RunOutputArtifactsProjectRun(GQLBase):
+ output_artifacts: Optional[RunOutputArtifactConnectionFragment] = Field(
+ alias="outputArtifacts"
+ )
+
+
+RunOutputArtifacts.model_rebuild()
+RunOutputArtifactsProject.model_rebuild()
+RunOutputArtifactsProjectRun.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/type_info.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/type_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a98543ad1477beee13913f9cc749453f73d42a1
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/type_info.py
@@ -0,0 +1,19 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+from .fragments import TypeInfoFragment
+
+
+class TypeInfo(GQLBase):
+ type: Optional[TypeInfoFragment] = Field(alias="__type")
+
+
+TypeInfo.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/unlink_artifact.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/unlink_artifact.py
new file mode 100644
index 0000000000000000000000000000000000000000..60cff8e6d461fa10fff54e8b5b8ae448f57576d6
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/unlink_artifact.py
@@ -0,0 +1,25 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase, GQLId
+
+
+class UnlinkArtifact(GQLBase):
+ unlink_artifact: Optional[UnlinkArtifactUnlinkArtifact] = Field(
+ alias="unlinkArtifact"
+ )
+
+
+class UnlinkArtifactUnlinkArtifact(GQLBase):
+ artifact_id: GQLId = Field(alias="artifactID")
+ success: bool
+ client_mutation_id: Optional[str] = Field(alias="clientMutationId")
+
+
+UnlinkArtifact.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_artifact.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_artifact.py
new file mode 100644
index 0000000000000000000000000000000000000000..7eaf59e7e9dde4e818449319e77f52912f6d322d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_artifact.py
@@ -0,0 +1,26 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+from .fragments import ArtifactFragment
+
+
+class UpdateArtifact(GQLBase):
+ update_artifact: Optional[UpdateArtifactUpdateArtifact] = Field(
+ alias="updateArtifact"
+ )
+
+
+class UpdateArtifactUpdateArtifact(GQLBase):
+ artifact: ArtifactFragment
+
+
+UpdateArtifact.model_rebuild()
+UpdateArtifactUpdateArtifact.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_artifact_portfolio.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_artifact_portfolio.py
new file mode 100644
index 0000000000000000000000000000000000000000..adae2799116e5adeb32599803680d89d1e8682bd
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_artifact_portfolio.py
@@ -0,0 +1,35 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Literal, Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase, GQLId, Typename
+
+
+class UpdateArtifactPortfolio(GQLBase):
+ update_artifact_portfolio: Optional[
+ UpdateArtifactPortfolioUpdateArtifactPortfolio
+ ] = Field(alias="updateArtifactPortfolio")
+
+
+class UpdateArtifactPortfolioUpdateArtifactPortfolio(GQLBase):
+ artifact_collection: UpdateArtifactPortfolioUpdateArtifactPortfolioArtifactCollection = Field(
+ alias="artifactCollection"
+ )
+
+
+class UpdateArtifactPortfolioUpdateArtifactPortfolioArtifactCollection(GQLBase):
+ typename__: Typename[
+ Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"]
+ ]
+ id: GQLId
+ name: str
+ description: Optional[str]
+
+
+UpdateArtifactPortfolio.model_rebuild()
+UpdateArtifactPortfolioUpdateArtifactPortfolio.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_artifact_sequence.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_artifact_sequence.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e875f1f732a0a33a989701ea0d37fdc43f1f34b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_artifact_sequence.py
@@ -0,0 +1,35 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/artifacts/
+
+from __future__ import annotations
+
+from typing import Literal, Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase, GQLId, Typename
+
+
+class UpdateArtifactSequence(GQLBase):
+ update_artifact_sequence: Optional[UpdateArtifactSequenceUpdateArtifactSequence] = (
+ Field(alias="updateArtifactSequence")
+ )
+
+
+class UpdateArtifactSequenceUpdateArtifactSequence(GQLBase):
+ artifact_collection: UpdateArtifactSequenceUpdateArtifactSequenceArtifactCollection = Field(
+ alias="artifactCollection"
+ )
+
+
+class UpdateArtifactSequenceUpdateArtifactSequenceArtifactCollection(GQLBase):
+ typename__: Typename[
+ Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"]
+ ]
+ id: GQLId
+ name: str
+ description: Optional[str]
+
+
+UpdateArtifactSequence.model_rebuild()
+UpdateArtifactSequenceUpdateArtifactSequence.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_gqlutils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_gqlutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..a735e0f3d11b960a8449d7357a7b46731a17bff8
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_gqlutils.py
@@ -0,0 +1,47 @@
+from __future__ import annotations
+
+from functools import lru_cache
+
+from wandb_gql import Client, gql
+
+from ._generated import TYPE_INFO_GQL, TypeInfo, TypeInfoFragment
+
+OMITTABLE_ARTIFACT_FIELDS = frozenset(
+ {
+ "ttlDurationSeconds",
+ "ttlIsInherited",
+ "aliases",
+ "tags",
+ "historyStep",
+ }
+)
+
+
+@lru_cache(maxsize=16)
+def type_info(client: Client, typename: str) -> TypeInfoFragment | None:
+ """Returns the type info for a given GraphQL type."""
+ data = client.execute(gql(TYPE_INFO_GQL), variable_values={"name": typename})
+ return TypeInfo.model_validate(data).type
+
+
+def supports_enable_tracking_var(client: Client) -> bool:
+ """Returns True if the server supports the `enableTracking` variable for the `Project.artifact(...)` field."""
+ typ = type_info(client, "Project")
+ if (
+ typ
+ and typ.fields
+ and (art_field := next((f for f in typ.fields if f.name == "artifact"), None))
+ ):
+ return any("enableTracking" == arg.name for arg in art_field.args)
+ return False
+
+
+def allowed_fields(client: Client, typename: str) -> set[str]:
+ """Returns the allowed field names for a given GraphQL type."""
+ typ = type_info(client, typename)
+ return {f.name for f in typ.fields} if (typ and typ.fields) else set()
+
+
+def omit_artifact_fields(client: Client) -> set[str]:
+ """Return names of Artifact fields to remove from GraphQL requests (for server compatibility)."""
+ return set(OMITTABLE_ARTIFACT_FIELDS) - allowed_fields(client, "Artifact")
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_internal_artifact.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_internal_artifact.py
new file mode 100644
index 0000000000000000000000000000000000000000..280df6ff0d095bc39924e3f0fe6cd108678647a4
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_internal_artifact.py
@@ -0,0 +1,54 @@
+from __future__ import annotations
+
+import re
+from base64 import urlsafe_b64encode
+from typing import Any, Final
+from zlib import crc32
+
+from wandb.sdk.artifacts.artifact import Artifact
+
+PLACEHOLDER: Final[str] = "PLACEHOLDER"
+
+
+def sanitize_artifact_name(name: str) -> str:
+ """Sanitize the string to satisfy constraints on artifact names."""
+ # If the name is already sanitized, don't change it.
+ if (sanitized := re.sub(r"[^a-zA-Z0-9_\-.]+", "", name)) == name:
+ return name
+
+ # Append a short alphanumeric suffix to maintain uniqueness.
+ # Yes, CRC is meant for checksums and not as a general hash function, but
+ # a 32-bit CRC hash, encoded as (url-safe) base64, is fairly short while
+ # providing 4B+ possible values, which should be good enough for the corner
+ # case names this function is meant to address.
+ #
+ # As implemented, the final suffix should be 6 characters.
+ crc: int = crc32(name.encode("utf-8")) & 0xFFFFFFFF # Ensure it's unsigned
+ crc_bytes = crc.to_bytes(4, byteorder="big")
+ suffix = urlsafe_b64encode(crc_bytes).rstrip(b"=").decode("ascii")
+
+ return f"{sanitized}-{suffix}"
+
+
+class InternalArtifact(Artifact):
+ """InternalArtifact is used to create artifacts that are intended for internal use.
+
+ This includes artifacts of type: `job`, `code`(with `source-` prefix in the collection name),
+ `run_table` (with `run-` prefix in the collection name), and artifacts that start with `wandb-`.
+ Users should not use this class directly.
+ """
+
+ def __init__(
+ self,
+ name: str,
+ type: str,
+ description: str | None = None,
+ metadata: dict[str, Any] | None = None,
+ incremental: bool = False,
+ use_as: str | None = None,
+ ) -> None:
+ sanitized_name = sanitize_artifact_name(name)
+ super().__init__(
+ sanitized_name, PLACEHOLDER, description, metadata, incremental, use_as
+ )
+ self._type = type
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_models/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_models/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..478413a083d609f8ae627554142a73b1d62b9ffc
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_models/__init__.py
@@ -0,0 +1,4 @@
+"""Pydantic model classes and related helpers for artifacts code.
+
+Excludes GraphQL-generated classes.
+"""
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_models/base_model.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_models/base_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8dcbb5038054e6841b13e892072941f3c418ffa
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_models/base_model.py
@@ -0,0 +1,20 @@
+from __future__ import annotations
+
+from abc import ABC
+
+from pydantic import ConfigDict
+
+from wandb._pydantic import JsonableModel
+
+
+# Abstract base class with a common default configuration that's shared by all
+# pydantic classes in artifacts code (excluding GraphQL-generated types).
+class ArtifactsBase(JsonableModel, ABC):
+ # See: https://docs.pydantic.dev/latest/api/config/#pydantic.config.ConfigDict
+ model_config = ConfigDict(
+ # Most likely, some fields won't be pydantic types
+ arbitrary_types_allowed=True,
+ # Assume instances of the same class have already been validated to save time,
+ # but validate subclasses in case they override the default behavior.
+ revalidate_instances="subclass-instances",
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_validators.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_validators.py
new file mode 100644
index 0000000000000000000000000000000000000000..453cd1487cef2d9f6de54c0418a091e79ccf602b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/_validators.py
@@ -0,0 +1,338 @@
+"""Internal validation utilities that are specific to artifacts."""
+
+from __future__ import annotations
+
+import json
+import re
+from dataclasses import dataclass, field, replace
+from functools import wraps
+from typing import TYPE_CHECKING, Any, Callable, Dict, Literal, Optional, TypeVar, cast
+
+from pydantic.dataclasses import dataclass as pydantic_dataclass
+from typing_extensions import Concatenate, ParamSpec, Self
+
+from wandb._iterutils import always_list, unique_list
+from wandb._pydantic import from_json, gql_typename
+from wandb._strutils import nameof, removeprefix
+from wandb.util import json_friendly_val
+
+from ._generated import ArtifactPortfolioTypeFields, ArtifactSequenceTypeFields
+from .exceptions import ArtifactFinalizedError, ArtifactNotLoggedError
+
+if TYPE_CHECKING:
+ from typing import Collection, Final
+
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ArtifactT = TypeVar("ArtifactT", bound="Artifact")
+SelfT = TypeVar("SelfT")
+R = TypeVar("R")
+P = ParamSpec("P")
+
+REGISTRY_PREFIX: Final[str] = "wandb-registry-"
+MAX_ARTIFACT_METADATA_KEYS: Final[int] = 100
+
+ARTIFACT_NAME_MAXLEN: Final[int] = 128
+ARTIFACT_NAME_INVALID_CHARS: Final[frozenset[str]] = frozenset({"/"})
+
+LINKED_ARTIFACT_COLLECTION_TYPE: Final[str] = gql_typename(ArtifactPortfolioTypeFields)
+SOURCE_ARTIFACT_COLLECTION_TYPE: Final[str] = gql_typename(ArtifactSequenceTypeFields)
+
+
+@dataclass
+class _LinkArtifactFields:
+ """Keep this list updated with fields where the linked artifact and the source artifact differ."""
+
+ entity_name: str
+ project_name: str
+ name: str
+ version: str
+ aliases: list[str]
+
+ # These fields shouldn't be set as they should always be
+ # these values for a linked artifact
+ # These fields shouldn't be set by the user as they should always be these values for a linked artifact
+ _is_link: Literal[True] = field(init=False, default=True)
+ _linked_artifacts: list[Artifact] = field(init=False, default_factory=list)
+
+ @property
+ def is_link(self) -> bool:
+ return self._is_link
+
+ @property
+ def linked_artifacts(self) -> list[Artifact]:
+ return self._linked_artifacts
+
+
+def validate_artifact_name(name: str) -> str:
+ """Validate the artifact name, returning it if successful.
+
+ Raises:
+ ValueError: If the artifact name is invalid.
+ """
+ if len(name) > ARTIFACT_NAME_MAXLEN:
+ short_name = f"{name[:ARTIFACT_NAME_MAXLEN]} ..."
+ raise ValueError(
+ f"Artifact name is longer than {ARTIFACT_NAME_MAXLEN} characters: {short_name!r}"
+ )
+
+ if ARTIFACT_NAME_INVALID_CHARS.intersection(name):
+ raise ValueError(
+ "Artifact names must not contain any of the following characters: "
+ f"{', '.join(sorted(ARTIFACT_NAME_INVALID_CHARS))}. Got: {name!r}"
+ )
+
+ return name
+
+
+INVALID_URL_CHARACTERS = ("/", "\\", "#", "?", "%", ":", "\r", "\n")
+
+
+def validate_project_name(name: str) -> None:
+ """Validates a project name according to W&B rules.
+
+ Args:
+ name: The project name string.
+
+ Raises:
+ ValueError: If the name is invalid (too long or contains invalid characters).
+ """
+ max_len = 128
+
+ if not name:
+ raise ValueError("Project name cannot be empty")
+ if not (registry_name := removeprefix(name, REGISTRY_PREFIX)):
+ raise ValueError("Registry name cannot be empty")
+
+ if len(name) > max_len:
+ if registry_name != name:
+ msg = f"Invalid registry name {registry_name!r}, must be {max_len - len(REGISTRY_PREFIX)} characters or less"
+ else:
+ msg = f"Invalid project name {name!r}, must be {max_len} characters or less"
+ raise ValueError(msg)
+
+ # Find the first occurrence of any invalid character
+ if invalid_chars := set(INVALID_URL_CHARACTERS).intersection(name):
+ error_name = registry_name or name
+ invalid_chars_repr = ", ".join(sorted(map(repr, invalid_chars)))
+ raise ValueError(
+ f"Invalid project/registry name {error_name!r}, cannot contain characters: {invalid_chars_repr!s}"
+ )
+
+
+def validate_aliases(aliases: Collection[str] | str) -> list[str]:
+ """Validate the artifact aliases and return them as a list.
+
+ Raises:
+ ValueError: If any of the aliases contain invalid characters.
+ """
+ aliases_list = always_list(aliases)
+
+ invalid_chars = ("/", ":")
+ if any(char in alias for alias in aliases_list for char in invalid_chars):
+ raise ValueError(
+ f"Aliases must not contain any of the following characters: {', '.join(invalid_chars)}"
+ )
+ return aliases_list
+
+
+def validate_artifact_types_list(artifact_types: list[str]) -> list[str]:
+ """Return True if the artifact types list is valid, False otherwise."""
+ artifact_types = always_list(artifact_types)
+ invalid_chars = ("/", ":")
+ if any(
+ char in type or len(type) > 128
+ for type in artifact_types
+ for char in invalid_chars
+ ):
+ raise ValueError(
+ f"""Artifact types must not contain any of the following characters: {", ".join(invalid_chars)}
+ and must be less than equal to 128 characters"""
+ )
+ return artifact_types
+
+
+TAG_REGEX: re.Pattern[str] = re.compile(r"^[-\w]+( +[-\w]+)*$")
+"""Regex pattern for valid tag names."""
+
+
+def validate_tags(tags: Collection[str] | str) -> list[str]:
+ """Validate the artifact tag names and return them as a deduped list.
+
+ In the case of duplicates, only keep the first tag, and otherwise maintain the order of appearance.
+
+ Raises:
+ ValueError: If any of the tags contain invalid characters.
+ """
+ tags_list = unique_list(always_list(tags))
+ if any(not TAG_REGEX.match(tag) for tag in tags_list):
+ raise ValueError(
+ "Invalid tag(s). "
+ "Tags must only contain alphanumeric characters separated by hyphens, underscores, and/or spaces."
+ )
+ return tags_list
+
+
+RESERVED_ARTIFACT_TYPE_PREFIX: Final[str] = "wandb-"
+"""Internal, reserved artifact type prefix."""
+
+RESERVED_ARTIFACT_NAME_PREFIX_BY_TYPE: Final[dict[str, str]] = {
+ "job": "", # Empty prefix means ALL artifact names are reserved for this artifact type
+ "run_table": "run-",
+ "code": "source-",
+}
+"""Lookup of internal, reserved `Artifact.name` prefixes by `Artifact.type`."""
+
+
+def validate_artifact_type(typ: str, name: str) -> str:
+ """Validate the artifact type and return it as a string."""
+ if (
+ # Check if the artifact name is disallowed, based on the artifact type
+ (
+ # This check MUST be against `None`, since "" disallows ALL artifact names
+ (bad_prefix := RESERVED_ARTIFACT_NAME_PREFIX_BY_TYPE.get(typ)) is not None
+ and name.startswith(bad_prefix)
+ )
+ or
+ # Check if the artifact type is disallowed
+ typ.startswith(RESERVED_ARTIFACT_TYPE_PREFIX)
+ ):
+ raise ValueError(
+ f"Artifact type {typ!r} is reserved for internal use. "
+ "Please use a different type."
+ )
+ return typ
+
+
+def validate_metadata(metadata: dict[str, Any] | None) -> dict[str, Any]:
+ """Validate the artifact metadata and return it as a dict."""
+ if metadata is None:
+ return {}
+ if isinstance(metadata, str):
+ return from_json(metadata) if metadata else {}
+ if isinstance(metadata, dict):
+ return cast(Dict[str, Any], json.loads(json.dumps(json_friendly_val(metadata))))
+ raise TypeError(f"metadata must be dict, not {type(metadata)}")
+
+
+def validate_ttl_duration_seconds(gql_ttl_duration_seconds: int | None) -> int | None:
+ """Validate the `ttlDurationSeconds` value (if any) from a GraphQL response."""
+ # If gql_ttl_duration_seconds is not positive, its indicating that TTL is DISABLED(-2)
+ # gql_ttl_duration_seconds only returns None if the server is not compatible with setting Artifact TTLs
+ if gql_ttl_duration_seconds and gql_ttl_duration_seconds > 0:
+ return gql_ttl_duration_seconds
+ return None
+
+
+# ----------------------------------------------------------------------------
+MethodT = Callable[Concatenate[SelfT, P], R]
+"""Generic type hint for an instance method, e.g. for use with decorators."""
+
+
+def ensure_logged(method: MethodT[ArtifactT, P, R]) -> MethodT[ArtifactT, P, R]:
+ """Decorator to ensure that an Artifact method can only be called if the artifact has been logged.
+
+ If the method is called on an artifact that's not logged, `ArtifactNotLoggedError` is raised.
+ """
+ # For clarity, use the qualified (full) name of the method
+ method_fullname = nameof(method)
+
+ @wraps(method)
+ def wrapper(self: ArtifactT, *args: P.args, **kwargs: P.kwargs) -> R:
+ if self.is_draft():
+ raise ArtifactNotLoggedError(fullname=method_fullname, obj=self)
+ return method(self, *args, **kwargs)
+
+ return wrapper
+
+
+def ensure_not_finalized(method: MethodT[ArtifactT, P, R]) -> MethodT[ArtifactT, P, R]:
+ """Decorator to ensure that an `Artifact` method can only be called if the artifact isn't finalized.
+
+ If the method is called on an artifact that's not logged, `ArtifactFinalizedError` is raised.
+ """
+ # For clarity, use the qualified (full) name of the method
+ method_fullname = nameof(method)
+
+ @wraps(method)
+ def wrapper(self: ArtifactT, *args: P.args, **kwargs: P.kwargs) -> R:
+ if self._final:
+ raise ArtifactFinalizedError(fullname=method_fullname, obj=self)
+ return method(self, *args, **kwargs)
+
+ return wrapper
+
+
+def is_artifact_registry_project(project: str) -> bool:
+ return project.startswith(REGISTRY_PREFIX)
+
+
+def remove_registry_prefix(project: str) -> str:
+ if not is_artifact_registry_project(project):
+ raise ValueError(
+ f"Project {project!r} does not have the prefix {REGISTRY_PREFIX}. It is not a registry project"
+ )
+ return removeprefix(project, REGISTRY_PREFIX)
+
+
+@pydantic_dataclass
+class ArtifactPath:
+ name: str
+ """The collection or artifact version name."""
+ project: Optional[str] = None # noqa: UP045
+ """The project name."""
+ prefix: Optional[str] = None # noqa: UP045
+ """Typically the entity or org name."""
+
+ @classmethod
+ def from_str(cls, path: str) -> Self:
+ """Instantiate by parsing a string artifact path.
+
+ Raises:
+ ValueError: If the string is not a valid artifact path.
+ """
+ # Separate the alias first, which may itself contain slashes.
+ # If there's no alias, note that both sep and alias will be empty.
+ collection_path, sep, alias = path.partition(":")
+
+ prefix, project = None, None # defaults, if missing
+ if len(parts := collection_path.split("/")) == 1:
+ name = parts[0]
+ elif len(parts) == 2:
+ project, name = parts
+ elif len(parts) == 3:
+ prefix, project, name = parts
+ else:
+ raise ValueError(f"Invalid artifact path: {path!r}")
+ return cls(prefix=prefix, project=project, name=f"{name}{sep}{alias}")
+
+ def to_str(self) -> str:
+ """Returns the slash-separated string representation of the path."""
+ ordered_parts = (self.prefix, self.project, self.name)
+ return "/".join(part for part in ordered_parts if part)
+
+ def with_defaults(
+ self,
+ *,
+ prefix: str | None = None,
+ project: str | None = None,
+ ) -> Self:
+ """Returns a copy of this path with missing values set to the given defaults."""
+ return replace(
+ self,
+ prefix=self.prefix or prefix,
+ project=self.project or project,
+ )
+
+ def is_registry_path(self) -> bool:
+ """Returns True if this path appears to be a registry path."""
+ return bool((p := self.project) and is_artifact_registry_project(p))
+
+
+@pydantic_dataclass
+class FullArtifactPath(ArtifactPath):
+ """Same as ArtifactPath, but with all parts required."""
+
+ name: str
+ project: str
+ prefix: str
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac6842b6a7485b18902080c1126e65e8d11f9e37
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact.py
@@ -0,0 +1,2683 @@
+"""Artifact class."""
+
+from __future__ import annotations
+
+import atexit
+import contextlib
+import json
+import logging
+import multiprocessing.dummy
+import os
+import re
+import shutil
+import stat
+import tempfile
+import time
+from collections import deque
+from concurrent.futures import Executor, ThreadPoolExecutor, as_completed
+from copy import copy
+from dataclasses import asdict, dataclass, replace
+from datetime import timedelta
+from itertools import filterfalse
+from pathlib import Path, PurePosixPath
+from typing import (
+ IO,
+ TYPE_CHECKING,
+ Any,
+ Final,
+ Iterator,
+ Literal,
+ Sequence,
+ Type,
+ final,
+)
+from urllib.parse import quote, urljoin, urlparse
+
+import requests
+
+import wandb
+from wandb import data_types, env
+from wandb._iterutils import one, unique_list
+from wandb._strutils import nameof
+from wandb.apis.normalize import normalize_exceptions
+from wandb.apis.public import ArtifactCollection, ArtifactFiles, Run
+from wandb.apis.public.utils import gql_compat
+from wandb.data_types import WBValue
+from wandb.errors import CommError
+from wandb.errors.errors import UnsupportedError
+from wandb.errors.term import termerror, termlog, termwarn
+from wandb.proto import wandb_internal_pb2 as pb
+from wandb.proto.wandb_deprecated import Deprecated
+from wandb.sdk import wandb_setup
+from wandb.sdk.artifacts.storage_policies._multipart import should_multipart_download
+from wandb.sdk.data_types._dtypes import Type as WBType
+from wandb.sdk.data_types._dtypes import TypeRegistry
+from wandb.sdk.internal.internal_api import Api as InternalApi
+from wandb.sdk.internal.thread_local_settings import _thread_local_api_settings
+from wandb.sdk.lib import retry, runid, telemetry
+from wandb.sdk.lib.deprecate import deprecate
+from wandb.sdk.lib.filesystem import check_exists, system_preferred_path
+from wandb.sdk.lib.hashutil import B64MD5, b64_to_hex_id, md5_file_b64
+from wandb.sdk.lib.paths import FilePathStr, LogicalPath, StrPath, URIStr
+from wandb.sdk.lib.runid import generate_id
+from wandb.sdk.mailbox import MailboxHandle
+from wandb.util import (
+ alias_is_version_index,
+ artifact_to_json,
+ fsync_open,
+ json_dumps_safer,
+ uri_from_path,
+ vendor_setup,
+)
+
+from ._factories import make_storage_policy
+from ._generated import (
+ ADD_ALIASES_GQL,
+ ARTIFACT_BY_ID_GQL,
+ ARTIFACT_BY_NAME_GQL,
+ ARTIFACT_COLLECTION_MEMBERSHIP_FILE_URLS_GQL,
+ ARTIFACT_CREATED_BY_GQL,
+ ARTIFACT_FILE_URLS_GQL,
+ ARTIFACT_TYPE_GQL,
+ ARTIFACT_USED_BY_GQL,
+ ARTIFACT_VIA_MEMBERSHIP_BY_NAME_GQL,
+ DELETE_ALIASES_GQL,
+ DELETE_ARTIFACT_GQL,
+ FETCH_ARTIFACT_MANIFEST_GQL,
+ FETCH_LINKED_ARTIFACTS_GQL,
+ LINK_ARTIFACT_GQL,
+ UNLINK_ARTIFACT_GQL,
+ UPDATE_ARTIFACT_GQL,
+ ArtifactAliasInput,
+ ArtifactByID,
+ ArtifactByName,
+ ArtifactCollectionAliasInput,
+ ArtifactCollectionMembershipFileUrls,
+ ArtifactCreatedBy,
+ ArtifactFileUrls,
+ ArtifactFragment,
+ ArtifactType,
+ ArtifactUsedBy,
+ ArtifactViaMembershipByName,
+ FetchArtifactManifest,
+ FetchLinkedArtifacts,
+ FileUrlsFragment,
+ LinkArtifact,
+ LinkArtifactInput,
+ MembershipWithArtifact,
+ TagInput,
+ UpdateArtifact,
+)
+from ._gqlutils import omit_artifact_fields, supports_enable_tracking_var, type_info
+from ._validators import (
+ LINKED_ARTIFACT_COLLECTION_TYPE,
+ ArtifactPath,
+ FullArtifactPath,
+ _LinkArtifactFields,
+ ensure_logged,
+ ensure_not_finalized,
+ is_artifact_registry_project,
+ remove_registry_prefix,
+ validate_aliases,
+ validate_artifact_name,
+ validate_artifact_type,
+ validate_metadata,
+ validate_tags,
+ validate_ttl_duration_seconds,
+)
+from .artifact_download_logger import ArtifactDownloadLogger
+from .artifact_instance_cache import artifact_instance_cache
+from .artifact_manifest import ArtifactManifest
+from .artifact_manifest_entry import ArtifactManifestEntry
+from .artifact_manifests.artifact_manifest_v1 import ArtifactManifestV1
+from .artifact_state import ArtifactState
+from .artifact_ttl import ArtifactTTL
+from .exceptions import (
+ ArtifactNotLoggedError,
+ TooFewItemsError,
+ TooManyItemsError,
+ WaitTimeoutError,
+)
+from .staging import get_staging_dir
+from .storage_handlers.gcs_handler import _GCSIsADirectoryError
+
+reset_path = vendor_setup()
+
+from wandb_gql import gql # noqa: E402
+
+reset_path()
+
+if TYPE_CHECKING:
+ from wandb.apis.public import RetryingClient
+
+logger = logging.getLogger(__name__)
+
+
+_MB: Final[int] = 1024 * 1024
+
+
+@final
+@dataclass
+class _DeferredArtifactManifest:
+ """A lightweight wrapper around the manifest URL, used to indicate deferred loading of the actual manifest."""
+
+ url: str
+
+
+class Artifact:
+ """Flexible and lightweight building block for dataset and model versioning.
+
+ Construct an empty W&B Artifact. Populate an artifacts contents with methods that
+ begin with `add`. Once the artifact has all the desired files, you can call
+ `run.log_artifact()` to log it.
+
+ Args:
+ name (str): A human-readable name for the artifact. Use the name to identify
+ a specific artifact in the W&B App UI or programmatically. You can
+ interactively reference an artifact with the `use_artifact` Public API.
+ A name can contain letters, numbers, underscores, hyphens, and dots.
+ The name must be unique across a project.
+ type (str): The artifact's type. Use the type of an artifact to both organize
+ and differentiate artifacts. You can use any string that contains letters,
+ numbers, underscores, hyphens, and dots. Common types include `dataset` or `model`.
+ Include `model` within your type string if you want to link the artifact
+ to the W&B Model Registry. Note that some types reserved for internal use
+ and cannot be set by users. Such types include `job` and types that start with `wandb-`.
+ description (str | None) = None: A description of the artifact. For Model or Dataset Artifacts,
+ add documentation for your standardized team model or dataset card. View
+ an artifact's description programmatically with the `Artifact.description`
+ attribute or programmatically with the W&B App UI. W&B renders the
+ description as markdown in the W&B App.
+ metadata (dict[str, Any] | None) = None: Additional information about an artifact. Specify metadata as a
+ dictionary of key-value pairs. You can specify no more than 100 total keys.
+ incremental: Use `Artifact.new_draft()` method instead to modify an
+ existing artifact.
+ use_as: Deprecated.
+ is_link: Boolean indication of if the artifact is a linked artifact(`True`) or source artifact(`False`).
+
+ Returns:
+ An `Artifact` object.
+ """
+
+ _TMP_DIR = tempfile.TemporaryDirectory("wandb-artifacts")
+ atexit.register(_TMP_DIR.cleanup)
+
+ def __init__(
+ self,
+ name: str,
+ type: str,
+ description: str | None = None,
+ metadata: dict[str, Any] | None = None,
+ incremental: bool = False,
+ use_as: str | None = None,
+ storage_region: str | None = None,
+ ) -> None:
+ if not re.match(r"^[a-zA-Z0-9_\-.]+$", name):
+ raise ValueError(
+ f"Artifact name may only contain alphanumeric characters, dashes, "
+ f"underscores, and dots. Invalid name: {name}"
+ )
+
+ from wandb.sdk.artifacts._internal_artifact import InternalArtifact
+
+ if incremental and not isinstance(self, InternalArtifact):
+ termwarn("Using experimental arg `incremental`")
+
+ # Internal.
+ self._client: RetryingClient | None = None
+
+ self._tmp_dir: tempfile.TemporaryDirectory | None = None
+ self._added_objs: dict[int, tuple[WBValue, ArtifactManifestEntry]] = {}
+ self._added_local_paths: dict[str, ArtifactManifestEntry] = {}
+ self._save_handle: MailboxHandle[pb.Result] | None = None
+ self._download_roots: set[str] = set()
+ # Set by new_draft(), otherwise the latest artifact will be used as the base.
+ self._base_id: str | None = None
+ # Properties.
+ self._id: str | None = None
+ self._client_id: str = runid.generate_id(128)
+ self._sequence_client_id: str = runid.generate_id(128)
+ self._entity: str | None = None
+ self._project: str | None = None
+ self._name: str = validate_artifact_name(name) # includes version after saving
+ self._version: str | None = None
+ self._source_entity: str | None = None
+ self._source_project: str | None = None
+ self._source_name: str = name # includes version after saving
+ self._source_version: str | None = None
+ self._source_artifact: Artifact | None = None
+ self._is_link: bool = False
+ self._type: str = validate_artifact_type(type, name)
+ self._description: str | None = description
+ self._metadata: dict[str, Any] = validate_metadata(metadata)
+ self._ttl_duration_seconds: int | None = None
+ self._ttl_is_inherited: bool = True
+ self._ttl_changed: bool = False
+ self._aliases: list[str] = []
+ self._saved_aliases: list[str] = []
+ self._tags: list[str] = []
+ self._saved_tags: list[str] = []
+ self._distributed_id: str | None = None
+ self._incremental: bool = incremental
+ if use_as is not None:
+ deprecate(
+ field_name=Deprecated.artifact__init_use_as,
+ warning_message=(
+ "`use_as` argument is deprecated and does not affect the behaviour of `wandb.Artifact()`"
+ ),
+ )
+ self._use_as: str | None = None
+ self._state: ArtifactState = ArtifactState.PENDING
+ self._manifest: ArtifactManifest | _DeferredArtifactManifest | None = (
+ ArtifactManifestV1(storage_policy=make_storage_policy(storage_region))
+ )
+ self._commit_hash: str | None = None
+ self._file_count: int | None = None
+ self._created_at: str | None = None
+ self._updated_at: str | None = None
+ self._final: bool = False
+ self._history_step: int | None = None
+ self._linked_artifacts: list[Artifact] = []
+
+ # Cache.
+ artifact_instance_cache[self._client_id] = self
+
+ def __repr__(self) -> str:
+ return f""
+
+ @classmethod
+ def _from_id(cls, artifact_id: str, client: RetryingClient) -> Artifact | None:
+ if cached_artifact := artifact_instance_cache.get(artifact_id):
+ return cached_artifact
+
+ query = gql_compat(ARTIFACT_BY_ID_GQL, omit_fields=omit_artifact_fields(client))
+
+ data = client.execute(query, variable_values={"id": artifact_id})
+ result = ArtifactByID.model_validate(data)
+
+ if (artifact := result.artifact) is None:
+ return None
+
+ src_collection = artifact.artifact_sequence
+ src_project = src_collection.project
+
+ entity_name = src_project.entity_name if src_project else ""
+ project_name = src_project.name if src_project else ""
+
+ name = f"{src_collection.name}:v{artifact.version_index}"
+
+ path = FullArtifactPath(prefix=entity_name, project=project_name, name=name)
+ return cls._from_attrs(path, artifact, client)
+
+ @classmethod
+ def _membership_from_name(
+ cls, *, path: FullArtifactPath, client: RetryingClient
+ ) -> Artifact:
+ if not InternalApi()._server_supports(
+ pb.ServerFeature.PROJECT_ARTIFACT_COLLECTION_MEMBERSHIP
+ ):
+ raise UnsupportedError(
+ "querying for the artifact collection membership is not supported "
+ "by this version of wandb server. Consider updating to the latest version."
+ )
+
+ query = gql_compat(
+ ARTIFACT_VIA_MEMBERSHIP_BY_NAME_GQL,
+ omit_fields=omit_artifact_fields(client),
+ )
+ gql_vars = {
+ "entityName": path.prefix,
+ "projectName": path.project,
+ "name": path.name,
+ }
+ data = client.execute(query, variable_values=gql_vars)
+ result = ArtifactViaMembershipByName.model_validate(data)
+
+ if not (project := result.project):
+ raise ValueError(
+ f"project {path.project!r} not found under entity {path.prefix!r}"
+ )
+ if not (membership := project.artifact_collection_membership):
+ entity_project = f"{path.prefix}/{path.project}"
+ raise ValueError(
+ f"artifact membership {path.name!r} not found in {entity_project!r}"
+ )
+ return cls._from_membership(membership, target=path, client=client)
+
+ @classmethod
+ def _from_name(
+ cls,
+ *,
+ path: FullArtifactPath,
+ client: RetryingClient,
+ enable_tracking: bool = False,
+ ) -> Artifact:
+ if InternalApi()._server_supports(
+ pb.ServerFeature.PROJECT_ARTIFACT_COLLECTION_MEMBERSHIP
+ ):
+ return cls._membership_from_name(path=path, client=client)
+
+ omit_vars = None if supports_enable_tracking_var(client) else {"enableTracking"}
+ gql_vars = {
+ "entityName": path.prefix,
+ "projectName": path.project,
+ "name": path.name,
+ "enableTracking": enable_tracking,
+ }
+ query = gql_compat(
+ ARTIFACT_BY_NAME_GQL,
+ omit_variables=omit_vars,
+ omit_fields=omit_artifact_fields(client),
+ )
+ data = client.execute(query, variable_values=gql_vars)
+ result = ArtifactByName.model_validate(data)
+
+ if not (project := result.project):
+ raise ValueError(
+ f"project {path.project!r} not found under entity {path.prefix!r}"
+ )
+ if not (artifact := project.artifact):
+ entity_project = f"{path.prefix}/{path.project}"
+ raise ValueError(f"artifact {path.name!r} not found in {entity_project!r}")
+
+ return cls._from_attrs(path, artifact, client)
+
+ @classmethod
+ def _from_membership(
+ cls,
+ membership: MembershipWithArtifact,
+ target: FullArtifactPath,
+ client: RetryingClient,
+ ) -> Artifact:
+ if not (
+ (collection := membership.artifact_collection)
+ and (name := collection.name)
+ and (proj := collection.project)
+ ):
+ raise ValueError("Missing artifact collection project in GraphQL response")
+
+ if is_artifact_registry_project(proj.name) and (
+ target.project == "model-registry"
+ ):
+ wandb.termwarn(
+ "This model registry has been migrated and will be discontinued. "
+ f"Your request was redirected to the corresponding artifact {name!r} in the new registry. "
+ f"Please update your paths to point to the migrated registry directly, '{proj.name}/{name}'."
+ )
+ new_target = replace(target, prefix=proj.entity_name, project=proj.name)
+ else:
+ new_target = copy(target)
+
+ if not (artifact := membership.artifact):
+ raise ValueError(f"Artifact {target.to_str()!r} not found in response")
+
+ return cls._from_attrs(new_target, artifact, client)
+
+ @classmethod
+ def _from_attrs(
+ cls,
+ path: FullArtifactPath,
+ attrs: ArtifactFragment,
+ client: RetryingClient,
+ aliases: list[str] | None = None,
+ ) -> Artifact:
+ # Placeholder is required to skip validation.
+ artifact = cls("placeholder", type="placeholder")
+ artifact._client = client
+ artifact._entity = path.prefix
+ artifact._project = path.project
+ artifact._name = path.name
+
+ artifact._assign_attrs(attrs, aliases)
+
+ artifact.finalize()
+
+ # Cache.
+ assert artifact.id is not None
+ artifact_instance_cache[artifact.id] = artifact
+ return artifact
+
+ # TODO: Eventually factor out is_link. Have to currently use it since some forms of fetching the artifact
+ # doesn't make it clear if the artifact is a link or not and have to manually set it.
+ def _assign_attrs(
+ self,
+ art: ArtifactFragment,
+ aliases: list[str] | None = None,
+ is_link: bool | None = None,
+ ) -> None:
+ """Update this Artifact's attributes using the server response."""
+ self._id = art.id
+
+ src_collection = art.artifact_sequence
+ src_project = src_collection.project
+
+ self._source_entity = src_project.entity_name if src_project else ""
+ self._source_project = src_project.name if src_project else ""
+ self._source_name = f"{src_collection.name}:v{art.version_index}"
+ self._source_version = f"v{art.version_index}"
+
+ self._entity = self._entity or self._source_entity
+ self._project = self._project or self._source_project
+ self._name = self._name or self._source_name
+
+ # TODO: Refactor artifact query to fetch artifact via membership instead
+ # and get the collection type
+ if is_link is None:
+ self._is_link = (
+ self._entity != self._source_entity
+ or self._project != self._source_project
+ or self._name.split(":")[0] != self._source_name.split(":")[0]
+ )
+ else:
+ self._is_link = is_link
+
+ self._type = art.artifact_type.name
+ self._description = art.description
+
+ # The future of aliases is to move all alias fetches to the membership level
+ # so we don't have to do the collection fetches below
+ if aliases:
+ processed_aliases = aliases
+ elif art.aliases:
+ entity = self._entity
+ project = self._project
+ collection = self._name.split(":")[0]
+ processed_aliases = [
+ art_alias.alias
+ for art_alias in art.aliases
+ if (
+ (coll := art_alias.artifact_collection)
+ and (proj := coll.project)
+ and proj.entity_name == entity
+ and proj.name == project
+ and coll.name == collection
+ )
+ ]
+ else:
+ processed_aliases = []
+
+ version_aliases = list(filter(alias_is_version_index, processed_aliases))
+ other_aliases = list(filterfalse(alias_is_version_index, processed_aliases))
+
+ try:
+ version = one(
+ version_aliases, too_short=TooFewItemsError, too_long=TooManyItemsError
+ )
+ except TooFewItemsError:
+ version = f"v{art.version_index}" # default to the source version
+ except TooManyItemsError:
+ msg = f"Expected at most one version alias, got {len(version_aliases)}: {version_aliases!r}"
+ raise ValueError(msg) from None
+
+ self._version = version
+ self._name = self._name if (":" in self._name) else f"{self._name}:{version}"
+
+ self._aliases = other_aliases
+ self._saved_aliases = copy(self._aliases)
+
+ self._tags = [tag.name for tag in (art.tags or [])]
+ self._saved_tags = copy(self._tags)
+
+ self._metadata = validate_metadata(art.metadata)
+
+ self._ttl_duration_seconds = validate_ttl_duration_seconds(
+ art.ttl_duration_seconds
+ )
+ self._ttl_is_inherited = (
+ True if (art.ttl_is_inherited is None) else art.ttl_is_inherited
+ )
+
+ self._state = ArtifactState(art.state)
+
+ self._manifest = (
+ _DeferredArtifactManifest(manifest.file.direct_url)
+ if (manifest := art.current_manifest)
+ else None
+ )
+
+ self._commit_hash = art.commit_hash
+ self._file_count = art.file_count
+ self._created_at = art.created_at
+ self._updated_at = art.updated_at
+ self._history_step = art.history_step
+
+ @ensure_logged
+ def new_draft(self) -> Artifact:
+ """Create a new draft artifact with the same content as this committed artifact.
+
+ Modifying an existing artifact creates a new artifact version known
+ as an "incremental artifact". The artifact returned can be extended or
+ modified and logged as a new version.
+
+ Returns:
+ An `Artifact` object.
+
+ Raises:
+ ArtifactNotLoggedError: If the artifact is not logged.
+ """
+ # Name, _entity and _project are set to the *source* name/entity/project:
+ # if this artifact is saved it must be saved to the source sequence.
+ artifact = Artifact(self.source_name.split(":")[0], self.type)
+ artifact._entity = self._source_entity
+ artifact._project = self._source_project
+ artifact._source_entity = self._source_entity
+ artifact._source_project = self._source_project
+
+ # This artifact's parent is the one we are making a draft from.
+ artifact._base_id = self.id
+
+ # We can reuse the client, and copy over all the attributes that aren't
+ # version-dependent and don't depend on having been logged.
+ artifact._client = self._client
+ artifact._description = self.description
+ artifact._metadata = self.metadata
+ artifact._manifest = ArtifactManifest.from_manifest_json(
+ self.manifest.to_manifest_json()
+ )
+ return artifact
+
+ # Properties (Python Class managed attributes).
+
+ @property
+ def id(self) -> str | None:
+ """The artifact's ID."""
+ if self.is_draft():
+ return None
+ assert self._id is not None
+ return self._id
+
+ @property
+ @ensure_logged
+ def entity(self) -> str:
+ """The name of the entity that the artifact collection belongs to.
+
+ If the artifact is a link, the entity will be the entity of the linked artifact.
+ """
+ assert self._entity is not None
+ return self._entity
+
+ @property
+ @ensure_logged
+ def project(self) -> str:
+ """The name of the project that the artifact collection belongs to.
+
+ If the artifact is a link, the project will be the project of the linked artifact.
+ """
+ assert self._project is not None
+ return self._project
+
+ @property
+ def name(self) -> str:
+ """The artifact name and version of the artifact.
+
+ A string with the format `{collection}:{alias}`. If fetched before an artifact is logged/saved, the name won't contain the alias.
+ If the artifact is a link, the name will be the name of the linked artifact.
+ """
+ return self._name
+
+ @property
+ def qualified_name(self) -> str:
+ """The entity/project/name of the artifact.
+
+ If the artifact is a link, the qualified name will be the qualified name of the linked artifact path.
+ """
+ return f"{self.entity}/{self.project}/{self.name}"
+
+ @property
+ @ensure_logged
+ def version(self) -> str:
+ """The artifact's version.
+
+ A string with the format `v{number}`.
+ If the artifact is a link artifact, the version will be from the linked collection.
+ """
+ assert self._version is not None
+ return self._version
+
+ @property
+ @ensure_logged
+ def collection(self) -> ArtifactCollection:
+ """The collection this artifact was retrieved from.
+
+ A collection is an ordered group of artifact versions.
+ If this artifact was retrieved from a portfolio / linked collection, that
+ collection will be returned rather than the collection
+ that an artifact version originated from. The collection
+ that an artifact originates from is known as the source sequence.
+ """
+ base_name = self.name.split(":")[0]
+ return ArtifactCollection(
+ self._client, self.entity, self.project, base_name, self.type
+ )
+
+ @property
+ @ensure_logged
+ def source_entity(self) -> str:
+ """The name of the entity of the source artifact."""
+ assert self._source_entity is not None
+ return self._source_entity
+
+ @property
+ @ensure_logged
+ def source_project(self) -> str:
+ """The name of the project of the source artifact."""
+ assert self._source_project is not None
+ return self._source_project
+
+ @property
+ def source_name(self) -> str:
+ """The artifact name and version of the source artifact.
+
+ A string with the format `{source_collection}:{alias}`. Before the artifact is saved,
+ contains only the name since the version is not yet known.
+ """
+ return self._source_name
+
+ @property
+ def source_qualified_name(self) -> str:
+ """The source_entity/source_project/source_name of the source artifact."""
+ return f"{self.source_entity}/{self.source_project}/{self.source_name}"
+
+ @property
+ @ensure_logged
+ def source_version(self) -> str:
+ """The source artifact's version.
+
+ A string with the format `v{number}`.
+ """
+ assert self._source_version is not None
+ return self._source_version
+
+ @property
+ @ensure_logged
+ def source_collection(self) -> ArtifactCollection:
+ """The artifact's source collection.
+
+ The source collection is the collection that the artifact was logged from.
+ """
+ base_name = self.source_name.split(":")[0]
+ return ArtifactCollection(
+ self._client, self.source_entity, self.source_project, base_name, self.type
+ )
+
+ @property
+ def is_link(self) -> bool:
+ """Boolean flag indicating if the artifact is a link artifact.
+
+ True: The artifact is a link artifact to a source artifact.
+ False: The artifact is a source artifact.
+ """
+ return self._is_link
+
+ @property
+ @ensure_logged
+ def linked_artifacts(self) -> list[Artifact]:
+ """Returns a list of all the linked artifacts of a source artifact.
+
+ If the artifact is a link artifact (`artifact.is_link == True`), it will return an empty list.
+ Limited to 500 results."""
+ if not self.is_link:
+ self._linked_artifacts = self._fetch_linked_artifacts()
+ return self._linked_artifacts
+
+ @property
+ @ensure_logged
+ def source_artifact(self) -> Artifact:
+ """Returns the source artifact. The source artifact is the original logged artifact.
+
+ If the artifact itself is a source artifact (`artifact.is_link == False`), it will return itself."""
+ if not self.is_link:
+ return self
+ if self._source_artifact is None:
+ if self._client is None:
+ raise ValueError("Client is not initialized")
+
+ try:
+ path = FullArtifactPath(
+ prefix=self.source_entity,
+ project=self.source_project,
+ name=self.source_name,
+ )
+ self._source_artifact = self._from_name(path=path, client=self._client)
+ except Exception as e:
+ raise ValueError(
+ f"Unable to fetch source artifact for linked artifact {self.name}"
+ ) from e
+ return self._source_artifact
+
+ @property
+ def type(self) -> str:
+ """The artifact's type. Common types include `dataset` or `model`."""
+ return self._type
+
+ @property
+ @ensure_logged
+ def url(self) -> str:
+ """
+ Constructs the URL of the artifact.
+
+ Returns:
+ str: The URL of the artifact.
+ """
+ try:
+ base_url = self._client.app_url # type: ignore[union-attr]
+ except AttributeError:
+ return ""
+
+ if not self.is_link:
+ return self._construct_standard_url(base_url)
+ if is_artifact_registry_project(self.project):
+ return self._construct_registry_url(base_url)
+ if self._type == "model" or self.project == "model-registry":
+ return self._construct_model_registry_url(base_url)
+ return self._construct_standard_url(base_url)
+
+ def _construct_standard_url(self, base_url: str) -> str:
+ if not all(
+ [
+ base_url,
+ self.entity,
+ self.project,
+ self._type,
+ self.collection.name,
+ self._version,
+ ]
+ ):
+ return ""
+ return urljoin(
+ base_url,
+ f"{self.entity}/{self.project}/artifacts/{quote(self._type)}/{quote(self.collection.name)}/{self._version}",
+ )
+
+ def _construct_registry_url(self, base_url: str) -> str:
+ if not all(
+ [
+ base_url,
+ self.entity,
+ self.project,
+ self.collection.name,
+ self._version,
+ ]
+ ):
+ return ""
+
+ try:
+ org, *_ = InternalApi()._fetch_orgs_and_org_entities_from_entity(
+ self.entity
+ )
+ except ValueError:
+ return ""
+
+ selection_path = quote(
+ f"{self.entity}/{self.project}/{self.collection.name}", safe=""
+ )
+ return urljoin(
+ base_url,
+ f"orgs/{org.display_name}/registry/{remove_registry_prefix(self.project)}?selectionPath={selection_path}&view=membership&version={self.version}",
+ )
+
+ def _construct_model_registry_url(self, base_url: str) -> str:
+ if not all(
+ [
+ base_url,
+ self.entity,
+ self.project,
+ self.collection.name,
+ self._version,
+ ]
+ ):
+ return ""
+ selection_path = quote(
+ f"{self.entity}/{self.project}/{self.collection.name}", safe=""
+ )
+ return urljoin(
+ base_url,
+ f"{self.entity}/registry/model?selectionPath={selection_path}&view=membership&version={self._version}",
+ )
+
+ @property
+ def description(self) -> str | None:
+ """A description of the artifact."""
+ return self._description
+
+ @description.setter
+ def description(self, description: str | None) -> None:
+ """Set the description of the artifact.
+
+ For model or dataset Artifacts, add documentation for your
+ standardized team model or dataset card. In the W&B UI the
+ description is rendered as markdown.
+
+ Editing the description will apply the changes to the source artifact and all linked artifacts associated with it.
+
+ Args:
+ description: Free text that offers a description of the artifact.
+ """
+ if self.is_link:
+ wandb.termwarn(
+ "Editing the description of this linked artifact will edit the description for the source artifact and it's linked artifacts as well."
+ )
+ self._description = description
+
+ @property
+ def metadata(self) -> dict:
+ """User-defined artifact metadata.
+
+ Structured data associated with the artifact.
+ """
+ return self._metadata
+
+ @metadata.setter
+ def metadata(self, metadata: dict) -> None:
+ """User-defined artifact metadata.
+
+ Metadata set this way will eventually be queryable and plottable in the UI; e.g.
+ the class distribution of a dataset.
+
+ Note: There is currently a limit of 100 total keys.
+ Editing the metadata will apply the changes to the source artifact and all linked artifacts associated with it.
+
+ Args:
+ metadata: Structured data associated with the artifact.
+ """
+ if self.is_link:
+ wandb.termwarn(
+ "Editing the metadata of this linked artifact will edit the metadata for the source artifact and it's linked artifacts as well."
+ )
+ self._metadata = validate_metadata(metadata)
+
+ @property
+ def ttl(self) -> timedelta | None:
+ """The time-to-live (TTL) policy of an artifact.
+
+ Artifacts are deleted shortly after a TTL policy's duration passes.
+ If set to `None`, the artifact deactivates TTL policies and will be not
+ scheduled for deletion, even if there is a team default TTL.
+ An artifact inherits a TTL policy from
+ the team default if the team administrator defines a default
+ TTL and there is no custom policy set on an artifact.
+
+ Raises:
+ ArtifactNotLoggedError: Unable to fetch inherited TTL if the
+ artifact has not been logged or saved.
+ """
+ if self._ttl_is_inherited and (self.is_draft() or self._ttl_changed):
+ raise ArtifactNotLoggedError(f"{nameof(type(self))}.ttl", self)
+ if self._ttl_duration_seconds is None:
+ return None
+ return timedelta(seconds=self._ttl_duration_seconds)
+
+ @ttl.setter
+ def ttl(self, ttl: timedelta | ArtifactTTL | None) -> None:
+ """The time-to-live (TTL) policy of an artifact.
+
+ Artifacts are deleted shortly after a TTL policy's duration passes.
+ If set to `None`, the artifact has no TTL policy set and it is not
+ scheduled for deletion. An artifact inherits a TTL policy from
+ the team default if the team administrator defines a default
+ TTL and there is no custom policy set on an artifact.
+
+ Args:
+ ttl: The duration as a positive Python `datetime.timedelta` Type
+ that represents how long the artifact will remain active from its creation.
+
+ """
+ if self.type == "wandb-history":
+ raise ValueError("Cannot set artifact TTL for type wandb-history")
+
+ if self.is_link:
+ raise ValueError(
+ "Cannot set TTL for link artifact. "
+ "Unlink the artifact first then set the TTL for the source artifact"
+ )
+
+ self._ttl_changed = True
+ if isinstance(ttl, ArtifactTTL):
+ if ttl == ArtifactTTL.INHERIT:
+ self._ttl_is_inherited = True
+ else:
+ raise ValueError(f"Unhandled ArtifactTTL enum {ttl}")
+ else:
+ self._ttl_is_inherited = False
+ if ttl is None:
+ self._ttl_duration_seconds = None
+ else:
+ if ttl.total_seconds() <= 0:
+ raise ValueError(
+ f"Artifact TTL Duration has to be positive. ttl: {ttl.total_seconds()}"
+ )
+ self._ttl_duration_seconds = int(ttl.total_seconds())
+
+ @property
+ @ensure_logged
+ def aliases(self) -> list[str]:
+ """List of one or more semantically-friendly references or
+
+ identifying "nicknames" assigned to an artifact version.
+
+ Aliases are mutable references that you can programmatically reference.
+ Change an artifact's alias with the W&B App UI or programmatically.
+ See [Create new artifact versions](https://docs.wandb.ai/guides/artifacts/create-a-new-artifact-version)
+ for more information.
+ """
+ return self._aliases
+
+ @aliases.setter
+ @ensure_logged
+ def aliases(self, aliases: list[str]) -> None:
+ """Set the aliases associated with this artifact."""
+ self._aliases = validate_aliases(aliases)
+
+ @property
+ @ensure_logged
+ def tags(self) -> list[str]:
+ """List of one or more tags assigned to this artifact version."""
+ return self._tags
+
+ @tags.setter
+ @ensure_logged
+ def tags(self, tags: list[str]) -> None:
+ """Set the tags associated with this artifact.
+
+ Editing tags will apply the changes to the source artifact and all linked artifacts associated with it.
+ """
+ if self.is_link:
+ wandb.termwarn(
+ "Editing tags will apply the changes to the source artifact and all linked artifacts associated with it."
+ )
+ self._tags = validate_tags(tags)
+
+ @property
+ def distributed_id(self) -> str | None:
+ """The distributed ID of the artifact.
+
+
+ """
+ return self._distributed_id
+
+ @distributed_id.setter
+ def distributed_id(self, distributed_id: str | None) -> None:
+ self._distributed_id = distributed_id
+
+ @property
+ def incremental(self) -> bool:
+ """Boolean flag indicating if the artifact is an incremental artifact.
+
+
+ """
+ return self._incremental
+
+ @property
+ def use_as(self) -> str | None:
+ """Deprecated."""
+ deprecate(
+ field_name=Deprecated.artifact__use_as,
+ warning_message=("The use_as property of Artifact is deprecated."),
+ )
+ return self._use_as
+
+ @property
+ def state(self) -> str:
+ """The status of the artifact. One of: "PENDING", "COMMITTED", or "DELETED"."""
+ return self._state.value
+
+ @property
+ def manifest(self) -> ArtifactManifest:
+ """The artifact's manifest.
+
+ The manifest lists all of its contents, and can't be changed once the artifact
+ has been logged.
+ """
+ if isinstance(self._manifest, _DeferredArtifactManifest):
+ # A deferred manifest URL flags a deferred download request,
+ # so fetch the manifest to override the placeholder object
+ self._manifest = self._load_manifest(self._manifest.url)
+ return self._manifest
+
+ if self._manifest is None:
+ if self._client is None:
+ raise RuntimeError("Client not initialized for artifact queries")
+
+ query = gql(FETCH_ARTIFACT_MANIFEST_GQL)
+ gql_vars = {
+ "entityName": self.entity,
+ "projectName": self.project,
+ "name": self.name,
+ }
+ data = self._client.execute(query, variable_values=gql_vars)
+ result = FetchArtifactManifest.model_validate(data)
+ if not (
+ (project := result.project)
+ and (artifact := project.artifact)
+ and (manifest := artifact.current_manifest)
+ ):
+ raise ValueError("Failed to fetch artifact manifest")
+ self._manifest = self._load_manifest(manifest.file.direct_url)
+
+ return self._manifest
+
+ @property
+ def digest(self) -> str:
+ """The logical digest of the artifact.
+
+ The digest is the checksum of the artifact's contents. If an artifact has the
+ same digest as the current `latest` version, then `log_artifact` is a no-op.
+ """
+ return self.manifest.digest()
+
+ @property
+ def size(self) -> int:
+ """The total size of the artifact in bytes.
+
+ Includes any references tracked by this artifact.
+ """
+ return sum(entry.size for entry in self.manifest.entries.values() if entry.size)
+
+ @property
+ @ensure_logged
+ def commit_hash(self) -> str:
+ """The hash returned when this artifact was committed."""
+ assert self._commit_hash is not None
+ return self._commit_hash
+
+ @property
+ @ensure_logged
+ def file_count(self) -> int:
+ """The number of files (including references)."""
+ assert self._file_count is not None
+ return self._file_count
+
+ @property
+ @ensure_logged
+ def created_at(self) -> str:
+ """Timestamp when the artifact was created."""
+ assert self._created_at is not None
+ return self._created_at
+
+ @property
+ @ensure_logged
+ def updated_at(self) -> str:
+ """The time when the artifact was last updated."""
+ assert self._created_at is not None
+ return self._updated_at or self._created_at
+
+ @property
+ @ensure_logged
+ def history_step(self) -> int | None:
+ """The nearest step at which history metrics were logged for the source run of the artifact.
+
+ Examples:
+ ```python
+ run = artifact.logged_by()
+ if run and (artifact.history_step is not None):
+ history = run.sample_history(
+ min_step=artifact.history_step,
+ max_step=artifact.history_step + 1,
+ keys=["my_metric"],
+ )
+ ```
+ """
+ if self._history_step is None:
+ return None
+ return max(0, self._history_step - 1)
+
+ # State management.
+
+ def finalize(self) -> None:
+ """Finalize the artifact version.
+
+ You cannot modify an artifact version once it is finalized because the artifact
+ is logged as a specific artifact version. Create a new artifact version
+ to log more data to an artifact. An artifact is automatically finalized
+ when you log the artifact with `log_artifact`.
+ """
+ self._final = True
+
+ def is_draft(self) -> bool:
+ """Check if artifact is not saved.
+
+ Returns:
+ Boolean. `False` if artifact is saved. `True` if artifact is not saved.
+ """
+ return self._state is ArtifactState.PENDING
+
+ def _is_draft_save_started(self) -> bool:
+ return self._save_handle is not None
+
+ def save(
+ self,
+ project: str | None = None,
+ settings: wandb.Settings | None = None,
+ ) -> None:
+ """Persist any changes made to the artifact.
+
+ If currently in a run, that run will log this artifact. If not currently in a
+ run, a run of type "auto" is created to track this artifact.
+
+ Args:
+ project: A project to use for the artifact in the case that a run is not
+ already in context.
+ settings: A settings object to use when initializing an automatic run. Most
+ commonly used in testing harness.
+ """
+ if self._state is not ArtifactState.PENDING:
+ return self._update()
+
+ if self._incremental:
+ with telemetry.context() as tel:
+ tel.feature.artifact_incremental = True
+
+ if run := wandb_setup.singleton().most_recent_active_run:
+ # TODO: Deprecate and encourage explicit log_artifact().
+ run.log_artifact(self)
+ else:
+ if settings is None:
+ settings = wandb.Settings(silent="true")
+ with wandb.init( # type: ignore
+ entity=self._source_entity,
+ project=project or self._source_project,
+ job_type="auto",
+ settings=settings,
+ ) as run:
+ # redoing this here because in this branch we know we didn't
+ # have the run at the beginning of the method
+ if self._incremental:
+ with telemetry.context(run=run) as tel:
+ tel.feature.artifact_incremental = True
+ run.log_artifact(self)
+
+ def _set_save_handle(
+ self,
+ save_handle: MailboxHandle[pb.Result],
+ client: RetryingClient,
+ ) -> None:
+ self._save_handle = save_handle
+ self._client = client
+
+ def wait(self, timeout: int | None = None) -> Artifact:
+ """If needed, wait for this artifact to finish logging.
+
+ Args:
+ timeout: The time, in seconds, to wait.
+
+ Returns:
+ An `Artifact` object.
+ """
+ if self.is_draft():
+ if self._save_handle is None:
+ raise ArtifactNotLoggedError(nameof(self.wait), self)
+
+ try:
+ result = self._save_handle.wait_or(timeout=timeout)
+ except TimeoutError as e:
+ raise WaitTimeoutError(
+ "Artifact upload wait timed out, failed to fetch Artifact response"
+ ) from e
+
+ response = result.response.log_artifact_response
+ if response.error_message:
+ raise ValueError(response.error_message)
+ self._populate_after_save(response.artifact_id)
+ return self
+
+ def _populate_after_save(self, artifact_id: str) -> None:
+ assert self._client is not None
+
+ query = gql_compat(
+ ARTIFACT_BY_ID_GQL, omit_fields=omit_artifact_fields(self._client)
+ )
+ data = self._client.execute(query, variable_values={"id": artifact_id})
+ result = ArtifactByID.model_validate(data)
+
+ if not (artifact := result.artifact):
+ raise ValueError(f"Unable to fetch artifact with id: {artifact_id!r}")
+
+ # _populate_after_save is only called on source artifacts, not linked artifacts
+ # We have to manually set is_link because we aren't fetching the collection the artifact.
+ # That requires greater refactoring for commitArtifact to return the artifact collection type.
+ self._assign_attrs(artifact, is_link=False)
+
+ @normalize_exceptions
+ def _update(self) -> None:
+ """Persists artifact changes to the wandb backend."""
+ if self._client is None:
+ raise RuntimeError("Client not initialized for artifact mutations")
+
+ entity = self.entity
+ project = self.project
+ collection = self.name.split(":")[0]
+
+ aliases = None
+
+ if type_info(self._client, "AddAliasesInput") is not None:
+ # wandb backend version >= 0.13.0
+ alias_props = {
+ "entity_name": entity,
+ "project_name": project,
+ "artifact_collection_name": collection,
+ }
+ if aliases_to_add := (set(self.aliases) - set(self._saved_aliases)):
+ add_mutation = gql(ADD_ALIASES_GQL)
+ add_alias_inputs = [
+ ArtifactCollectionAliasInput(**alias_props, alias=alias)
+ for alias in aliases_to_add
+ ]
+ try:
+ self._client.execute(
+ add_mutation,
+ variable_values={
+ "artifactID": self.id,
+ "aliases": [a.model_dump() for a in add_alias_inputs],
+ },
+ )
+ except CommError as e:
+ raise CommError(
+ "You do not have permission to add"
+ f" {'at least one of the following aliases' if len(aliases_to_add) > 1 else 'the following alias'}"
+ f" to this artifact: {aliases_to_add}"
+ ) from e
+
+ if aliases_to_delete := (set(self._saved_aliases) - set(self.aliases)):
+ delete_mutation = gql(DELETE_ALIASES_GQL)
+ delete_alias_inputs = [
+ ArtifactCollectionAliasInput(**alias_props, alias=alias)
+ for alias in aliases_to_delete
+ ]
+ try:
+ self._client.execute(
+ delete_mutation,
+ variable_values={
+ "artifactID": self.id,
+ "aliases": [a.model_dump() for a in delete_alias_inputs],
+ },
+ )
+ except CommError as e:
+ raise CommError(
+ f"You do not have permission to delete"
+ f" {'at least one of the following aliases' if len(aliases_to_delete) > 1 else 'the following alias'}"
+ f" from this artifact: {aliases_to_delete}"
+ ) from e
+
+ self._saved_aliases = copy(self.aliases)
+
+ else: # wandb backend version < 0.13.0
+ aliases = [
+ ArtifactAliasInput(
+ artifact_collection_name=collection, alias=alias
+ ).model_dump()
+ for alias in self.aliases
+ ]
+
+ omit_fields = omit_artifact_fields(self._client)
+ omit_variables = set()
+
+ if {"ttlIsInherited", "ttlDurationSeconds"} & omit_fields:
+ if self._ttl_changed:
+ termwarn(
+ "Server not compatible with setting Artifact TTLs, please upgrade the server to use Artifact TTL"
+ )
+
+ omit_variables |= {"ttlDurationSeconds"}
+
+ tags_to_add = validate_tags(set(self.tags) - set(self._saved_tags))
+ tags_to_del = validate_tags(set(self._saved_tags) - set(self.tags))
+
+ if {"tags"} & omit_fields:
+ if tags_to_add or tags_to_del:
+ termwarn(
+ "Server not compatible with Artifact tags. "
+ "To use Artifact tags, please upgrade the server to v0.85 or higher."
+ )
+
+ omit_variables |= {"tagsToAdd", "tagsToDelete"}
+
+ mutation = gql_compat(
+ UPDATE_ARTIFACT_GQL,
+ omit_variables=omit_variables,
+ omit_fields=omit_fields,
+ )
+
+ gql_vars = {
+ "artifactID": self.id,
+ "description": self.description,
+ "metadata": json_dumps_safer(self.metadata),
+ "ttlDurationSeconds": self._ttl_duration_seconds_to_gql(),
+ "aliases": aliases,
+ "tagsToAdd": [TagInput(tag_name=t).model_dump() for t in tags_to_add],
+ "tagsToDelete": [TagInput(tag_name=t).model_dump() for t in tags_to_del],
+ }
+
+ data = self._client.execute(mutation, variable_values=gql_vars)
+
+ result = UpdateArtifact.model_validate(data).update_artifact
+ if not (result and (artifact := result.artifact)):
+ raise ValueError("Unable to parse updateArtifact response")
+ self._assign_attrs(artifact)
+
+ self._ttl_changed = False # Reset after updating artifact
+
+ # Adding, removing, getting entries.
+
+ def __getitem__(self, name: str) -> WBValue | None:
+ """Get the WBValue object located at the artifact relative `name`.
+
+ Args:
+ name: The artifact relative name to get.
+
+ Returns:
+ W&B object that can be logged with `run.log()` and visualized in the W&B UI.
+
+ Raises:
+ ArtifactNotLoggedError: If the artifact isn't logged or the run is offline.
+ """
+ return self.get(name)
+
+ def __setitem__(self, name: str, item: WBValue) -> ArtifactManifestEntry:
+ """Add `item` to the artifact at path `name`.
+
+ Args:
+ name: The path within the artifact to add the object.
+ item: The object to add.
+
+ Returns:
+ The added manifest entry
+
+ Raises:
+ ArtifactFinalizedError: You cannot make changes to the current
+ artifact version because it is finalized. Log a new artifact
+ version instead.
+ """
+ return self.add(item, name)
+
+ @contextlib.contextmanager
+ @ensure_not_finalized
+ def new_file(
+ self, name: str, mode: str = "x", encoding: str | None = None
+ ) -> Iterator[IO]:
+ """Open a new temporary file and add it to the artifact.
+
+ Args:
+ name: The name of the new file to add to the artifact.
+ mode: The file access mode to use to open the new file.
+ encoding: The encoding used to open the new file.
+
+ Returns:
+ A new file object that can be written to. Upon closing, the file
+ is automatically added to the artifact.
+
+ Raises:
+ ArtifactFinalizedError: You cannot make changes to the current
+ artifact version because it is finalized. Log a new artifact
+ version instead.
+ """
+ overwrite: bool = "x" not in mode
+
+ if self._tmp_dir is None:
+ self._tmp_dir = tempfile.TemporaryDirectory()
+ path = os.path.join(self._tmp_dir.name, name.lstrip("/"))
+
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
+ try:
+ with fsync_open(path, mode, encoding) as f:
+ yield f
+ except FileExistsError:
+ raise ValueError(f"File with name {name!r} already exists at {path!r}")
+ except UnicodeEncodeError as e:
+ termerror(
+ f"Failed to open the provided file ({nameof(type(e))}: {e}). Please "
+ f"provide the proper encoding."
+ )
+ raise
+
+ self.add_file(
+ path, name=name, policy="immutable", skip_cache=True, overwrite=overwrite
+ )
+
+ @ensure_not_finalized
+ def add_file(
+ self,
+ local_path: str,
+ name: str | None = None,
+ is_tmp: bool | None = False,
+ skip_cache: bool | None = False,
+ policy: Literal["mutable", "immutable"] | None = "mutable",
+ overwrite: bool = False,
+ ) -> ArtifactManifestEntry:
+ """Add a local file to the artifact.
+
+ Args:
+ local_path: The path to the file being added.
+ name: The path within the artifact to use for the file being added.
+ Defaults to the basename of the file.
+ is_tmp: If true, then the file is renamed deterministically to avoid
+ collisions.
+ skip_cache: If `True`, do not copy files to the cache
+ after uploading.
+ policy: By default, set to "mutable". If set to "mutable",
+ create a temporary copy of the file to prevent corruption
+ during upload. If set to "immutable", disable
+ protection and rely on the user not to delete or change the
+ file.
+ overwrite: If `True`, overwrite the file if it already exists.
+
+ Returns:
+ The added manifest entry.
+
+ Raises:
+ ArtifactFinalizedError: You cannot make changes to the current
+ artifact version because it is finalized. Log a new artifact
+ version instead.
+ ValueError: Policy must be "mutable" or "immutable"
+ """
+ if not os.path.isfile(local_path):
+ raise ValueError(f"Path is not a file: {local_path!r}")
+
+ name = LogicalPath(name or os.path.basename(local_path))
+ digest = md5_file_b64(local_path)
+
+ if is_tmp:
+ file_path, file_name = os.path.split(name)
+ file_name_parts = file_name.split(".")
+ file_name_parts[0] = b64_to_hex_id(digest)[:20]
+ name = os.path.join(file_path, ".".join(file_name_parts))
+
+ return self._add_local_file(
+ name,
+ local_path,
+ digest=digest,
+ skip_cache=skip_cache,
+ policy=policy,
+ overwrite=overwrite,
+ )
+
+ @ensure_not_finalized
+ def add_dir(
+ self,
+ local_path: str,
+ name: str | None = None,
+ skip_cache: bool | None = False,
+ policy: Literal["mutable", "immutable"] | None = "mutable",
+ merge: bool = False,
+ ) -> None:
+ """Add a local directory to the artifact.
+
+ Args:
+ local_path: The path of the local directory.
+ name: The subdirectory name within an artifact. The name you
+ specify appears in the W&B App UI nested by artifact's `type`.
+ Defaults to the root of the artifact.
+ skip_cache: If set to `True`, W&B will not copy/move files to
+ the cache while uploading
+ policy: By default, "mutable".
+ - mutable: Create a temporary copy of the file to prevent corruption during upload.
+ - immutable: Disable protection, rely on the user not to delete or change the file.
+ merge: If `False` (default), throws ValueError if a file was already added in a previous add_dir call
+ and its content has changed. If `True`, overwrites existing files with changed content.
+ Always adds new files and never removes files. To replace an entire directory, pass a name when adding the directory
+ using `add_dir(local_path, name=my_prefix)` and call `remove(my_prefix)` to remove the directory, then add it again.
+
+ Raises:
+ ArtifactFinalizedError: You cannot make changes to the current
+ artifact version because it is finalized. Log a new artifact
+ version instead.
+ ValueError: Policy must be "mutable" or "immutable"
+ """
+ if not os.path.isdir(local_path):
+ raise ValueError(f"Path is not a directory: {local_path!r}")
+
+ termlog(
+ f"Adding directory to artifact ({Path('.', local_path)})... ",
+ newline=False,
+ )
+ start_time = time.monotonic()
+
+ paths: deque[tuple[str, str]] = deque()
+ logical_root = name or "" # shared prefix, if any, for logical paths
+ for dirpath, _, filenames in os.walk(local_path, followlinks=True):
+ for fname in filenames:
+ physical_path = os.path.join(dirpath, fname)
+ logical_path = os.path.relpath(physical_path, start=local_path)
+ logical_path = os.path.join(logical_root, logical_path)
+ paths.append((logical_path, physical_path))
+
+ def add_manifest_file(logical_pth: str, physical_pth: str) -> None:
+ self._add_local_file(
+ name=logical_pth,
+ path=physical_pth,
+ skip_cache=skip_cache,
+ policy=policy,
+ overwrite=merge,
+ )
+
+ num_threads = 8
+ pool = multiprocessing.dummy.Pool(num_threads)
+ pool.starmap(add_manifest_file, paths)
+ pool.close()
+ pool.join()
+
+ termlog("Done. %.1fs" % (time.monotonic() - start_time), prefix=False)
+
+ @ensure_not_finalized
+ def add_reference(
+ self,
+ uri: ArtifactManifestEntry | str,
+ name: StrPath | None = None,
+ checksum: bool = True,
+ max_objects: int | None = None,
+ ) -> Sequence[ArtifactManifestEntry]:
+ """Add a reference denoted by a URI to the artifact.
+
+ Unlike files or directories that you add to an artifact, references are not
+ uploaded to W&B. For more information,
+ see [Track external files](https://docs.wandb.ai/guides/artifacts/track-external-files).
+
+ By default, the following schemes are supported:
+
+ - http(s): The size and digest of the file will be inferred by the
+ `Content-Length` and the `ETag` response headers returned by the server.
+ - s3: The checksum and size are pulled from the object metadata.
+ If bucket versioning is enabled, then the version ID is also tracked.
+ - gs: The checksum and size are pulled from the object metadata. If bucket
+ versioning is enabled, then the version ID is also tracked.
+ - https, domain matching `*.blob.core.windows.net`
+ - Azure: The checksum and size are be pulled from the blob metadata.
+ If storage account versioning is enabled, then the version ID is
+ also tracked.
+ - file: The checksum and size are pulled from the file system. This scheme
+ is useful if you have an NFS share or other externally mounted volume
+ containing files you wish to track but not necessarily upload.
+
+ For any other scheme, the digest is just a hash of the URI and the size is left
+ blank.
+
+ Args:
+ uri: The URI path of the reference to add. The URI path can be an object
+ returned from `Artifact.get_entry` to store a reference to another
+ artifact's entry.
+ name: The path within the artifact to place the contents of this reference.
+ checksum: Whether or not to checksum the resource(s) located at the
+ reference URI. Checksumming is strongly recommended as it enables
+ automatic integrity validation. Disabling checksumming will speed up
+ artifact creation but reference directories will not iterated through so the
+ objects in the directory will not be saved to the artifact. We recommend
+ setting `checksum=False` when adding reference objects, in which case
+ a new version will only be created if the reference URI changes.
+ max_objects: The maximum number of objects to consider when adding a
+ reference that points to directory or bucket store prefix.
+ By default, the maximum number of objects allowed for Amazon S3,
+ GCS, Azure, and local files is 10,000,000. Other URI schemas
+ do not have a maximum.
+
+ Returns:
+ The added manifest entries.
+
+ Raises:
+ ArtifactFinalizedError: You cannot make changes to the current
+ artifact version because it is finalized. Log a new artifact
+ version instead.
+ """
+ if name is not None:
+ name = LogicalPath(name)
+
+ # This is a bit of a hack, we want to check if the uri is a of the type
+ # ArtifactManifestEntry. If so, then recover the reference URL.
+ if isinstance(uri, ArtifactManifestEntry):
+ uri_str = uri.ref_url()
+ elif isinstance(uri, str):
+ uri_str = uri
+ url = urlparse(str(uri_str))
+ if not url.scheme:
+ raise ValueError(
+ "References must be URIs. To reference a local file, use file://"
+ )
+
+ manifest_entries = self.manifest.storage_policy.store_reference(
+ self,
+ URIStr(uri_str),
+ name=name,
+ checksum=checksum,
+ max_objects=max_objects,
+ )
+ for entry in manifest_entries:
+ self.manifest.add_entry(entry)
+
+ return manifest_entries
+
+ @ensure_not_finalized
+ def add(
+ self, obj: WBValue, name: StrPath, overwrite: bool = False
+ ) -> ArtifactManifestEntry:
+ """Add wandb.WBValue `obj` to the artifact.
+
+ Args:
+ obj: The object to add. Currently support one of Bokeh, JoinedTable,
+ PartitionedTable, Table, Classes, ImageMask, BoundingBoxes2D,
+ Audio, Image, Video, Html, Object3D
+ name: The path within the artifact to add the object.
+ overwrite: If True, overwrite existing objects with the same file
+ path if applicable.
+
+ Returns:
+ The added manifest entry
+
+ Raises:
+ ArtifactFinalizedError: You cannot make changes to the current
+ artifact version because it is finalized. Log a new artifact
+ version instead.
+ """
+ name = LogicalPath(name)
+
+ # This is a "hack" to automatically rename tables added to
+ # the wandb /media/tables directory to their sha-based name.
+ # TODO: figure out a more appropriate convention.
+ is_tmp_name = name.startswith("media/tables")
+
+ # Validate that the object is one of the correct wandb.Media types
+ # TODO: move this to checking subclass of wandb.Media once all are
+ # generally supported
+ allowed_types = (
+ data_types.Bokeh,
+ data_types.JoinedTable,
+ data_types.PartitionedTable,
+ data_types.Table,
+ data_types.Classes,
+ data_types.ImageMask,
+ data_types.BoundingBoxes2D,
+ data_types.Audio,
+ data_types.Image,
+ data_types.Video,
+ data_types.Html,
+ data_types.Object3D,
+ data_types.Molecule,
+ data_types._SavedModel,
+ )
+ if not isinstance(obj, allowed_types):
+ raise TypeError(
+ f"Found object of type {obj.__class__}, expected one of:"
+ f" {allowed_types}"
+ )
+
+ obj_id = id(obj)
+ if obj_id in self._added_objs:
+ return self._added_objs[obj_id][1]
+
+ # If the object is coming from another artifact, save it as a reference
+ ref_path = obj._get_artifact_entry_ref_url()
+ if ref_path is not None:
+ return self.add_reference(ref_path, type(obj).with_suffix(name))[0]
+
+ val = obj.to_json(self)
+ name = obj.with_suffix(name)
+ entry = self.manifest.get_entry_by_path(name)
+ if (not overwrite) and (entry is not None):
+ return entry
+
+ if is_tmp_name:
+ file_path = os.path.join(self._TMP_DIR.name, str(id(self)), name)
+ folder_path, _ = os.path.split(file_path)
+ os.makedirs(folder_path, exist_ok=True)
+ with open(file_path, "w", encoding="utf-8") as tmp_f:
+ json.dump(val, tmp_f, sort_keys=True)
+ else:
+ filemode = "w" if overwrite else "x"
+ with self.new_file(name, mode=filemode, encoding="utf-8") as f:
+ json.dump(val, f, sort_keys=True)
+ file_path = f.name
+
+ # Note, we add the file from our temp directory.
+ # It will be added again later on finalize, but succeed since
+ # the checksum should match
+ entry = self.add_file(file_path, name, is_tmp_name)
+ # We store a reference to the obj so that its id doesn't get reused.
+ self._added_objs[obj_id] = (obj, entry)
+ if obj._artifact_target is None:
+ obj._set_artifact_target(self, entry.path)
+
+ if is_tmp_name:
+ with contextlib.suppress(FileNotFoundError):
+ os.remove(file_path)
+
+ return entry
+
+ def _add_local_file(
+ self,
+ name: StrPath,
+ path: StrPath,
+ digest: B64MD5 | None = None,
+ skip_cache: bool | None = False,
+ policy: Literal["mutable", "immutable"] | None = "mutable",
+ overwrite: bool = False,
+ ) -> ArtifactManifestEntry:
+ policy = policy or "mutable"
+ if policy not in ["mutable", "immutable"]:
+ raise ValueError(
+ f"Invalid policy {policy!r}. Policy may only be `mutable` or `immutable`."
+ )
+ upload_path = path
+ if policy == "mutable":
+ with tempfile.NamedTemporaryFile(dir=get_staging_dir(), delete=False) as f:
+ staging_path = f.name
+ shutil.copyfile(path, staging_path)
+ # Set as read-only to prevent changes to the file during upload process
+ os.chmod(staging_path, stat.S_IRUSR)
+ upload_path = staging_path
+
+ entry = ArtifactManifestEntry(
+ path=name,
+ digest=digest or md5_file_b64(upload_path),
+ size=os.path.getsize(upload_path),
+ local_path=upload_path,
+ skip_cache=skip_cache,
+ )
+ self.manifest.add_entry(entry, overwrite=overwrite)
+ self._added_local_paths[os.fspath(path)] = entry
+ return entry
+
+ @ensure_not_finalized
+ def remove(self, item: StrPath | ArtifactManifestEntry) -> None:
+ """Remove an item from the artifact.
+
+ Args:
+ item: The item to remove. Can be a specific manifest entry
+ or the name of an artifact-relative path. If the item
+ matches a directory all items in that directory will be removed.
+
+ Raises:
+ ArtifactFinalizedError: You cannot make changes to the current
+ artifact version because it is finalized. Log a new artifact
+ version instead.
+ FileNotFoundError: If the item isn't found in the artifact.
+ """
+ if isinstance(item, ArtifactManifestEntry):
+ self.manifest.remove_entry(item)
+ return
+
+ path = str(PurePosixPath(item))
+ if entry := self.manifest.get_entry_by_path(path):
+ return self.manifest.remove_entry(entry)
+
+ entries = self.manifest.get_entries_in_directory(path)
+ if not entries:
+ raise FileNotFoundError(f"No such file or directory: {path}")
+ for entry in entries:
+ self.manifest.remove_entry(entry)
+
+ def get_path(self, name: StrPath) -> ArtifactManifestEntry:
+ """Deprecated. Use `get_entry(name)`."""
+ deprecate(
+ field_name=Deprecated.artifact__get_path,
+ warning_message="Artifact.get_path(name) is deprecated, use Artifact.get_entry(name) instead.",
+ )
+ return self.get_entry(name)
+
+ @ensure_logged
+ def get_entry(self, name: StrPath) -> ArtifactManifestEntry:
+ """Get the entry with the given name.
+
+ Args:
+ name: The artifact relative name to get
+
+ Returns:
+ A `W&B` object.
+
+ Raises:
+ ArtifactNotLoggedError: if the artifact isn't logged or the run is offline.
+ KeyError: if the artifact doesn't contain an entry with the given name.
+ """
+ name = LogicalPath(name)
+ entry = self.manifest.entries.get(name) or self._get_obj_entry(name)[0]
+ if entry is None:
+ raise KeyError(f"Path not contained in artifact: {name}")
+ entry._parent_artifact = self
+ return entry
+
+ @ensure_logged
+ def get(self, name: str) -> WBValue | None:
+ """Get the WBValue object located at the artifact relative `name`.
+
+ Args:
+ name: The artifact relative name to retrieve.
+
+ Returns:
+ W&B object that can be logged with `run.log()` and
+ visualized in the W&B UI.
+
+ Raises:
+ ArtifactNotLoggedError: if the artifact isn't logged or the
+ run is offline.
+ """
+ entry, wb_class = self._get_obj_entry(name)
+ if entry is None or wb_class is None:
+ return None
+
+ # If the entry is a reference from another artifact, then get it directly from
+ # that artifact.
+ if referenced_id := entry._referenced_artifact_id():
+ assert self._client is not None
+ artifact = self._from_id(referenced_id, client=self._client)
+ assert artifact is not None
+ return artifact.get(uri_from_path(entry.ref))
+
+ # Special case for wandb.Table. This is intended to be a short term
+ # optimization. Since tables are likely to download many other assets in
+ # artifact(s), we eagerly download the artifact using the parallelized
+ # `artifact.download`. In the future, we should refactor the deserialization
+ # pattern such that this special case is not needed.
+ if wb_class == wandb.Table:
+ self.download()
+
+ # Get the ArtifactManifestEntry
+ item = self.get_entry(entry.path)
+ item_path = item.download()
+
+ # Load the object from the JSON blob
+ with open(item_path) as file:
+ json_obj = json.load(file)
+
+ result = wb_class.from_json(json_obj, self)
+ result._set_artifact_source(self, name)
+ return result
+
+ def get_added_local_path_name(self, local_path: str) -> str | None:
+ """Get the artifact relative name of a file added by a local filesystem path.
+
+ Args:
+ local_path: The local path to resolve into an artifact relative name.
+
+ Returns:
+ The artifact relative name.
+ """
+ if entry := self._added_local_paths.get(local_path):
+ return entry.path
+ return None
+
+ def _get_obj_entry(
+ self, name: str
+ ) -> tuple[ArtifactManifestEntry, Type[WBValue]] | tuple[None, None]: # noqa: UP006 # `type` shadows `Artifact.type`
+ """Return an object entry by name, handling any type suffixes.
+
+ When objects are added with `.add(obj, name)`, the name is typically changed to
+ include the suffix of the object type when serializing to JSON. So we need to be
+ able to resolve a name, without tasking the user with appending .THING.json.
+ This method returns an entry if it exists by a suffixed name.
+
+ Args:
+ name: name used when adding
+ """
+ for wb_class in WBValue.type_mapping().values():
+ wandb_file_name = wb_class.with_suffix(name)
+ if entry := self.manifest.entries.get(wandb_file_name):
+ return entry, wb_class
+ return None, None
+
+ # Downloading.
+
+ @ensure_logged
+ def download(
+ self,
+ root: StrPath | None = None,
+ allow_missing_references: bool = False,
+ skip_cache: bool | None = None,
+ path_prefix: StrPath | None = None,
+ multipart: bool | None = None,
+ ) -> FilePathStr:
+ """Download the contents of the artifact to the specified root directory.
+
+ Existing files located within `root` are not modified. Explicitly delete `root`
+ before you call `download` if you want the contents of `root` to exactly match
+ the artifact.
+
+ Args:
+ root: The directory W&B stores the artifact's files.
+ allow_missing_references: If set to `True`, any invalid reference paths
+ will be ignored while downloading referenced files.
+ skip_cache: If set to `True`, the artifact cache will be skipped when
+ downloading and W&B will download each file into the default root or
+ specified download directory.
+ path_prefix: If specified, only files with a path that starts with the given
+ prefix will be downloaded. Uses unix format (forward slashes).
+ multipart: If set to `None` (default), the artifact will be downloaded
+ in parallel using multipart download if individual file size is greater than
+ 2GB. If set to `True` or `False`, the artifact will be downloaded in
+ parallel or serially regardless of the file size.
+
+ Returns:
+ The path to the downloaded contents.
+
+ Raises:
+ ArtifactNotLoggedError: If the artifact is not logged.
+ """
+ root = FilePathStr(root or self._default_root())
+ self._add_download_root(root)
+
+ # TODO: download artifacts using core when implemented
+ # if is_require_core():
+ # return self._download_using_core(
+ # root=root,
+ # allow_missing_references=allow_missing_references,
+ # skip_cache=bool(skip_cache),
+ # path_prefix=path_prefix,
+ # )
+ return self._download(
+ root=root,
+ allow_missing_references=allow_missing_references,
+ skip_cache=skip_cache,
+ path_prefix=path_prefix,
+ multipart=multipart,
+ )
+
+ def _download_using_core(
+ self,
+ root: str,
+ allow_missing_references: bool = False,
+ skip_cache: bool = False,
+ path_prefix: StrPath | None = None,
+ ) -> FilePathStr:
+ import pathlib
+
+ from wandb.sdk.backend.backend import Backend
+
+ # TODO: Create a special stream instead of relying on an existing run.
+ if wandb.run is None:
+ wl = wandb_setup.singleton()
+
+ stream_id = generate_id()
+
+ settings = wl.settings.to_proto()
+ # TODO: remove this
+ tmp_dir = pathlib.Path(tempfile.mkdtemp())
+
+ settings.sync_dir.value = str(tmp_dir)
+ settings.sync_file.value = str(tmp_dir / f"{stream_id}.wandb")
+ settings.files_dir.value = str(tmp_dir / "files")
+ settings.run_id.value = stream_id
+
+ service = wl.ensure_service()
+ service.inform_init(settings=settings, run_id=stream_id)
+
+ backend = Backend(settings=wl.settings, service=service)
+ backend.ensure_launched()
+
+ assert backend.interface
+ backend.interface._stream_id = stream_id # type: ignore
+ else:
+ assert wandb.run._backend
+ backend = wandb.run._backend
+
+ assert backend.interface
+ handle = backend.interface.deliver_download_artifact(
+ self.id, # type: ignore
+ root,
+ allow_missing_references,
+ skip_cache,
+ path_prefix, # type: ignore
+ )
+ # TODO: Start the download process in the user process too, to handle reference downloads
+ self._download(
+ root=root,
+ allow_missing_references=allow_missing_references,
+ skip_cache=skip_cache,
+ path_prefix=path_prefix,
+ )
+ result = handle.wait_or(timeout=None)
+
+ response = result.response.download_artifact_response
+ if response.error_message:
+ raise ValueError(f"Error downloading artifact: {response.error_message}")
+
+ return FilePathStr(root)
+
+ def _download(
+ self,
+ root: str,
+ allow_missing_references: bool = False,
+ skip_cache: bool | None = None,
+ path_prefix: StrPath | None = None,
+ multipart: bool | None = None,
+ ) -> FilePathStr:
+ nfiles = len(self.manifest.entries)
+ size_mb = self.size / _MB
+
+ if log := (nfiles > 5000 or size_mb > 50):
+ termlog(
+ f"Downloading large artifact {self.name!r}, {size_mb:.2f}MB. {nfiles!r} files...",
+ )
+ start_time = time.monotonic()
+
+ download_logger = ArtifactDownloadLogger(nfiles=nfiles)
+
+ def _download_entry(entry: ArtifactManifestEntry, executor: Executor) -> None:
+ multipart_executor = (
+ executor
+ if should_multipart_download(entry.size, override=multipart)
+ else None
+ )
+ try:
+ entry.download(root, skip_cache=skip_cache, executor=multipart_executor)
+ except FileNotFoundError as e:
+ if allow_missing_references:
+ wandb.termwarn(str(e))
+ return
+ raise
+ except _GCSIsADirectoryError as e:
+ logger.debug(str(e))
+ return
+ download_logger.notify_downloaded()
+
+ def _init_thread(
+ api_key: str | None, cookies: dict | None, headers: dict | None
+ ) -> None:
+ """Initialize the thread-local API settings in the CURRENT thread."""
+ _thread_local_api_settings.api_key = api_key
+ _thread_local_api_settings.cookies = cookies
+ _thread_local_api_settings.headers = headers
+
+ with ThreadPoolExecutor(
+ max_workers=64,
+ initializer=_init_thread,
+ initargs=(
+ _thread_local_api_settings.api_key,
+ _thread_local_api_settings.cookies,
+ _thread_local_api_settings.headers,
+ ),
+ ) as executor:
+ batch_size = env.get_artifact_fetch_file_url_batch_size()
+
+ active_futures = set()
+ cursor, has_more = None, True
+ while has_more:
+ files_page = self._fetch_file_urls(cursor=cursor, per_page=batch_size)
+
+ has_more = files_page.page_info.has_next_page
+ cursor = files_page.page_info.end_cursor
+
+ # `File` nodes are formally nullable, so filter them out just in case.
+ file_nodes = (e.node for e in files_page.edges if e.node)
+ for node in file_nodes:
+ entry = self.get_entry(node.name)
+ # TODO: uncomment once artifact downloads are supported in core
+ # if require_core and entry.ref is None:
+ # # Handled by core
+ # continue
+ entry._download_url = node.direct_url
+ if (not path_prefix) or entry.path.startswith(str(path_prefix)):
+ active_futures.add(
+ executor.submit(_download_entry, entry, executor=executor)
+ )
+
+ # Wait for download threads to catch up.
+ #
+ # Extra context and observations (tonyyli):
+ # - Even though the ThreadPoolExecutor limits the number of
+ # concurrently-executed tasks, its internal task queue is unbounded.
+ # The code below seems intended to ensure that at most `batch_size`
+ # "backlogged" futures are held in memory at any given time. This seems like
+ # a reasonable safeguard against unbounded memory consumption.
+ #
+ # - We should probably use a builtin (bounded) Queue or Semaphore here instead.
+ # Consider this for a future change, or (depending on risk and risk tolerance)
+ # managing this logic via asyncio instead, if viable.
+ if len(active_futures) > batch_size:
+ for future in as_completed(active_futures):
+ future.result() # check for errors
+ active_futures.remove(future)
+ if len(active_futures) <= batch_size:
+ break
+
+ # Check for errors.
+ for future in as_completed(active_futures):
+ future.result()
+
+ if log:
+ # If you're wondering if we can display a `timedelta`, note that it
+ # doesn't really support custom string format specifiers (compared to
+ # e.g. `datetime` objs). To truncate the number of decimal places for
+ # the seconds part, we manually convert/format each part below.
+ dt_secs = abs(time.monotonic() - start_time)
+ hrs, mins = divmod(dt_secs, 3600)
+ mins, secs = divmod(mins, 60)
+ termlog(
+ f"Done. {int(hrs):02d}:{int(mins):02d}:{secs:04.1f} ({size_mb / dt_secs:.1f}MB/s)",
+ prefix=False,
+ )
+ return FilePathStr(root)
+
+ @retry.retriable(
+ retry_timedelta=timedelta(minutes=3),
+ retryable_exceptions=(requests.RequestException),
+ )
+ def _fetch_file_urls(
+ self, cursor: str | None, per_page: int = 5000
+ ) -> FileUrlsFragment:
+ if self._client is None:
+ raise RuntimeError("Client not initialized")
+
+ if InternalApi()._server_supports(
+ pb.ServerFeature.ARTIFACT_COLLECTION_MEMBERSHIP_FILES
+ ):
+ query = gql(ARTIFACT_COLLECTION_MEMBERSHIP_FILE_URLS_GQL)
+ gql_vars = {
+ "entityName": self.entity,
+ "projectName": self.project,
+ "artifactName": self.name.split(":")[0],
+ "artifactVersionIndex": self.version,
+ "cursor": cursor,
+ "perPage": per_page,
+ }
+ data = self._client.execute(query, variable_values=gql_vars, timeout=60)
+ result = ArtifactCollectionMembershipFileUrls.model_validate(data)
+
+ if not (
+ (project := result.project)
+ and (collection := project.artifact_collection)
+ and (membership := collection.artifact_membership)
+ and (files := membership.files)
+ ):
+ raise ValueError(f"Unable to fetch files for artifact: {self.name!r}")
+ return files
+ else:
+ query = gql(ARTIFACT_FILE_URLS_GQL)
+ gql_vars = {"id": self.id, "cursor": cursor, "perPage": per_page}
+ data = self._client.execute(query, variable_values=gql_vars, timeout=60)
+ result = ArtifactFileUrls.model_validate(data)
+
+ if not ((artifact := result.artifact) and (files := artifact.files)):
+ raise ValueError(f"Unable to fetch files for artifact: {self.name!r}")
+ return files
+
+ @ensure_logged
+ def checkout(self, root: str | None = None) -> str:
+ """Replace the specified root directory with the contents of the artifact.
+
+ WARNING: This will delete all files in `root` that are not included in the
+ artifact.
+
+ Args:
+ root: The directory to replace with this artifact's files.
+
+ Returns:
+ The path of the checked out contents.
+
+ Raises:
+ ArtifactNotLoggedError: If the artifact is not logged.
+ """
+ root = root or self._default_root(include_version=False)
+
+ for dirpath, _, files in os.walk(root):
+ for file in files:
+ full_path = os.path.join(dirpath, file)
+ artifact_path = os.path.relpath(full_path, start=root)
+ try:
+ self.get_entry(artifact_path)
+ except KeyError:
+ # File is not part of the artifact, remove it.
+ os.remove(full_path)
+
+ return self.download(root=root)
+
+ @ensure_logged
+ def verify(self, root: str | None = None) -> None:
+ """Verify that the contents of an artifact match the manifest.
+
+ All files in the directory are checksummed and the checksums are then
+ cross-referenced against the artifact's manifest. References are not verified.
+
+ Args:
+ root: The directory to verify. If None artifact will be downloaded to
+ './artifacts/self.name/'.
+
+ Raises:
+ ArtifactNotLoggedError: If the artifact is not logged.
+ ValueError: If the verification fails.
+ """
+ root = root or self._default_root()
+
+ for dirpath, _, files in os.walk(root):
+ for file in files:
+ full_path = os.path.join(dirpath, file)
+ artifact_path = os.path.relpath(full_path, start=root)
+ try:
+ self.get_entry(artifact_path)
+ except KeyError:
+ raise ValueError(
+ f"Found file {full_path} which is not a member of artifact {self.name}"
+ )
+
+ ref_count = 0
+ for entry in self.manifest.entries.values():
+ if entry.ref is None:
+ if md5_file_b64(os.path.join(root, entry.path)) != entry.digest:
+ raise ValueError(f"Digest mismatch for file: {entry.path}")
+ else:
+ ref_count += 1
+ if ref_count > 0:
+ termwarn(f"skipped verification of {ref_count} refs")
+
+ @ensure_logged
+ def file(self, root: str | None = None) -> StrPath:
+ """Download a single file artifact to the directory you specify with `root`.
+
+ Args:
+ root: The root directory to store the file. Defaults to
+ `./artifacts/self.name/`.
+
+ Returns:
+ The full path of the downloaded file.
+
+ Raises:
+ ArtifactNotLoggedError: If the artifact is not logged.
+ ValueError: If the artifact contains more than one file.
+ """
+ if root is None:
+ root = os.path.join(".", "artifacts", self.name)
+
+ if len(self.manifest.entries) > 1:
+ raise ValueError(
+ "This artifact contains more than one file, call `.download()` to get "
+ 'all files or call .get_entry("filename").download()'
+ )
+
+ return self.get_entry(list(self.manifest.entries)[0]).download(root)
+
+ @ensure_logged
+ def files(
+ self, names: list[str] | None = None, per_page: int = 50
+ ) -> ArtifactFiles:
+ """Iterate over all files stored in this artifact.
+
+ Args:
+ names: The filename paths relative to the root of the artifact you wish to
+ list.
+ per_page: The number of files to return per request.
+
+ Returns:
+ An iterator containing `File` objects.
+
+ Raises:
+ ArtifactNotLoggedError: If the artifact is not logged.
+ """
+ return ArtifactFiles(self._client, self, names, per_page)
+
+ def _default_root(self, include_version: bool = True) -> FilePathStr:
+ name = self.source_name if include_version else self.source_name.split(":")[0]
+ root = os.path.join(env.get_artifact_dir(), name)
+ # In case we're on a system where the artifact dir has a name corresponding to
+ # an unexpected filesystem, we'll check for alternate roots. If one exists we'll
+ # use that, otherwise we'll fall back to the system-preferred path.
+ return FilePathStr(check_exists(root) or system_preferred_path(root))
+
+ def _add_download_root(self, dir_path: str) -> None:
+ self._download_roots.add(os.path.abspath(dir_path))
+
+ def _local_path_to_name(self, file_path: str) -> str | None:
+ """Convert a local file path to a path entry in the artifact."""
+ abs_file_path = os.path.abspath(file_path)
+ abs_file_parts = abs_file_path.split(os.sep)
+ for i in range(len(abs_file_parts) + 1):
+ if os.path.join(os.sep, *abs_file_parts[:i]) in self._download_roots:
+ return os.path.join(*abs_file_parts[i:])
+ return None
+
+ # Others.
+
+ @ensure_logged
+ def delete(self, delete_aliases: bool = False) -> None:
+ """Delete an artifact and its files.
+
+ If called on a linked artifact, only the link is deleted, and the
+ source artifact is unaffected.
+
+ Use `artifact.unlink()` instead of `artifact.delete()` to remove a link between a source artifact and a linked artifact.
+
+ Args:
+ delete_aliases: If set to `True`, deletes all aliases associated
+ with the artifact. Otherwise, this raises an exception if
+ the artifact has existing aliases. This parameter is ignored
+ if the artifact is linked (a member of a portfolio collection).
+
+ Raises:
+ ArtifactNotLoggedError: If the artifact is not logged.
+ """
+ if self.is_link:
+ wandb.termwarn(
+ "Deleting a link artifact will only unlink the artifact from the source artifact and not delete the source artifact and the data of the source artifact."
+ )
+ self._unlink()
+ else:
+ self._delete(delete_aliases)
+
+ @normalize_exceptions
+ def _delete(self, delete_aliases: bool = False) -> None:
+ if self._client is None:
+ raise RuntimeError("Client not initialized for artifact mutations")
+
+ mutation = gql(DELETE_ARTIFACT_GQL)
+ gql_vars = {"artifactID": self.id, "deleteAliases": delete_aliases}
+
+ self._client.execute(mutation, variable_values=gql_vars)
+
+ @normalize_exceptions
+ def link(self, target_path: str, aliases: list[str] | None = None) -> Artifact:
+ """Link this artifact to a portfolio (a promoted collection of artifacts).
+
+ Args:
+ target_path: The path to the portfolio inside a project.
+ The target path must adhere to one of the following
+ schemas `{portfolio}`, `{project}/{portfolio}` or
+ `{entity}/{project}/{portfolio}`.
+ To link the artifact to the Model Registry, rather than to a generic
+ portfolio inside a project, set `target_path` to the following
+ schema `{"model-registry"}/{Registered Model Name}` or
+ `{entity}/{"model-registry"}/{Registered Model Name}`.
+ aliases: A list of strings that uniquely identifies the artifact
+ inside the specified portfolio.
+
+ Raises:
+ ArtifactNotLoggedError: If the artifact is not logged.
+
+ Returns:
+ The linked artifact.
+ """
+ from wandb import Api
+
+ if self.is_link:
+ wandb.termwarn(
+ "Linking to a link artifact will result in directly linking to the source artifact of that link artifact."
+ )
+
+ if self._client is None:
+ raise ValueError("Client not initialized for artifact mutations")
+
+ # Save the artifact first if necessary
+ if self.is_draft():
+ if not self._is_draft_save_started():
+ self.save(project=self.source_project)
+
+ # Wait until the artifact is committed before trying to link it.
+ self.wait()
+
+ api = InternalApi()
+ settings = api.settings()
+
+ target = ArtifactPath.from_str(target_path).with_defaults(
+ project=settings.get("project") or "uncategorized",
+ )
+
+ # Parse the entity (first part of the path) appropriately,
+ # depending on whether we're linking to a registry
+ if target.is_registry_path():
+ # In a Registry linking, the entity is used to fetch the organization of the artifact
+ # therefore the source artifact's entity is passed to the backend
+ org = target.prefix or settings.get("organization") or ""
+ target.prefix = api._resolve_org_entity_name(self.source_entity, org)
+ else:
+ target = target.with_defaults(prefix=self.source_entity)
+
+ # Explicitly convert to FullArtifactPath to ensure all fields are present
+ target = FullArtifactPath(**asdict(target))
+
+ # Prepare the validated GQL input, send it
+ alias_inputs = [
+ ArtifactAliasInput(artifact_collection_name=target.name, alias=a)
+ for a in (aliases or [])
+ ]
+ gql_input = LinkArtifactInput(
+ artifact_id=self.id,
+ artifact_portfolio_name=target.name,
+ entity_name=target.prefix,
+ project_name=target.project,
+ aliases=alias_inputs,
+ )
+ gql_vars = {"input": gql_input.model_dump(exclude_none=True)}
+
+ # Newer server versions can return `artifactMembership` directly in the response,
+ # avoiding the need to re-fetch the linked artifact at the end.
+ if api._server_supports(
+ pb.ServerFeature.ARTIFACT_MEMBERSHIP_IN_LINK_ARTIFACT_RESPONSE
+ ):
+ omit_fragments = set()
+ else:
+ # FIXME: Make `gql_compat` omit nested fragment definitions recursively (but safely)
+ omit_fragments = {
+ "MembershipWithArtifact",
+ "ArtifactFragment",
+ "ArtifactFragmentWithoutAliases",
+ }
+
+ gql_op = gql_compat(LINK_ARTIFACT_GQL, omit_fragments=omit_fragments)
+ data = self._client.execute(gql_op, variable_values=gql_vars)
+ result = LinkArtifact.model_validate(data).link_artifact
+
+ # Newer server versions can return artifactMembership directly in the response
+ if result and (membership := result.artifact_membership):
+ return self._from_membership(membership, target=target, client=self._client)
+
+ # Fallback to old behavior, which requires re-fetching the linked artifact to return it
+ if not (result and (version_idx := result.version_index) is not None):
+ raise ValueError("Unable to parse linked artifact version from response")
+
+ link_name = f"{target.to_str()}:v{version_idx}"
+ return Api(overrides={"entity": self.source_entity})._artifact(link_name)
+
+ @ensure_logged
+ def unlink(self) -> None:
+ """Unlink this artifact if it is currently a member of a promoted collection of artifacts.
+
+ Raises:
+ ArtifactNotLoggedError: If the artifact is not logged.
+ ValueError: If the artifact is not linked, in other words,
+ it is not a member of a portfolio collection.
+ """
+ # Fail early if this isn't a linked artifact to begin with
+ if not self.is_link:
+ raise ValueError(
+ f"Artifact {self.qualified_name!r} is not a linked artifact and cannot be unlinked. "
+ f"To delete it, use {nameof(self.delete)!r} instead."
+ )
+
+ self._unlink()
+
+ @normalize_exceptions
+ def _unlink(self) -> None:
+ if self._client is None:
+ raise RuntimeError("Client not initialized for artifact mutations")
+
+ mutation = gql(UNLINK_ARTIFACT_GQL)
+ gql_vars = {"artifactID": self.id, "artifactPortfolioID": self.collection.id}
+
+ try:
+ self._client.execute(mutation, variable_values=gql_vars)
+ except CommError as e:
+ raise CommError(
+ f"You do not have permission to unlink the artifact {self.qualified_name}"
+ ) from e
+
+ @ensure_logged
+ def used_by(self) -> list[Run]:
+ """Get a list of the runs that have used this artifact and its linked artifacts.
+
+ Returns:
+ A list of `Run` objects.
+
+ Raises:
+ ArtifactNotLoggedError: If the artifact is not logged.
+ """
+ if self._client is None:
+ raise RuntimeError("Client not initialized for artifact queries")
+
+ query = gql(ARTIFACT_USED_BY_GQL)
+ gql_vars = {"id": self.id}
+ data = self._client.execute(query, variable_values=gql_vars)
+ result = ArtifactUsedBy.model_validate(data)
+
+ if (
+ (artifact := result.artifact)
+ and (used_by := artifact.used_by)
+ and (edges := used_by.edges)
+ ):
+ run_nodes = (e.node for e in edges)
+ return [
+ Run(self._client, proj.entity_name, proj.name, run.name)
+ for run in run_nodes
+ if (proj := run.project)
+ ]
+ return []
+
+ @ensure_logged
+ def logged_by(self) -> Run | None:
+ """Get the W&B run that originally logged the artifact.
+
+ Returns:
+ The name of the W&B run that originally logged the artifact.
+
+ Raises:
+ ArtifactNotLoggedError: If the artifact is not logged.
+ """
+ if self._client is None:
+ raise RuntimeError("Client not initialized for artifact queries")
+
+ query = gql(ARTIFACT_CREATED_BY_GQL)
+ gql_vars = {"id": self.id}
+ data = self._client.execute(query, variable_values=gql_vars)
+ result = ArtifactCreatedBy.model_validate(data)
+
+ if (
+ (artifact := result.artifact)
+ and (creator := artifact.created_by)
+ and (name := creator.name)
+ and (project := creator.project)
+ ):
+ return Run(self._client, project.entity_name, project.name, name)
+ return None
+
+ @ensure_logged
+ def json_encode(self) -> dict[str, Any]:
+ """Returns the artifact encoded to the JSON format.
+
+ Returns:
+ A `dict` with `string` keys representing attributes of the artifact.
+ """
+ return artifact_to_json(self)
+
+ @staticmethod
+ def _expected_type(
+ entity_name: str, project_name: str, name: str, client: RetryingClient
+ ) -> str | None:
+ """Returns the expected type for a given artifact name and project."""
+ query = gql(ARTIFACT_TYPE_GQL)
+ gql_vars = {
+ "entityName": entity_name,
+ "projectName": project_name,
+ "name": name if (":" in name) else f"{name}:latest",
+ }
+ data = client.execute(query, variable_values=gql_vars)
+ result = ArtifactType.model_validate(data)
+
+ if (
+ (project := result.project)
+ and (artifact := project.artifact)
+ and (artifact_type := artifact.artifact_type)
+ ):
+ return artifact_type.name
+ return None
+
+ def _load_manifest(self, url: str) -> ArtifactManifest:
+ with requests.get(url) as response:
+ response.raise_for_status()
+ return ArtifactManifest.from_manifest_json(response.json())
+
+ def _ttl_duration_seconds_to_gql(self) -> int | None:
+ # Set artifact ttl value to ttl_duration_seconds if the user set a value
+ # otherwise use ttl_status to indicate the backend INHERIT(-1) or DISABLED(-2) when the TTL is None
+ # When ttl_change = None its a no op since nothing changed
+ INHERIT = -1 # noqa: N806
+ DISABLED = -2 # noqa: N806
+
+ if not self._ttl_changed:
+ return None
+ if self._ttl_is_inherited:
+ return INHERIT
+ return self._ttl_duration_seconds or DISABLED
+
+ def _fetch_linked_artifacts(self) -> list[Artifact]:
+ """Fetches all linked artifacts from the server."""
+ if self.id is None:
+ raise ValueError(
+ "Unable to find any artifact memberships for artifact without an ID"
+ )
+ if self._client is None:
+ raise ValueError("Client is not initialized")
+ response = self._client.execute(
+ gql_compat(FETCH_LINKED_ARTIFACTS_GQL),
+ variable_values={"artifactID": self.id},
+ )
+ result = FetchLinkedArtifacts.model_validate(response)
+
+ if not (
+ (artifact := result.artifact)
+ and (memberships := artifact.artifact_memberships)
+ and (membership_edges := memberships.edges)
+ ):
+ raise ValueError("Unable to find any artifact memberships for artifact")
+
+ linked_artifacts: deque[Artifact] = deque()
+ linked_nodes = (
+ node
+ for edge in membership_edges
+ if (
+ (node := edge.node)
+ and (col := node.artifact_collection)
+ and (col.typename__ == LINKED_ARTIFACT_COLLECTION_TYPE)
+ )
+ )
+ for node in linked_nodes:
+ alias_names = unique_list(a.alias for a in node.aliases)
+ version = f"v{node.version_index}"
+ aliases = (
+ [*alias_names, version]
+ if version not in alias_names
+ else [*alias_names]
+ )
+
+ if not (
+ node
+ and (col := node.artifact_collection)
+ and (proj := col.project)
+ and (proj.entity_name and proj.name)
+ ):
+ raise ValueError("Unable to fetch fields for linked artifact")
+
+ link_fields = _LinkArtifactFields(
+ entity_name=proj.entity_name,
+ project_name=proj.name,
+ name=f"{col.name}:{version}",
+ version=version,
+ aliases=aliases,
+ )
+ link = self._create_linked_artifact_using_source_artifact(link_fields)
+ linked_artifacts.append(link)
+ return list(linked_artifacts)
+
+ def _create_linked_artifact_using_source_artifact(
+ self,
+ link_fields: _LinkArtifactFields,
+ ) -> Artifact:
+ """Copies the source artifact to a linked artifact."""
+ linked_artifact = copy(self)
+ linked_artifact._version = link_fields.version
+ linked_artifact._aliases = link_fields.aliases
+ linked_artifact._saved_aliases = copy(link_fields.aliases)
+ linked_artifact._name = link_fields.name
+ linked_artifact._entity = link_fields.entity_name
+ linked_artifact._project = link_fields.project_name
+ linked_artifact._is_link = link_fields.is_link
+ linked_artifact._linked_artifacts = link_fields.linked_artifacts
+ return linked_artifact
+
+
+class _ArtifactVersionType(WBType):
+ name = "artifactVersion"
+ types = [Artifact]
+
+
+TypeRegistry.add(_ArtifactVersionType)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_download_logger.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_download_logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4370d68bc74b9252827b6b18aeac87a4b06ef55
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_download_logger.py
@@ -0,0 +1,45 @@
+"""Artifact download logger."""
+
+from __future__ import annotations
+
+import multiprocessing.dummy
+import time
+from typing import Callable
+
+from wandb.errors.term import termlog
+
+
+class ArtifactDownloadLogger:
+ def __init__(
+ self,
+ nfiles: int,
+ clock_for_testing: Callable[[], float] = time.monotonic,
+ termlog_for_testing: Callable[..., None] = termlog,
+ ) -> None:
+ self._nfiles = nfiles
+ self._clock = clock_for_testing
+ self._termlog = termlog_for_testing
+
+ self._n_files_downloaded = 0
+ self._spinner_index = 0
+ self._last_log_time = self._clock()
+ self._lock = multiprocessing.dummy.Lock()
+
+ def notify_downloaded(self) -> None:
+ with self._lock:
+ self._n_files_downloaded += 1
+ if self._n_files_downloaded == self._nfiles:
+ self._termlog(
+ f" {self._nfiles} of {self._nfiles} files downloaded. ",
+ # ^ trailing spaces to wipe out ellipsis from previous logs
+ newline=True,
+ )
+ self._last_log_time = self._clock()
+ elif self._clock() - self._last_log_time > 0.1:
+ self._spinner_index += 1
+ spinner = r"-\|/"[self._spinner_index % 4]
+ self._termlog(
+ f"{spinner} {self._n_files_downloaded} of {self._nfiles} files downloaded...\r",
+ newline=False,
+ )
+ self._last_log_time = self._clock()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_file_cache.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_file_cache.py
new file mode 100644
index 0000000000000000000000000000000000000000..90c4adb1bea34cf324331e77a7c19744da3cc5c6
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_file_cache.py
@@ -0,0 +1,256 @@
+"""Artifact cache."""
+
+from __future__ import annotations
+
+import contextlib
+import errno
+import hashlib
+import os
+import shutil
+import subprocess
+import sys
+from functools import lru_cache
+from pathlib import Path
+from tempfile import NamedTemporaryFile
+from typing import IO, ContextManager, Iterator, Protocol
+
+import wandb
+from wandb import env, util
+from wandb.sdk.lib.filesystem import files_in
+from wandb.sdk.lib.hashutil import B64MD5, ETag, b64_to_hex_id
+from wandb.sdk.lib.paths import FilePathStr, StrPath, URIStr
+
+
+class Opener(Protocol):
+ def __call__(self, mode: str = ...) -> ContextManager[IO]:
+ pass
+
+
+def artifacts_cache_dir() -> Path:
+ """Get the artifacts cache directory."""
+ return env.get_cache_dir() / "artifacts"
+
+
+def _get_sys_umask_threadsafe() -> int:
+ # Workaround to get the current system umask, since
+ # - `os.umask()` isn't thread-safe
+ # - we don't want to inadvertently change the umask of the current process
+ # See: https://stackoverflow.com/questions/53227072/reading-umask-thread-safe
+ umask_cmd = (sys.executable, "-c", "import os; print(os.umask(22))")
+ return int(subprocess.check_output(umask_cmd))
+
+
+class ArtifactFileCache:
+ def __init__(self, cache_dir: StrPath) -> None:
+ self._cache_dir = Path(cache_dir)
+ self._obj_dir = self._cache_dir / "obj"
+ self._temp_dir = self._cache_dir / "tmp"
+ self._ensure_write_permissions()
+
+ # NamedTemporaryFile sets the file mode to 600 [1], we reset to the default.
+ # [1] https://stackoverflow.com/questions/10541760/can-i-set-the-umask-for-tempfile-namedtemporaryfile-in-python
+ self._sys_umask = _get_sys_umask_threadsafe()
+
+ self._override_cache_path: StrPath | None = None
+
+ def check_md5_obj_path(
+ self, b64_md5: B64MD5, size: int
+ ) -> tuple[FilePathStr, bool, Opener]:
+ # Check if we're using vs skipping the cache
+ if self._override_cache_path is not None:
+ skip_cache = True
+ path = Path(self._override_cache_path)
+ else:
+ skip_cache = False
+ hex_md5 = b64_to_hex_id(b64_md5)
+ path = self._obj_dir / "md5" / hex_md5[:2] / hex_md5[2:]
+ return self._check_or_create(path, size, skip_cache=skip_cache)
+
+ # TODO(spencerpearson): this method at least needs its signature changed.
+ # An ETag is not (necessarily) a checksum.
+ def check_etag_obj_path(
+ self,
+ url: URIStr,
+ etag: ETag,
+ size: int,
+ ) -> tuple[FilePathStr, bool, Opener]:
+ # Check if we're using vs skipping the cache
+ if self._override_cache_path is not None:
+ skip_cache = True
+ path = Path(self._override_cache_path)
+ else:
+ skip_cache = False
+ hexhash = hashlib.sha256(
+ hashlib.sha256(url.encode("utf-8")).digest()
+ + hashlib.sha256(etag.encode("utf-8")).digest()
+ ).hexdigest()
+ path = self._obj_dir / "etag" / hexhash[:2] / hexhash[2:]
+ return self._check_or_create(path, size, skip_cache=skip_cache)
+
+ def _check_or_create(
+ self, path: Path, size: int, skip_cache: bool = False
+ ) -> tuple[FilePathStr, bool, Opener]:
+ opener = self._opener(path, size, skip_cache=skip_cache)
+ hit = path.is_file() and path.stat().st_size == size
+ return FilePathStr(path), hit, opener
+
+ def cleanup(
+ self,
+ target_size: int | None = None,
+ remove_temp: bool = False,
+ target_fraction: float | None = None,
+ ) -> int:
+ """Clean up the cache, removing the least recently used files first.
+
+ Args:
+ target_size: The target size of the cache in bytes. If the cache is larger
+ than this, we will remove the least recently used files until the cache
+ is smaller than this size.
+ remove_temp: Whether to remove temporary files. Temporary files are files
+ that are currently being written to the cache. If remove_temp is True,
+ all temp files will be removed, regardless of the target_size or
+ target_fraction.
+ target_fraction: The target fraction of the cache to reclaim. If the cache
+ is larger than this, we will remove the least recently used files until
+ the cache is smaller than this fraction of its current size. It is an
+ error to specify both target_size and target_fraction.
+
+ Returns:
+ The number of bytes reclaimed.
+ """
+ if target_size is None and target_fraction is None:
+ # Default to clearing the entire cache.
+ target_size = 0
+ if target_size is not None and target_fraction is not None:
+ raise ValueError("Cannot specify both target_size and target_fraction")
+ if target_size is not None and target_size < 0:
+ raise ValueError("target_size must be non-negative")
+ if target_fraction is not None and (target_fraction < 0 or target_fraction > 1):
+ raise ValueError("target_fraction must be between 0 and 1")
+
+ bytes_reclaimed = 0
+ total_size = 0
+ temp_size = 0
+
+ # Remove all temporary files if requested. Otherwise sum their size.
+ for entry in files_in(self._temp_dir):
+ size = entry.stat().st_size
+ total_size += size
+ if remove_temp:
+ try:
+ os.remove(entry.path)
+ bytes_reclaimed += size
+ except OSError:
+ pass
+ else:
+ temp_size += size
+ if temp_size:
+ wandb.termwarn(
+ f"Cache contains {util.to_human_size(temp_size)} of temporary files. "
+ "Run `wandb artifact cleanup --remove-temp` to remove them."
+ )
+
+ entries = []
+ for file_entry in files_in(self._obj_dir):
+ total_size += file_entry.stat().st_size
+ entries.append(file_entry)
+
+ if target_fraction is not None:
+ target_size = int(total_size * target_fraction)
+ assert target_size is not None
+
+ for entry in sorted(entries, key=lambda x: x.stat().st_atime):
+ if total_size <= target_size:
+ return bytes_reclaimed
+ try:
+ os.remove(entry.path)
+ except OSError:
+ pass
+ total_size -= entry.stat().st_size
+ bytes_reclaimed += entry.stat().st_size
+
+ if total_size > target_size:
+ wandb.termerror(
+ f"Failed to reclaim enough space in {self._cache_dir}. Try running"
+ " `wandb artifact cache cleanup --remove-temp` to remove temporary files."
+ )
+
+ return bytes_reclaimed
+
+ def _free_space(self) -> int:
+ """Return the number of bytes of free space in the cache directory."""
+ return shutil.disk_usage(self._cache_dir)[2]
+
+ def _reserve_space(self, size: int) -> None:
+ """If a `size` write would exceed disk space, remove cached items to make space.
+
+ Raises:
+ OSError: If there is not enough space to write `size` bytes, even after
+ removing cached items.
+ """
+ if size <= self._free_space():
+ return
+
+ wandb.termwarn("Cache size exceeded. Attempting to reclaim space...")
+ self.cleanup(target_fraction=0.5)
+ if size <= self._free_space():
+ return
+
+ self.cleanup(target_size=0)
+ if size > self._free_space():
+ raise OSError(errno.ENOSPC, f"Insufficient free space in {self._cache_dir}")
+
+ def _opener(self, path: Path, size: int, skip_cache: bool = False) -> Opener:
+ @contextlib.contextmanager
+ def atomic_open(mode: str = "w") -> Iterator[IO]:
+ if "a" in mode:
+ raise ValueError("Appending to cache files is not supported")
+
+ if skip_cache:
+ # We skip the cache, but we'll still need an intermediate, temporary file to ensure atomicity.
+ # Put the temp file in the same root as the destination file in an attempt to avoid moving/copying
+ # across filesystems.
+ temp_dir = path.parent
+ else:
+ self._reserve_space(size)
+ temp_dir = self._temp_dir
+
+ temp_dir.mkdir(parents=True, exist_ok=True)
+ temp_file = NamedTemporaryFile(dir=temp_dir, mode=mode, delete=False)
+ try:
+ yield temp_file
+ temp_file.close()
+ os.chmod(temp_file.name, 0o666 & ~self._sys_umask)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ os.replace(temp_file.name, path)
+ except Exception:
+ os.remove(temp_file.name)
+ raise
+
+ return atomic_open
+
+ def _ensure_write_permissions(self) -> None:
+ """Raise an error if we cannot write to the cache directory."""
+ try:
+ self._temp_dir.mkdir(parents=True, exist_ok=True)
+ with NamedTemporaryFile(dir=self._temp_dir) as f:
+ f.write(b"wandb")
+ except PermissionError as e:
+ raise PermissionError(
+ f"Unable to write to {self._cache_dir}. "
+ "Ensure that the current user has write permissions."
+ ) from e
+
+
+# Memo `ArtifactFileCache` instances while avoiding reliance on global
+# variable(s). Notes:
+# - @lru_cache should be thread-safe.
+# - We don't memoize `get_artifact_file_cache` directly, as the cache_dir
+# may change at runtime. This is likely rare in practice, though.
+@lru_cache(maxsize=1)
+def _build_artifact_file_cache(cache_dir: StrPath) -> ArtifactFileCache:
+ return ArtifactFileCache(cache_dir)
+
+
+def get_artifact_file_cache() -> ArtifactFileCache:
+ return _build_artifact_file_cache(artifacts_cache_dir())
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_instance_cache.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_instance_cache.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6fd6e9676d048a0a7fc0715bb7ae107ae01e7cc
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_instance_cache.py
@@ -0,0 +1,17 @@
+"""Recent Artifact storage.
+
+Artifacts are registered in the cache to ensure they won't be immediately garbage
+collected and can be retrieved by their ID.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from wandb.sdk.lib.capped_dict import CappedDict
+
+if TYPE_CHECKING:
+ from wandb.sdk.artifacts.artifact import Artifact
+
+# There is nothing special about the artifact cache, it's just a global capped dict.
+artifact_instance_cache: dict[str, Artifact] = CappedDict(100)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifest.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifest.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2af2dfa7625ff0c34bc70fef3a2551e508d4807
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifest.py
@@ -0,0 +1,76 @@
+"""Artifact manifest."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Mapping
+
+from wandb.sdk.internal.internal_api import Api as InternalApi
+from wandb.sdk.lib.hashutil import HexMD5
+
+if TYPE_CHECKING:
+ from wandb.sdk.artifacts.artifact_manifest_entry import ArtifactManifestEntry
+ from wandb.sdk.artifacts.storage_policy import StoragePolicy
+
+
+class ArtifactManifest:
+ entries: dict[str, ArtifactManifestEntry]
+
+ @classmethod
+ def from_manifest_json(
+ cls, manifest_json: dict, api: InternalApi | None = None
+ ) -> ArtifactManifest:
+ if "version" not in manifest_json:
+ raise ValueError("Invalid manifest format. Must contain version field.")
+ version = manifest_json["version"]
+ for sub in cls.__subclasses__():
+ if sub.version() == version:
+ return sub.from_manifest_json(manifest_json, api=api)
+ raise ValueError("Invalid manifest version.")
+
+ @classmethod
+ def version(cls) -> int:
+ raise NotImplementedError
+
+ def __init__(
+ self,
+ storage_policy: StoragePolicy,
+ entries: Mapping[str, ArtifactManifestEntry] | None = None,
+ ) -> None:
+ self.storage_policy = storage_policy
+ self.entries = dict(entries) if entries else {}
+
+ def __len__(self) -> int:
+ return len(self.entries)
+
+ def to_manifest_json(self) -> dict:
+ raise NotImplementedError
+
+ def digest(self) -> HexMD5:
+ raise NotImplementedError
+
+ def add_entry(self, entry: ArtifactManifestEntry, overwrite: bool = False) -> None:
+ path = entry.path
+ if (
+ (not overwrite)
+ and (old_entry := self.entries.get(path))
+ and (entry.digest != old_entry.digest)
+ ):
+ raise ValueError(f"Cannot add the same path twice: {path!r}")
+ self.entries[path] = entry
+
+ def remove_entry(self, entry: ArtifactManifestEntry) -> None:
+ try:
+ del self.entries[entry.path]
+ except LookupError:
+ raise FileNotFoundError(f"Cannot remove missing entry: '{entry.path}'")
+
+ def get_entry_by_path(self, path: str) -> ArtifactManifestEntry | None:
+ return self.entries.get(path)
+
+ def get_entries_in_directory(self, directory: str) -> list[ArtifactManifestEntry]:
+ return [
+ entry
+ for key, entry in self.entries.items()
+ # entry keys (paths) use forward slash even for windows
+ if key.startswith(f"{directory}/")
+ ]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifest_entry.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifest_entry.py
new file mode 100644
index 0000000000000000000000000000000000000000..f56f8736b2ac6186486f9856b8a91b0158655e41
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifest_entry.py
@@ -0,0 +1,309 @@
+"""Artifact manifest entry."""
+
+from __future__ import annotations
+
+import concurrent.futures
+import hashlib
+import json
+import logging
+import os
+from contextlib import suppress
+from pathlib import Path
+from typing import TYPE_CHECKING
+from urllib.parse import urlparse
+
+from wandb.proto.wandb_deprecated import Deprecated
+from wandb.sdk.lib.deprecate import deprecate
+from wandb.sdk.lib.filesystem import copy_or_overwrite_changed
+from wandb.sdk.lib.hashutil import (
+ B64MD5,
+ ETag,
+ b64_to_hex_id,
+ hex_to_b64_id,
+ md5_file_b64,
+)
+from wandb.sdk.lib.paths import FilePathStr, LogicalPath, StrPath, URIStr
+
+logger = logging.getLogger(__name__)
+
+if TYPE_CHECKING:
+ from typing_extensions import TypedDict
+
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ class ArtifactManifestEntryDict(TypedDict, total=False):
+ path: str
+ digest: str
+ skip_cache: bool
+ ref: str
+ birthArtifactID: str
+ size: int
+ extra: dict
+ local_path: str
+
+
+_WB_ARTIFACT_SCHEME = "wandb-artifact"
+
+
+def _checksum_cache_path(file_path: str) -> str:
+ """Get path for checksum in central cache directory."""
+ from wandb.sdk.artifacts.artifact_file_cache import artifacts_cache_dir
+
+ # Create a unique cache key based on the file's absolute path
+ abs_path = os.path.abspath(file_path)
+ path_hash = hashlib.sha256(abs_path.encode()).hexdigest()
+
+ # Store in wandb cache directory under checksums subdirectory
+ cache_dir = artifacts_cache_dir() / "checksums"
+ cache_dir.mkdir(parents=True, exist_ok=True)
+
+ return str(cache_dir / f"{path_hash}.checksum")
+
+
+def _read_cached_checksum(file_path: str) -> str | None:
+ """Read checksum from cache if it exists and is valid."""
+ checksum_path = _checksum_cache_path(file_path)
+
+ try:
+ with open(file_path) as f, open(checksum_path) as f_checksum:
+ if os.path.getmtime(f_checksum.name) < os.path.getmtime(f.name):
+ # File was modified after checksum was written
+ return None
+ # Read and return the cached checksum
+ return f_checksum.read().strip()
+ except OSError:
+ # File doesn't exist or couldn't be opened
+ return None
+
+
+def _write_cached_checksum(file_path: str, checksum: str) -> None:
+ """Write checksum to cache directory."""
+ checksum_path = _checksum_cache_path(file_path)
+ try:
+ with open(checksum_path, "w") as f:
+ f.write(checksum)
+ except OSError:
+ # Non-critical failure, just log it
+ logger.debug(f"Failed to write checksum cache for {file_path!r}")
+
+
+class ArtifactManifestEntry:
+ """A single entry in an artifact manifest."""
+
+ path: LogicalPath
+ digest: B64MD5 | URIStr | FilePathStr | ETag
+ skip_cache: bool
+ ref: FilePathStr | URIStr | None
+ birth_artifact_id: str | None
+ size: int | None
+ extra: dict
+ local_path: str | None
+
+ _parent_artifact: Artifact | None = None
+ _download_url: str | None = None
+
+ def __init__(
+ self,
+ path: StrPath,
+ digest: B64MD5 | URIStr | FilePathStr | ETag,
+ skip_cache: bool | None = False,
+ ref: FilePathStr | URIStr | None = None,
+ birth_artifact_id: str | None = None,
+ size: int | None = None,
+ extra: dict | None = None,
+ local_path: StrPath | None = None,
+ ) -> None:
+ self.path = LogicalPath(path)
+ self.digest = digest
+ self.ref = ref
+ self.birth_artifact_id = birth_artifact_id
+ self.size = size
+ self.extra = extra or {}
+ self.local_path = str(local_path) if local_path else None
+ if self.local_path and self.size is None:
+ self.size = Path(self.local_path).stat().st_size
+ self.skip_cache = skip_cache or False
+
+ def __repr__(self) -> str:
+ cls = self.__class__.__name__
+ ref = f", ref={self.ref!r}" if self.ref is not None else ""
+ birth_artifact_id = (
+ f", birth_artifact_id={self.birth_artifact_id!r}"
+ if self.birth_artifact_id is not None
+ else ""
+ )
+ size = f", size={self.size}" if self.size is not None else ""
+ extra = f", extra={json.dumps(self.extra)}" if self.extra else ""
+ local_path = f", local_path={self.local_path!r}" if self.local_path else ""
+ skip_cache = f", skip_cache={self.skip_cache}"
+ others = ref + birth_artifact_id + size + extra + local_path + skip_cache
+ return f"{cls}(path={self.path!r}, digest={self.digest!r}{others})"
+
+ def __eq__(self, other: object) -> bool:
+ """Strict equality, comparing all public fields.
+
+ ArtifactManifestEntries for the same file may not compare equal if they were
+ added in different ways or created for different parent artifacts.
+ """
+ if not isinstance(other, ArtifactManifestEntry):
+ return False
+ return (
+ self.path == other.path
+ and self.digest == other.digest
+ and self.ref == other.ref
+ and self.birth_artifact_id == other.birth_artifact_id
+ and self.size == other.size
+ and self.extra == other.extra
+ and self.local_path == other.local_path
+ and self.skip_cache == other.skip_cache
+ )
+
+ @property
+ def name(self) -> LogicalPath:
+ """Deprecated; use `path` instead."""
+ deprecate(
+ field_name=Deprecated.artifactmanifestentry__name,
+ warning_message="ArtifactManifestEntry.name is deprecated, use .path instead.",
+ )
+ return self.path
+
+ def parent_artifact(self) -> Artifact:
+ """Get the artifact to which this artifact entry belongs.
+
+ Returns:
+ (PublicArtifact): The parent artifact
+ """
+ if self._parent_artifact is None:
+ raise NotImplementedError
+ return self._parent_artifact
+
+ def download(
+ self,
+ root: str | None = None,
+ skip_cache: bool | None = None,
+ executor: concurrent.futures.Executor | None = None,
+ ) -> FilePathStr:
+ """Download this artifact entry to the specified root path.
+
+ Args:
+ root: (str, optional) The root path in which to download this
+ artifact entry. Defaults to the artifact's root.
+
+ Returns:
+ (str): The path of the downloaded artifact entry.
+ """
+ artifact = self.parent_artifact()
+
+ root = root or artifact._default_root()
+ artifact._add_download_root(root)
+ path = str(Path(self.path))
+ dest_path = os.path.join(root, path)
+
+ if skip_cache:
+ override_cache_path = dest_path
+ else:
+ override_cache_path = None
+
+ # Skip checking the cache (and possibly downloading) if the file already exists
+ # and has the digest we're expecting.
+
+ # Fast integrity check using cached checksum from persistent cache
+ with suppress(OSError):
+ if self.digest == _read_cached_checksum(dest_path):
+ return FilePathStr(dest_path)
+
+ # Fallback to computing/caching the checksum hash
+ try:
+ md5_hash = md5_file_b64(dest_path)
+ except (FileNotFoundError, IsADirectoryError):
+ logger.debug(f"unable to find {dest_path!r}, skip searching for file")
+ else:
+ _write_cached_checksum(dest_path, md5_hash)
+ if self.digest == md5_hash:
+ return FilePathStr(dest_path)
+
+ if self.ref is not None:
+ cache_path = artifact.manifest.storage_policy.load_reference(
+ self, local=True, dest_path=override_cache_path
+ )
+ else:
+ cache_path = artifact.manifest.storage_policy.load_file(
+ artifact, self, dest_path=override_cache_path, executor=executor
+ )
+
+ # Determine the final path
+ final_path = (
+ dest_path
+ if skip_cache
+ else copy_or_overwrite_changed(cache_path, dest_path)
+ )
+
+ # Cache the checksum for future downloads
+ _write_cached_checksum(str(final_path), self.digest)
+
+ return FilePathStr(final_path)
+
+ def ref_target(self) -> FilePathStr | URIStr:
+ """Get the reference URL that is targeted by this artifact entry.
+
+ Returns:
+ (str): The reference URL of this artifact entry.
+
+ Raises:
+ ValueError: If this artifact entry was not a reference.
+ """
+ if self.ref is None:
+ raise ValueError("Only reference entries support ref_target().")
+ if self._parent_artifact is None:
+ return self.ref
+ return self._parent_artifact.manifest.storage_policy.load_reference(
+ self._parent_artifact.manifest.entries[self.path], local=False
+ )
+
+ def ref_url(self) -> str:
+ """Get a URL to this artifact entry.
+
+ These URLs can be referenced by another artifact.
+
+ Returns:
+ (str): A URL representing this artifact entry.
+
+ Examples:
+ Basic usage
+ ```
+ ref_url = source_artifact.get_entry("file.txt").ref_url()
+ derived_artifact.add_reference(ref_url)
+ ```
+ """
+ if (parent_artifact := self.parent_artifact()) is None:
+ raise ValueError("Parent artifact is not set")
+ elif (parent_id := parent_artifact.id) is None:
+ raise ValueError("Parent artifact ID is not set")
+ return f"{_WB_ARTIFACT_SCHEME}://{b64_to_hex_id(B64MD5(parent_id))}/{self.path}"
+
+ def to_json(self) -> ArtifactManifestEntryDict:
+ contents: ArtifactManifestEntryDict = {
+ "path": self.path,
+ "digest": self.digest,
+ }
+ if self.size is not None:
+ contents["size"] = self.size
+ if self.ref:
+ contents["ref"] = self.ref
+ if self.birth_artifact_id:
+ contents["birthArtifactID"] = self.birth_artifact_id
+ if self.local_path:
+ contents["local_path"] = self.local_path
+ if self.skip_cache:
+ contents["skip_cache"] = self.skip_cache
+ if self.extra:
+ contents["extra"] = self.extra
+ return contents
+
+ def _is_artifact_reference(self) -> bool:
+ return self.ref is not None and urlparse(self.ref).scheme == _WB_ARTIFACT_SCHEME
+
+ def _referenced_artifact_id(self) -> str | None:
+ if not self._is_artifact_reference():
+ return None
+ return hex_to_b64_id(urlparse(self.ref).netloc)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifests/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifests/artifact_manifest_v1.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifests/artifact_manifest_v1.py
new file mode 100644
index 0000000000000000000000000000000000000000..62edaa2006385e3d0113341159c9453e33fb5782
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifests/artifact_manifest_v1.py
@@ -0,0 +1,94 @@
+"""Artifact manifest v1."""
+
+from __future__ import annotations
+
+from operator import itemgetter
+from typing import Any, Mapping
+
+from wandb.sdk.artifacts.artifact_manifest import ArtifactManifest
+from wandb.sdk.artifacts.artifact_manifest_entry import ArtifactManifestEntry
+from wandb.sdk.artifacts.storage_policy import StoragePolicy
+from wandb.sdk.internal.internal_api import Api as InternalApi
+from wandb.sdk.lib.hashutil import HexMD5, _md5
+
+
+class ArtifactManifestV1(ArtifactManifest):
+ @classmethod
+ def version(cls) -> int:
+ return 1
+
+ @classmethod
+ def from_manifest_json(
+ cls, manifest_json: dict, api: InternalApi | None = None
+ ) -> ArtifactManifestV1:
+ if manifest_json["version"] != cls.version():
+ raise ValueError(
+ "Expected manifest version 1, got {}".format(manifest_json["version"])
+ )
+
+ storage_policy_name = manifest_json["storagePolicy"]
+ storage_policy_config = manifest_json.get("storagePolicyConfig", {})
+ storage_policy_cls = StoragePolicy.lookup_by_name(storage_policy_name)
+
+ entries: Mapping[str, ArtifactManifestEntry]
+ entries = {
+ name: ArtifactManifestEntry(
+ path=name,
+ digest=val["digest"],
+ birth_artifact_id=val.get("birthArtifactID"),
+ ref=val.get("ref"),
+ size=val.get("size"),
+ extra=val.get("extra"),
+ local_path=val.get("local_path"),
+ skip_cache=val.get("skip_cache"),
+ )
+ for name, val in manifest_json["contents"].items()
+ }
+
+ return cls(
+ storage_policy_cls.from_config(storage_policy_config, api=api), entries
+ )
+
+ def __init__(
+ self,
+ storage_policy: StoragePolicy,
+ entries: Mapping[str, ArtifactManifestEntry] | None = None,
+ ) -> None:
+ super().__init__(storage_policy, entries=entries)
+
+ def to_manifest_json(self) -> dict:
+ """This is the JSON that's stored in wandb_manifest.json.
+
+ If include_local is True we also include the local paths to files. This is
+ used to represent an artifact that's waiting to be saved on the current
+ system. We don't need to include the local paths in the artifact manifest
+ contents.
+ """
+ contents = {}
+ for name, entry in sorted(self.entries.items(), key=itemgetter(0)):
+ json_entry: dict[str, Any] = {
+ "digest": entry.digest,
+ }
+ if entry.birth_artifact_id:
+ json_entry["birthArtifactID"] = entry.birth_artifact_id
+ if entry.ref:
+ json_entry["ref"] = entry.ref
+ if entry.extra:
+ json_entry["extra"] = entry.extra
+ if entry.size is not None:
+ json_entry["size"] = entry.size
+ contents[name] = json_entry
+ return {
+ "version": self.__class__.version(),
+ "storagePolicy": self.storage_policy.name(),
+ "storagePolicyConfig": self.storage_policy.config() or {},
+ "contents": contents,
+ }
+
+ def digest(self) -> HexMD5:
+ hasher = _md5()
+ hasher.update(b"wandb-artifact-manifest-v1\n")
+ # sort by key (path)
+ for name, entry in sorted(self.entries.items(), key=itemgetter(0)):
+ hasher.update(f"{name}:{entry.digest}\n".encode())
+ return HexMD5(hasher.hexdigest())
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_saver.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_saver.py
new file mode 100644
index 0000000000000000000000000000000000000000..e163f150060f553cf22ce5dd9916dcc3868d4830
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_saver.py
@@ -0,0 +1,277 @@
+"""Artifact saver."""
+
+from __future__ import annotations
+
+import concurrent.futures
+import json
+import os
+import tempfile
+from typing import TYPE_CHECKING, Awaitable, Sequence
+
+import wandb
+import wandb.filesync.step_prepare
+from wandb import util
+from wandb.sdk.artifacts.artifact_manifest import ArtifactManifest
+from wandb.sdk.lib.hashutil import B64MD5, b64_to_hex_id, md5_file_b64
+from wandb.sdk.lib.paths import URIStr
+
+if TYPE_CHECKING:
+ from typing import Protocol
+
+ from wandb.sdk.artifacts.artifact_manifest_entry import ArtifactManifestEntry
+ from wandb.sdk.internal.file_pusher import FilePusher
+ from wandb.sdk.internal.internal_api import Api as InternalApi
+ from wandb.sdk.internal.progress import ProgressFn
+
+ class SaveFn(Protocol):
+ def __call__(
+ self, entry: ArtifactManifestEntry, progress_callback: ProgressFn
+ ) -> bool:
+ pass
+
+ class SaveFnAsync(Protocol):
+ def __call__(
+ self, entry: ArtifactManifestEntry, progress_callback: ProgressFn
+ ) -> Awaitable[bool]:
+ pass
+
+
+class ArtifactSaver:
+ _server_artifact: dict | None # TODO better define this dict
+
+ def __init__(
+ self,
+ api: InternalApi,
+ digest: str,
+ manifest_json: dict,
+ file_pusher: FilePusher,
+ is_user_created: bool = False,
+ ) -> None:
+ self._api = api
+ self._file_pusher = file_pusher
+ self._digest = digest
+ self._manifest = ArtifactManifest.from_manifest_json(
+ manifest_json,
+ api=self._api,
+ )
+ self._is_user_created = is_user_created
+ self._server_artifact = None
+
+ def save(
+ self,
+ entity: str,
+ project: str,
+ type: str,
+ name: str,
+ client_id: str,
+ sequence_client_id: str,
+ distributed_id: str | None = None,
+ finalize: bool = True,
+ metadata: dict | None = None,
+ ttl_duration_seconds: int | None = None,
+ description: str | None = None,
+ aliases: Sequence[str] | None = None,
+ tags: Sequence[str] | None = None,
+ use_after_commit: bool = False,
+ incremental: bool = False,
+ history_step: int | None = None,
+ base_id: str | None = None,
+ ) -> dict | None:
+ return self._save_internal(
+ entity,
+ project,
+ type,
+ name,
+ client_id,
+ sequence_client_id,
+ distributed_id,
+ finalize,
+ metadata,
+ ttl_duration_seconds,
+ description,
+ aliases,
+ tags,
+ use_after_commit,
+ incremental,
+ history_step,
+ base_id,
+ )
+
+ def _save_internal(
+ self,
+ entity: str,
+ project: str,
+ type: str,
+ name: str,
+ client_id: str,
+ sequence_client_id: str,
+ distributed_id: str | None = None,
+ finalize: bool = True,
+ metadata: dict | None = None,
+ ttl_duration_seconds: int | None = None,
+ description: str | None = None,
+ aliases: Sequence[str] | None = None,
+ tags: Sequence[str] | None = None,
+ use_after_commit: bool = False,
+ incremental: bool = False,
+ history_step: int | None = None,
+ base_id: str | None = None,
+ ) -> dict | None:
+ alias_specs = []
+ for alias in aliases or []:
+ alias_specs.append({"artifactCollectionName": name, "alias": alias})
+
+ tag_specs = [{"tagName": tag} for tag in tags or []]
+
+ """Returns the server artifact."""
+ self._server_artifact, latest = self._api.create_artifact(
+ type,
+ name,
+ self._digest,
+ metadata=metadata,
+ ttl_duration_seconds=ttl_duration_seconds,
+ aliases=alias_specs,
+ tags=tag_specs,
+ description=description,
+ is_user_created=self._is_user_created,
+ distributed_id=distributed_id,
+ client_id=client_id,
+ sequence_client_id=sequence_client_id,
+ history_step=history_step,
+ )
+
+ assert self._server_artifact is not None # mypy optionality unwrapper
+ artifact_id = self._server_artifact["id"]
+ if base_id is None and latest:
+ base_id = latest["id"]
+ if self._server_artifact["state"] == "COMMITTED":
+ if use_after_commit:
+ self._api.use_artifact(
+ artifact_id,
+ artifact_entity_name=entity,
+ artifact_project_name=project,
+ )
+ return self._server_artifact
+ if (
+ self._server_artifact["state"] != "PENDING"
+ # For old servers, see https://github.com/wandb/wandb/pull/6190
+ and self._server_artifact["state"] != "DELETED"
+ ):
+ raise Exception(
+ 'Unknown artifact state "{}"'.format(self._server_artifact["state"])
+ )
+
+ manifest_type = "FULL"
+ manifest_filename = "wandb_manifest.json"
+ if incremental:
+ manifest_type = "INCREMENTAL"
+ manifest_filename = "wandb_manifest.incremental.json"
+ elif distributed_id:
+ manifest_type = "PATCH"
+ manifest_filename = "wandb_manifest.patch.json"
+ artifact_manifest_id, _ = self._api.create_artifact_manifest(
+ manifest_filename,
+ "",
+ artifact_id,
+ base_artifact_id=base_id,
+ include_upload=False,
+ type=manifest_type,
+ )
+
+ step_prepare = wandb.filesync.step_prepare.StepPrepare(
+ self._api, 0.1, 0.01, 1000
+ ) # TODO: params
+ step_prepare.start()
+
+ # Upload Artifact "L1" files, the actual artifact contents
+ self._file_pusher.store_manifest_files(
+ self._manifest,
+ artifact_id,
+ lambda entry, progress_callback: self._manifest.storage_policy.store_file(
+ artifact_id,
+ artifact_manifest_id,
+ entry,
+ step_prepare,
+ progress_callback=progress_callback,
+ ),
+ )
+
+ def before_commit() -> None:
+ self._resolve_client_id_manifest_references()
+ with tempfile.NamedTemporaryFile("w+", suffix=".json", delete=False) as fp:
+ path = os.path.abspath(fp.name)
+ json.dump(self._manifest.to_manifest_json(), fp, indent=4)
+ digest = md5_file_b64(path)
+ if distributed_id or incremental:
+ # If we're in the distributed flow, we want to update the
+ # patch manifest we created with our finalized digest.
+ _, resp = self._api.update_artifact_manifest(
+ artifact_manifest_id,
+ digest=digest,
+ )
+ else:
+ # In the regular flow, we can recreate the full manifest with the
+ # updated digest.
+ #
+ # NOTE: We do this for backwards compatibility with older backends
+ # that don't support the 'updateArtifactManifest' API.
+ _, resp = self._api.create_artifact_manifest(
+ manifest_filename,
+ digest,
+ artifact_id,
+ base_artifact_id=base_id,
+ )
+
+ # We're duplicating the file upload logic a little, which isn't great.
+ upload_url = resp["uploadUrl"]
+ upload_headers = resp["uploadHeaders"]
+ extra_headers = {}
+ for upload_header in upload_headers:
+ key, val = upload_header.split(":", 1)
+ extra_headers[key] = val
+ with open(path, "rb") as fp2:
+ self._api.upload_file_retry(
+ upload_url,
+ fp2,
+ extra_headers=extra_headers,
+ )
+
+ commit_result: concurrent.futures.Future[None] = concurrent.futures.Future()
+
+ # This will queue the commit. It will only happen after all the file uploads are done
+ self._file_pusher.commit_artifact(
+ artifact_id,
+ finalize=finalize,
+ before_commit=before_commit,
+ result_future=commit_result,
+ )
+
+ # Block until all artifact files are uploaded and the
+ # artifact is committed.
+ try:
+ commit_result.result()
+ finally:
+ step_prepare.shutdown()
+
+ if finalize and use_after_commit:
+ self._api.use_artifact(
+ artifact_id,
+ artifact_entity_name=entity,
+ artifact_project_name=project,
+ )
+
+ return self._server_artifact
+
+ def _resolve_client_id_manifest_references(self) -> None:
+ for entry_path in self._manifest.entries:
+ entry = self._manifest.entries[entry_path]
+ if entry.ref is not None:
+ if entry.ref.startswith("wandb-client-artifact:"):
+ client_id = util.host_from_path(entry.ref)
+ artifact_file_path = util.uri_from_path(entry.ref)
+ artifact_id = self._api._resolve_client_id(client_id)
+ if artifact_id is None:
+ raise RuntimeError(f"Could not resolve client id {client_id}")
+ entry.ref = URIStr(
+ f"wandb-artifact://{b64_to_hex_id(B64MD5(artifact_id))}/{artifact_file_path}"
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_state.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_state.py
new file mode 100644
index 0000000000000000000000000000000000000000..4df836c8b60e482e3de8a103b4b0e646800922a7
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_state.py
@@ -0,0 +1,13 @@
+"""Artifact state."""
+
+from __future__ import annotations
+
+from enum import Enum
+
+
+class ArtifactState(Enum):
+ PENDING = "PENDING"
+ COMMITTED = "COMMITTED"
+ DELETED = "DELETED"
+ GARBAGE_COLLECTED = "GARBAGE_COLLECTED"
+ PENDING_DELETION = "PENDING_DELETION"
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_ttl.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_ttl.py
new file mode 100644
index 0000000000000000000000000000000000000000..e63c69031923aa36a2214526443861497f3575d6
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/artifact_ttl.py
@@ -0,0 +1,9 @@
+"""Artifact TTL."""
+
+from __future__ import annotations
+
+from enum import Enum
+
+
+class ArtifactTTL(Enum):
+ INHERIT = 0
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/exceptions.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f8919ae619106730a2cdbb639a1d06e50ec8011
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/exceptions.py
@@ -0,0 +1,72 @@
+"""Artifact exceptions."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, TypeVar
+
+from wandb import errors
+from wandb._strutils import nameof
+
+if TYPE_CHECKING:
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ ArtifactT = TypeVar("ArtifactT", bound=Artifact)
+
+
+class ArtifactStatusError(AttributeError):
+ """Raised when an artifact is in an invalid state for the requested operation."""
+
+ def __init__(
+ self,
+ msg: str = "Artifact is in an invalid state for the requested operation.",
+ name: str | None = None,
+ obj: ArtifactT | None = None,
+ ):
+ # Follow the same pattern as AttributeError in python 3.10+ by `name/obj` attributes
+ # See: https://docs.python.org/3/library/exceptions.html#AttributeError
+ try:
+ super().__init__(msg, name=name, obj=obj)
+ except TypeError:
+ # The `name`/`obj` keyword args and attributes were only added in python >= 3.10
+ super().__init__(msg)
+ self.name = name or ""
+ self.obj = obj
+
+
+class ArtifactNotLoggedError(ArtifactStatusError):
+ """Raised for Artifact methods or attributes only available after logging."""
+
+ def __init__(self, fullname: str, obj: ArtifactT):
+ *_, name = fullname.split(".")
+ msg = (
+ f"{fullname!r} used prior to logging artifact or while in offline mode. "
+ f"Call {nameof(obj.wait)}() before accessing logged artifact properties."
+ )
+ super().__init__(msg=msg, name=name, obj=obj)
+
+
+class ArtifactFinalizedError(ArtifactStatusError):
+ """Raised for Artifact methods or attributes that can't be changed after logging."""
+
+ def __init__(self, fullname: str, obj: ArtifactT):
+ *_, name = fullname.split(".")
+ msg = f"{fullname!r} used on logged artifact. Can't modify finalized artifact."
+ super().__init__(msg=msg, name=name, obj=obj)
+
+
+class WaitTimeoutError(errors.Error):
+ """Raised when wait() timeout occurs before process is finished."""
+
+
+class TooFewItemsError(ValueError):
+ """Raised when there are fewer items than expected in a collection.
+
+ Intended for internal use only.
+ """
+
+
+class TooManyItemsError(ValueError):
+ """Raised when there are more items than expected in a collection.
+
+ Intended for internal use only.
+ """
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/staging.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/staging.py
new file mode 100644
index 0000000000000000000000000000000000000000..24a6313ca0507d1f4ee110570c80062644c08cb9
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/staging.py
@@ -0,0 +1,27 @@
+"""Manages artifact file staging.
+
+Artifact files are copied to the staging area as soon as they are added to an artifact
+in order to avoid file changes corrupting the artifact. Once the upload is complete, the
+file should be moved to the artifact cache.
+"""
+
+from __future__ import annotations
+
+import os
+
+from wandb import env
+from wandb.sdk.lib.filesystem import mkdir_exists_ok
+from wandb.sdk.lib.paths import FilePathStr
+
+
+def get_staging_dir() -> FilePathStr:
+ path = os.path.join(env.get_data_dir(), "artifacts", "staging")
+ try:
+ mkdir_exists_ok(path)
+ except OSError as e:
+ raise PermissionError(
+ f"Unable to write staging files to {path}. To fix this problem, please set "
+ f"{env.DATA_DIR} to a directory where you have the necessary write access."
+ ) from e
+
+ return FilePathStr(os.path.abspath(os.path.expanduser(path)))
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handler.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handler.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1883e5144cf8bf602b11a7012c0a85cb1025979
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handler.py
@@ -0,0 +1,68 @@
+"""Storage handler."""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING, Final
+
+from wandb.sdk.lib.paths import FilePathStr, URIStr
+
+if TYPE_CHECKING:
+ from urllib.parse import ParseResult
+
+ from wandb.sdk.artifacts.artifact import Artifact
+ from wandb.sdk.artifacts.artifact_manifest_entry import ArtifactManifestEntry
+
+DEFAULT_MAX_OBJECTS: Final[int] = 10_000_000 # 10**7
+
+
+class _BaseStorageHandler(ABC):
+ @abstractmethod
+ def load_path(
+ self,
+ manifest_entry: ArtifactManifestEntry,
+ local: bool = False,
+ ) -> URIStr | FilePathStr:
+ """Load a file or directory given the corresponding index entry.
+
+ Args:
+ manifest_entry: The index entry to load
+ local: Whether to load the file locally or not
+
+ Returns:
+ A path to the file represented by `index_entry`
+ """
+ raise NotImplementedError
+
+ @abstractmethod
+ def store_path(
+ self,
+ artifact: Artifact,
+ path: URIStr | FilePathStr,
+ name: str | None = None,
+ checksum: bool = True,
+ max_objects: int | None = None,
+ ) -> list[ArtifactManifestEntry]:
+ """Store the file or directory at the given path to the specified artifact.
+
+ Args:
+ path: The path to store
+ name: If specified, the logical name that should map to `path`
+ checksum: Whether to compute the checksum of the file
+ max_objects: The maximum number of objects to store
+
+ Returns:
+ A list of manifest entries to store within the artifact
+ """
+ raise NotImplementedError
+
+
+class StorageHandler(_BaseStorageHandler, ABC): # Handles a single storage protocol
+ @abstractmethod
+ def can_handle(self, parsed_url: ParseResult) -> bool:
+ """Checks whether this handler can handle the given url.
+
+ Returns:
+ Whether this handler can handle the given url.
+ """
+ raise NotImplementedError
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/azure_handler.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/azure_handler.py
new file mode 100644
index 0000000000000000000000000000000000000000..b49657515b06c02464a35df270f0ed983186f935
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/azure_handler.py
@@ -0,0 +1,219 @@
+"""Azure storage handler."""
+
+from __future__ import annotations
+
+from pathlib import PurePosixPath
+from types import ModuleType
+from typing import TYPE_CHECKING
+from urllib.parse import ParseResult, parse_qsl, urlparse
+
+import wandb
+from wandb import util
+from wandb.sdk.artifacts.artifact_file_cache import get_artifact_file_cache
+from wandb.sdk.artifacts.artifact_manifest_entry import ArtifactManifestEntry
+from wandb.sdk.artifacts.storage_handler import DEFAULT_MAX_OBJECTS, StorageHandler
+from wandb.sdk.lib.hashutil import ETag
+from wandb.sdk.lib.paths import FilePathStr, LogicalPath, StrPath, URIStr
+
+if TYPE_CHECKING:
+ import azure.identity # type: ignore
+ import azure.storage.blob # type: ignore
+
+ from wandb.sdk.artifacts.artifact import Artifact
+ from wandb.sdk.artifacts.artifact_file_cache import ArtifactFileCache
+
+
+class AzureHandler(StorageHandler):
+ _scheme: str
+ _cache: ArtifactFileCache
+
+ def __init__(self, scheme: str = "https") -> None:
+ self._scheme = scheme
+ self._cache = get_artifact_file_cache()
+
+ def can_handle(self, parsed_url: ParseResult) -> bool:
+ return parsed_url.scheme == self._scheme and parsed_url.netloc.endswith(
+ ".blob.core.windows.net"
+ )
+
+ def load_path(
+ self,
+ manifest_entry: ArtifactManifestEntry,
+ local: bool = False,
+ ) -> URIStr | FilePathStr:
+ assert manifest_entry.ref is not None
+ if not local:
+ return manifest_entry.ref
+
+ path, hit, cache_open = self._cache.check_etag_obj_path(
+ URIStr(manifest_entry.ref),
+ ETag(manifest_entry.digest),
+ manifest_entry.size or 0,
+ )
+ if hit:
+ return path
+
+ account_url, container_name, blob_name, query = self._parse_uri(
+ manifest_entry.ref
+ )
+ version_id = manifest_entry.extra.get("versionID")
+ blob_service_client = self._get_module("azure.storage.blob").BlobServiceClient(
+ account_url, credential=self._get_credential(account_url)
+ )
+ blob_client = blob_service_client.get_blob_client(
+ container=container_name, blob=blob_name
+ )
+ if version_id is None:
+ # Try current version, then all versions.
+ try:
+ downloader = blob_client.download_blob(
+ etag=manifest_entry.digest,
+ match_condition=self._get_module(
+ "azure.core"
+ ).MatchConditions.IfNotModified,
+ )
+ except self._get_module("azure.core.exceptions").ResourceModifiedError:
+ container_client = blob_service_client.get_container_client(
+ container_name
+ )
+ for blob_properties in container_client.walk_blobs(
+ name_starts_with=blob_name, include=["versions"]
+ ):
+ if (
+ blob_properties.name == blob_name
+ and blob_properties.etag == manifest_entry.digest
+ and blob_properties.version_id is not None
+ ):
+ downloader = blob_client.download_blob(
+ version_id=blob_properties.version_id
+ )
+ break
+ else: # didn't break
+ raise ValueError(
+ f"Couldn't find blob version for {manifest_entry.ref} matching "
+ f"etag {manifest_entry.digest}."
+ )
+ else:
+ downloader = blob_client.download_blob(version_id=version_id)
+ with cache_open(mode="wb") as f:
+ downloader.readinto(f)
+ return path
+
+ def store_path(
+ self,
+ artifact: Artifact,
+ path: URIStr | FilePathStr,
+ name: StrPath | None = None,
+ checksum: bool = True,
+ max_objects: int | None = None,
+ ) -> list[ArtifactManifestEntry]:
+ account_url, container_name, blob_name, query = self._parse_uri(path)
+ path = URIStr(f"{account_url}/{container_name}/{blob_name}")
+
+ if not checksum:
+ return [
+ ArtifactManifestEntry(path=name or blob_name, digest=path, ref=path)
+ ]
+
+ blob_service_client = self._get_module("azure.storage.blob").BlobServiceClient(
+ account_url, credential=self._get_credential(account_url)
+ )
+ blob_client = blob_service_client.get_blob_client(
+ container=container_name, blob=blob_name
+ )
+ if blob_client.exists(version_id=query.get("versionId")):
+ blob_properties = blob_client.get_blob_properties(
+ version_id=query.get("versionId")
+ )
+
+ if not self._is_directory_stub(blob_properties):
+ return [
+ self._create_entry(
+ blob_properties,
+ path=name or PurePosixPath(blob_name).name,
+ ref=URIStr(
+ f"{account_url}/{container_name}/{blob_properties.name}"
+ ),
+ )
+ ]
+
+ entries: list[ArtifactManifestEntry] = []
+ container_client = blob_service_client.get_container_client(container_name)
+ max_objects = max_objects or DEFAULT_MAX_OBJECTS
+ for blob_properties in container_client.list_blobs(
+ name_starts_with=f"{blob_name}/"
+ ):
+ if len(entries) >= max_objects:
+ wandb.termwarn(
+ f"Found more than {max_objects} objects under path, limiting upload "
+ f"to {max_objects} objects. Increase max_objects to upload more"
+ )
+ break
+ if not self._is_directory_stub(blob_properties):
+ suffix = PurePosixPath(blob_properties.name).relative_to(blob_name)
+ entries.append(
+ self._create_entry(
+ blob_properties,
+ path=LogicalPath(name) / suffix if name else suffix,
+ ref=URIStr(
+ f"{account_url}/{container_name}/{blob_properties.name}"
+ ),
+ )
+ )
+
+ return entries
+
+ def _get_module(self, name: str) -> ModuleType:
+ module = util.get_module(
+ name,
+ lazy=False,
+ required="Azure references require the azure library, run "
+ "pip install wandb[azure]",
+ )
+ assert isinstance(module, ModuleType)
+ return module
+
+ def _get_credential(
+ self, account_url: str
+ ) -> azure.identity.DefaultAzureCredential | str:
+ # NOTE: Always returns default credential for reinit="create_new" runs.
+ if (
+ wandb.run
+ and wandb.run.settings.azure_account_url_to_access_key is not None
+ and account_url in wandb.run.settings.azure_account_url_to_access_key
+ ):
+ return wandb.run.settings.azure_account_url_to_access_key[account_url]
+ return self._get_module("azure.identity").DefaultAzureCredential()
+
+ def _parse_uri(self, uri: str) -> tuple[str, str, str, dict[str, str]]:
+ parsed_url = urlparse(uri)
+ query = dict(parse_qsl(parsed_url.query))
+ account_url = f"{parsed_url.scheme}://{parsed_url.netloc}"
+ _, container_name, blob_name = parsed_url.path.split("/", 2)
+ return account_url, container_name, blob_name, query
+
+ def _create_entry(
+ self,
+ blob_properties: azure.storage.blob.BlobProperties,
+ path: StrPath,
+ ref: URIStr,
+ ) -> ArtifactManifestEntry:
+ extra = {"etag": blob_properties.etag.strip('"')}
+ if blob_properties.version_id:
+ extra["versionID"] = blob_properties.version_id
+ return ArtifactManifestEntry(
+ path=path,
+ ref=ref,
+ digest=blob_properties.etag.strip('"'),
+ size=blob_properties.size,
+ extra=extra,
+ )
+
+ def _is_directory_stub(
+ self, blob_properties: azure.storage.blob.BlobProperties
+ ) -> bool:
+ return (
+ blob_properties.has_key("metadata")
+ and "hdi_isfolder" in blob_properties.metadata
+ and blob_properties.metadata["hdi_isfolder"] == "true"
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/gcs_handler.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/gcs_handler.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a2f0f6fa36282d72a4e72439d989e683f79d544
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/gcs_handler.py
@@ -0,0 +1,227 @@
+"""GCS storage handler."""
+
+from __future__ import annotations
+
+import time
+from pathlib import PurePosixPath
+from typing import TYPE_CHECKING
+from urllib.parse import ParseResult, urlparse
+
+from wandb import util
+from wandb.errors.term import termlog
+from wandb.sdk.artifacts.artifact_file_cache import get_artifact_file_cache
+from wandb.sdk.artifacts.artifact_manifest_entry import ArtifactManifestEntry
+from wandb.sdk.artifacts.storage_handler import DEFAULT_MAX_OBJECTS, StorageHandler
+from wandb.sdk.lib.hashutil import ETag
+from wandb.sdk.lib.paths import FilePathStr, StrPath, URIStr
+
+if TYPE_CHECKING:
+ import google.cloud.storage as gcs_module # type: ignore
+
+ from wandb.sdk.artifacts.artifact import Artifact
+ from wandb.sdk.artifacts.artifact_file_cache import ArtifactFileCache
+
+
+class _GCSIsADirectoryError(Exception):
+ """Raised when we try to download a GCS folder."""
+
+
+class GCSHandler(StorageHandler):
+ _scheme: str
+ _client: gcs_module.client.Client | None
+ _cache: ArtifactFileCache
+
+ def __init__(self, scheme: str = "gs") -> None:
+ self._scheme = scheme
+ self._client = None
+ self._cache = get_artifact_file_cache()
+
+ def can_handle(self, parsed_url: ParseResult) -> bool:
+ return parsed_url.scheme == self._scheme
+
+ def init_gcs(self) -> gcs_module.client.Client:
+ if self._client is not None:
+ return self._client
+ storage = util.get_module(
+ "google.cloud.storage",
+ required="gs:// references requires the google-cloud-storage library, run pip install wandb[gcp]",
+ )
+ self._client = storage.Client()
+ return self._client
+
+ def _parse_uri(self, uri: str) -> tuple[str, str, str | None]:
+ url = urlparse(uri)
+ bucket = url.netloc
+ key = url.path[1:]
+ version = url.fragment if url.fragment else None
+ return bucket, key, version
+
+ def load_path(
+ self,
+ manifest_entry: ArtifactManifestEntry,
+ local: bool = False,
+ ) -> URIStr | FilePathStr:
+ assert manifest_entry.ref is not None
+ if not local:
+ return manifest_entry.ref
+
+ path, hit, cache_open = self._cache.check_etag_obj_path(
+ url=URIStr(manifest_entry.ref),
+ etag=ETag(manifest_entry.digest),
+ size=manifest_entry.size or 0,
+ )
+ if hit:
+ return path
+
+ self.init_gcs()
+ assert self._client is not None # mypy: unwraps optionality
+ assert manifest_entry.ref is not None
+ bucket, key, _ = self._parse_uri(manifest_entry.ref)
+ version = manifest_entry.extra.get("versionID")
+
+ if self._is_dir(manifest_entry):
+ raise _GCSIsADirectoryError(
+ f"Unable to download GCS folder {manifest_entry.ref!r}, skipping"
+ )
+
+ obj = None
+ # First attempt to get the generation specified, this will return None if versioning is not enabled
+ if version is not None:
+ obj = self._client.bucket(bucket).get_blob(key, generation=version)
+
+ if obj is None:
+ # Object versioning is disabled on the bucket, so just get
+ # the latest version and make sure the MD5 matches.
+ obj = self._client.bucket(bucket).get_blob(key)
+ if obj is None:
+ raise ValueError(
+ f"Unable to download object {manifest_entry.ref} with generation {version}"
+ )
+ if obj.etag != manifest_entry.digest:
+ raise ValueError(
+ f"Digest mismatch for object {manifest_entry.ref}: "
+ f"expected {manifest_entry.digest} but found {obj.etag}"
+ )
+
+ with cache_open(mode="wb") as f:
+ obj.download_to_file(f)
+ return path
+
+ def store_path(
+ self,
+ artifact: Artifact,
+ path: URIStr | FilePathStr,
+ name: StrPath | None = None,
+ checksum: bool = True,
+ max_objects: int | None = None,
+ ) -> list[ArtifactManifestEntry]:
+ self.init_gcs()
+ assert self._client is not None # mypy: unwraps optionality
+
+ # After parsing any query params / fragments for additional context,
+ # such as version identifiers, pare down the path to just the bucket
+ # and key.
+ bucket, key, version = self._parse_uri(path)
+ path = URIStr(f"{self._scheme}://{bucket}/{key}")
+ max_objects = max_objects or DEFAULT_MAX_OBJECTS
+
+ if not checksum:
+ return [ArtifactManifestEntry(path=name or key, ref=path, digest=path)]
+
+ start_time = None
+ obj = self._client.bucket(bucket).get_blob(key, generation=version)
+ if obj is None and version is not None:
+ raise ValueError(f"Object does not exist: {path}#{version}")
+ multi = obj is None
+ if multi:
+ start_time = time.monotonic()
+ termlog(
+ f'Generating checksum for up to {max_objects} objects with prefix "{key}"... ',
+ newline=False,
+ )
+ objects = self._client.bucket(bucket).list_blobs(
+ prefix=key, max_results=max_objects
+ )
+ else:
+ objects = [obj]
+
+ entries = [
+ self._entry_from_obj(obj, path, name, prefix=key, multi=multi)
+ for obj in objects
+ if not obj.name.endswith("/")
+ ]
+ if start_time is not None:
+ termlog("Done. %.1fs" % (time.monotonic() - start_time), prefix=False)
+ if len(entries) > max_objects:
+ raise ValueError(
+ f"Exceeded {max_objects} objects tracked, pass max_objects to add_reference"
+ )
+ return entries
+
+ def _entry_from_obj(
+ self,
+ obj: gcs_module.blob.Blob,
+ path: str,
+ name: StrPath | None = None,
+ prefix: str = "",
+ multi: bool = False,
+ ) -> ArtifactManifestEntry:
+ """Create an ArtifactManifestEntry from a GCS object.
+
+ Args:
+ obj: The GCS object
+ path: The GCS-style path (e.g.: "gs://bucket/file.txt")
+ name: The user assigned name, or None if not specified
+ prefix: The prefix to add (will be the same as `path` for directories)
+ multi: Whether or not this is a multi-object add.
+ """
+ bucket, key, _ = self._parse_uri(path)
+
+ # Always use posix paths, since that's what S3 uses.
+ posix_key = PurePosixPath(obj.name) # the bucket key
+ posix_path = PurePosixPath(bucket) / PurePosixPath(
+ key
+ ) # the path, with the scheme stripped
+ posix_prefix = PurePosixPath(prefix) # the prefix, if adding a prefix
+ posix_name = PurePosixPath(name or "")
+ posix_ref = posix_path
+
+ if name is None:
+ # We're adding a directory (prefix), so calculate a relative path.
+ if str(posix_prefix) in str(posix_key) and posix_prefix != posix_key:
+ posix_name = posix_key.relative_to(posix_prefix)
+ posix_ref = posix_path / posix_name
+ else:
+ posix_name = PurePosixPath(posix_key.name)
+ posix_ref = posix_path
+ elif multi:
+ # We're adding a directory with a name override.
+ relpath = posix_key.relative_to(posix_prefix)
+ posix_name = posix_name / relpath
+ posix_ref = posix_path / relpath
+ return ArtifactManifestEntry(
+ path=posix_name,
+ ref=URIStr(f"{self._scheme}://{posix_ref}"),
+ digest=obj.etag,
+ size=obj.size,
+ extra={"versionID": obj.generation},
+ )
+
+ def _is_dir(
+ self,
+ manifest_entry: ArtifactManifestEntry,
+ ) -> bool:
+ assert self._client is not None
+ assert manifest_entry.ref is not None
+ bucket, key, _ = self._parse_uri(manifest_entry.ref)
+ bucket_obj = self._client.bucket(bucket)
+ # A gcs bucket key should end with a forward slash on gcloud, but
+ # we save these refs without the forward slash in the manifest entry
+ # so we check the size and extension, make sure its not referring to
+ # an actual file with this reference, and that the ref with the slash
+ # exists on gcloud
+ return key.endswith("/") or (
+ not (manifest_entry.size or PurePosixPath(key).suffix)
+ and bucket_obj.get_blob(key) is None
+ and bucket_obj.get_blob(f"{key}/") is not None
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/http_handler.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/http_handler.py
new file mode 100644
index 0000000000000000000000000000000000000000..718c9a54898d367e32eeb9dba048e826b86195aa
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/http_handler.py
@@ -0,0 +1,117 @@
+"""HTTP storage handler."""
+
+from __future__ import annotations
+
+import os
+from typing import TYPE_CHECKING
+from urllib.parse import ParseResult
+
+from wandb.sdk.artifacts.artifact_file_cache import get_artifact_file_cache
+from wandb.sdk.artifacts.artifact_manifest_entry import ArtifactManifestEntry
+from wandb.sdk.artifacts.storage_handler import StorageHandler
+from wandb.sdk.internal.thread_local_settings import _thread_local_api_settings
+from wandb.sdk.lib.hashutil import ETag
+from wandb.sdk.lib.paths import FilePathStr, StrPath, URIStr
+
+if TYPE_CHECKING:
+ import requests
+ from requests.structures import CaseInsensitiveDict
+
+ from wandb.sdk.artifacts.artifact import Artifact
+ from wandb.sdk.artifacts.artifact_file_cache import ArtifactFileCache
+
+
+class HTTPHandler(StorageHandler):
+ _scheme: str
+ _cache: ArtifactFileCache
+ _session: requests.Session
+
+ def __init__(self, session: requests.Session, scheme: str = "http") -> None:
+ self._scheme = scheme
+ self._cache = get_artifact_file_cache()
+ self._session = session
+
+ def can_handle(self, parsed_url: ParseResult) -> bool:
+ return parsed_url.scheme == self._scheme
+
+ def load_path(
+ self,
+ manifest_entry: ArtifactManifestEntry,
+ local: bool = False,
+ ) -> URIStr | FilePathStr:
+ if not local:
+ assert manifest_entry.ref is not None
+ return manifest_entry.ref
+
+ assert manifest_entry.ref is not None
+
+ path, hit, cache_open = self._cache.check_etag_obj_path(
+ URIStr(manifest_entry.ref),
+ ETag(manifest_entry.digest),
+ manifest_entry.size or 0,
+ )
+ if hit:
+ return path
+
+ response = self._session.get(
+ manifest_entry.ref,
+ stream=True,
+ cookies=_thread_local_api_settings.cookies,
+ headers=_thread_local_api_settings.headers,
+ )
+
+ digest: ETag | FilePathStr | URIStr | None
+ digest, size, extra = self._entry_from_headers(response.headers)
+ digest = digest or manifest_entry.ref
+ if manifest_entry.digest != digest:
+ raise ValueError(
+ f"Digest mismatch for url {manifest_entry.ref}: expected {manifest_entry.digest} but found {digest}"
+ )
+
+ with cache_open(mode="wb") as file:
+ for data in response.iter_content(chunk_size=16 * 1024):
+ file.write(data)
+ return path
+
+ def store_path(
+ self,
+ artifact: Artifact,
+ path: URIStr | FilePathStr,
+ name: StrPath | None = None,
+ checksum: bool = True,
+ max_objects: int | None = None,
+ ) -> list[ArtifactManifestEntry]:
+ name = name or os.path.basename(path)
+ if not checksum:
+ return [ArtifactManifestEntry(path=name, ref=path, digest=path)]
+
+ with self._session.get(
+ path,
+ stream=True,
+ cookies=_thread_local_api_settings.cookies,
+ headers=_thread_local_api_settings.headers,
+ ) as response:
+ digest: ETag | FilePathStr | URIStr | None
+ digest, size, extra = self._entry_from_headers(response.headers)
+ digest = digest or path
+ return [
+ ArtifactManifestEntry(
+ path=name, ref=path, digest=digest, size=size, extra=extra
+ )
+ ]
+
+ def _entry_from_headers(
+ self, headers: CaseInsensitiveDict
+ ) -> tuple[ETag | None, int | None, dict[str, str]]:
+ response_headers = {k.lower(): v for k, v in headers.items()}
+ size = None
+ if response_headers.get("content-length", None):
+ size = int(response_headers["content-length"])
+
+ digest = response_headers.get("etag", None)
+ extra = {}
+ if digest:
+ extra["etag"] = digest
+ if digest and digest[:1] == '"' and digest[-1:] == '"':
+ digest = digest[1:-1] # trim leading and trailing quotes around etag
+ return digest, size, extra
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/local_file_handler.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/local_file_handler.py
new file mode 100644
index 0000000000000000000000000000000000000000..c003261e15a05255c6849a6a5222738f91f9fd33
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/local_file_handler.py
@@ -0,0 +1,146 @@
+"""Local file storage handler."""
+
+from __future__ import annotations
+
+import os
+import shutil
+import time
+from pathlib import Path
+from typing import TYPE_CHECKING
+from urllib.parse import ParseResult
+
+from wandb import util
+from wandb.errors.term import termlog
+from wandb.sdk.artifacts.artifact_file_cache import get_artifact_file_cache
+from wandb.sdk.artifacts.artifact_manifest_entry import ArtifactManifestEntry
+from wandb.sdk.artifacts.storage_handler import DEFAULT_MAX_OBJECTS, StorageHandler
+from wandb.sdk.lib import filesystem
+from wandb.sdk.lib.hashutil import B64MD5, md5_file_b64, md5_string
+from wandb.sdk.lib.paths import FilePathStr, StrPath, URIStr
+
+if TYPE_CHECKING:
+ from wandb.sdk.artifacts.artifact import Artifact
+ from wandb.sdk.artifacts.artifact_file_cache import ArtifactFileCache
+
+
+class LocalFileHandler(StorageHandler):
+ """Handles file:// references."""
+
+ _scheme: str
+ _cache: ArtifactFileCache
+
+ def __init__(self, scheme: str = "file") -> None:
+ """Track files or directories on a local filesystem.
+
+ Expand directories to create an entry for each file contained.
+ """
+ self._scheme = scheme
+ self._cache = get_artifact_file_cache()
+
+ def can_handle(self, parsed_url: ParseResult) -> bool:
+ return parsed_url.scheme == self._scheme
+
+ def load_path(
+ self,
+ manifest_entry: ArtifactManifestEntry,
+ local: bool = False,
+ ) -> URIStr | FilePathStr:
+ if manifest_entry.ref is None:
+ raise ValueError(f"Cannot add path with no ref: {manifest_entry.path}")
+ local_path = util.local_file_uri_to_path(str(manifest_entry.ref))
+ if not os.path.exists(local_path):
+ raise ValueError(
+ f"Local file reference: Failed to find file at path {local_path}"
+ )
+
+ path, hit, cache_open = self._cache.check_md5_obj_path(
+ B64MD5(manifest_entry.digest), # TODO(spencerpearson): unsafe cast
+ manifest_entry.size or 0,
+ )
+ if hit:
+ return path
+
+ md5 = md5_file_b64(local_path)
+ if md5 != manifest_entry.digest:
+ raise ValueError(
+ f"Local file reference: Digest mismatch for path {local_path}: expected {manifest_entry.digest} but found {md5}"
+ )
+
+ filesystem.mkdir_exists_ok(os.path.dirname(path))
+
+ with cache_open() as f:
+ shutil.copy(local_path, f.name)
+ return path
+
+ def store_path(
+ self,
+ artifact: Artifact,
+ path: URIStr | FilePathStr,
+ name: StrPath | None = None,
+ checksum: bool = True,
+ max_objects: int | None = None,
+ ) -> list[ArtifactManifestEntry]:
+ local_path = util.local_file_uri_to_path(path)
+ max_objects = max_objects or DEFAULT_MAX_OBJECTS
+ # We have a single file or directory
+ # Note, we follow symlinks for files contained within the directory
+ entries = []
+
+ # If checksum=False, the file's hash should only
+ # depend on its absolute path/URI, not its contents
+
+ # Closure func for calculating the file hash from its path
+ def md5(path: str) -> B64MD5:
+ return (
+ md5_file_b64(path)
+ if checksum
+ else md5_string(Path(path).resolve().as_uri())
+ )
+
+ if os.path.isdir(local_path):
+ i = 0
+ start_time = time.monotonic()
+ if checksum:
+ termlog(
+ f'Generating checksum for up to {max_objects} files in "{local_path}"... ',
+ newline=False,
+ )
+ for root, _, files in os.walk(local_path):
+ for sub_path in files:
+ i += 1
+ if i > max_objects:
+ raise ValueError(
+ f"Exceeded {max_objects} objects tracked, pass max_objects to add_reference"
+ )
+ physical_path = os.path.join(root, sub_path)
+ # TODO(spencerpearson): this is not a "logical path" in the sense that
+ # `LogicalPath` returns a "logical path"; it's a relative path
+ # **on the local filesystem**.
+ file_path = os.path.relpath(physical_path, start=local_path)
+ if name is not None:
+ artifact_path = os.path.join(name, file_path)
+ else:
+ artifact_path = file_path
+
+ entry = ArtifactManifestEntry(
+ path=artifact_path,
+ ref=FilePathStr(os.path.join(path, file_path)),
+ size=os.path.getsize(physical_path),
+ digest=md5(physical_path),
+ )
+ entries.append(entry)
+ if checksum:
+ termlog("Done. %.1fs" % (time.monotonic() - start_time), prefix=False)
+ elif os.path.isfile(local_path):
+ name = name or os.path.basename(local_path)
+ entry = ArtifactManifestEntry(
+ path=name,
+ ref=path,
+ size=os.path.getsize(local_path),
+ digest=md5(local_path),
+ )
+ entries.append(entry)
+ else:
+ # TODO: update error message if we don't allow directories.
+ raise ValueError(f'Path "{path}" must be a valid file or directory path')
+ return entries
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/multi_handler.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/multi_handler.py
new file mode 100644
index 0000000000000000000000000000000000000000..79107d43f9c44a16b0c5597f2927953d831fb6c1
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/multi_handler.py
@@ -0,0 +1,57 @@
+"""Multi storage handler."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+from urllib.parse import urlparse
+
+from wandb.sdk.artifacts.storage_handler import StorageHandler, _BaseStorageHandler
+from wandb.sdk.lib.paths import FilePathStr, URIStr
+
+if TYPE_CHECKING:
+ from wandb.sdk.artifacts.artifact import Artifact
+ from wandb.sdk.artifacts.artifact_manifest_entry import ArtifactManifestEntry
+
+
+class MultiHandler(_BaseStorageHandler):
+ _handlers: list[StorageHandler]
+ _default_handler: StorageHandler | None
+
+ def __init__(
+ self,
+ handlers: list[StorageHandler] | None = None,
+ default_handler: StorageHandler | None = None,
+ ) -> None:
+ self._handlers = handlers or []
+ self._default_handler = default_handler
+
+ def _get_handler(self, url: FilePathStr | URIStr) -> StorageHandler:
+ parsed_url = urlparse(url)
+ for handler in self._handlers:
+ if handler.can_handle(parsed_url):
+ return handler
+ if self._default_handler is not None:
+ return self._default_handler
+ raise ValueError(f'No storage handler registered for url "{url!s}"')
+
+ def load_path(
+ self,
+ manifest_entry: ArtifactManifestEntry,
+ local: bool = False,
+ ) -> URIStr | FilePathStr:
+ assert manifest_entry.ref is not None
+ handler = self._get_handler(manifest_entry.ref)
+ return handler.load_path(manifest_entry, local=local)
+
+ def store_path(
+ self,
+ artifact: Artifact,
+ path: URIStr | FilePathStr,
+ name: str | None = None,
+ checksum: bool = True,
+ max_objects: int | None = None,
+ ) -> list[ArtifactManifestEntry]:
+ handler = self._get_handler(path)
+ return handler.store_path(
+ artifact, path, name=name, checksum=checksum, max_objects=max_objects
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/s3_handler.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/s3_handler.py
new file mode 100644
index 0000000000000000000000000000000000000000..fabec1a83fd3911b914a09c19189b3fae492de4b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/s3_handler.py
@@ -0,0 +1,342 @@
+"""S3 storage handler."""
+
+from __future__ import annotations
+
+import os
+import re
+import time
+from pathlib import PurePosixPath
+from typing import TYPE_CHECKING
+from urllib.parse import parse_qsl, urlparse
+
+from wandb import util
+from wandb._strutils import ensureprefix
+from wandb.errors import CommError
+from wandb.errors.term import termlog
+from wandb.sdk.artifacts.artifact_file_cache import get_artifact_file_cache
+from wandb.sdk.artifacts.artifact_manifest_entry import ArtifactManifestEntry
+from wandb.sdk.artifacts.storage_handler import DEFAULT_MAX_OBJECTS, StorageHandler
+from wandb.sdk.lib.hashutil import ETag
+from wandb.sdk.lib.paths import FilePathStr, StrPath, URIStr
+
+if TYPE_CHECKING:
+ from urllib.parse import ParseResult
+
+ # We could probably use https://pypi.org/project/boto3-stubs/ or something
+ # instead of `type:ignore`ing these boto imports, but it's nontrivial:
+ # for some reason, despite being actively maintained as of 2022-09-30,
+ # the latest release of boto3-stubs doesn't include all the features we use.
+ import boto3 # type: ignore
+ import boto3.resources.base # type: ignore
+ import boto3.s3 # type: ignore
+ import boto3.session # type: ignore
+
+ from wandb.sdk.artifacts.artifact import Artifact
+ from wandb.sdk.artifacts.artifact_file_cache import ArtifactFileCache
+
+
+class S3Handler(StorageHandler):
+ _scheme: str
+ _cache: ArtifactFileCache
+ _s3: boto3.resources.base.ServiceResource | None
+
+ def __init__(self, scheme: str = "s3") -> None:
+ self._scheme = scheme
+ self._cache = get_artifact_file_cache()
+ self._s3 = None
+
+ def can_handle(self, parsed_url: ParseResult) -> bool:
+ return parsed_url.scheme == self._scheme
+
+ def init_boto(self) -> boto3.resources.base.ServiceResource:
+ if self._s3 is not None:
+ return self._s3
+ boto: boto3 = util.get_module(
+ "boto3",
+ required="s3:// references requires the boto3 library, run pip install wandb[aws]",
+ lazy=False,
+ )
+
+ from botocore.client import Config # type: ignore
+
+ s3_endpoint = os.getenv("AWS_S3_ENDPOINT_URL")
+ config = (
+ Config(s3={"addressing_style": "virtual"})
+ if s3_endpoint and self._is_coreweave_endpoint(s3_endpoint)
+ else None
+ )
+ self._s3 = boto.session.Session().resource(
+ "s3",
+ endpoint_url=s3_endpoint,
+ region_name=os.getenv("AWS_REGION"),
+ config=config,
+ )
+ self._botocore = util.get_module("botocore")
+ return self._s3
+
+ def _parse_uri(self, uri: str) -> tuple[str, str, str | None]:
+ url = urlparse(uri)
+ query = dict(parse_qsl(url.query))
+
+ bucket = url.netloc
+ key = url.path[1:] # strip leading slash
+ version = query.get("versionId")
+
+ return bucket, key, version
+
+ def load_path(
+ self,
+ manifest_entry: ArtifactManifestEntry,
+ local: bool = False,
+ ) -> URIStr | FilePathStr:
+ if not local:
+ assert manifest_entry.ref is not None
+ return manifest_entry.ref
+
+ assert manifest_entry.ref is not None
+
+ path, hit, cache_open = self._cache.check_etag_obj_path(
+ URIStr(manifest_entry.ref),
+ ETag(manifest_entry.digest),
+ manifest_entry.size or 0,
+ )
+ if hit:
+ return path
+
+ self.init_boto()
+ assert self._s3 is not None # mypy: unwraps optionality
+ bucket, key, _ = self._parse_uri(manifest_entry.ref)
+ version = manifest_entry.extra.get("versionID")
+
+ extra_args = {}
+ if version:
+ obj_version = self._s3.ObjectVersion(bucket, key, version)
+ extra_args["VersionId"] = version
+ obj = obj_version.Object()
+ else:
+ obj = self._s3.Object(bucket, key)
+
+ try:
+ etag = (
+ obj_version.head()["ETag"][1:-1] # escape leading and trailing
+ if version
+ else self._etag_from_obj(obj)
+ )
+ except self._botocore.exceptions.ClientError as e:
+ if e.response["Error"]["Code"] == "404":
+ raise FileNotFoundError(
+ f"Unable to find {manifest_entry.path} at s3://{bucket}/{key}"
+ ) from e
+ raise
+
+ if etag != manifest_entry.digest:
+ # Try to match the etag with some other version.
+ if version:
+ raise ValueError(
+ f"Digest mismatch for object {manifest_entry.ref} with version {version}: expected {manifest_entry.digest} but found {etag}"
+ )
+ obj = None
+ object_versions = self._s3.Bucket(bucket).object_versions.filter(Prefix=key)
+ for object_version in object_versions:
+ if manifest_entry.extra.get("etag") == self._etag_from_obj(
+ object_version
+ ):
+ obj = object_version.Object()
+ extra_args["VersionId"] = object_version.version_id
+ break
+ if obj is None:
+ raise FileNotFoundError(
+ "Couldn't find object version for {}/{} matching etag {}".format(
+ bucket, key, manifest_entry.extra.get("etag")
+ )
+ )
+
+ with cache_open(mode="wb") as f:
+ obj.download_fileobj(f, ExtraArgs=extra_args)
+ return path
+
+ def store_path(
+ self,
+ artifact: Artifact,
+ path: URIStr | FilePathStr,
+ name: StrPath | None = None,
+ checksum: bool = True,
+ max_objects: int | None = None,
+ ) -> list[ArtifactManifestEntry]:
+ self.init_boto()
+ assert self._s3 is not None # mypy: unwraps optionality
+
+ # The passed in path might have query string parameters.
+ # We only need to care about a subset, like version, when
+ # parsing. Once we have that, we can store the rest of the
+ # metadata in the artifact entry itself.
+ bucket, key, version = self._parse_uri(path)
+ path = URIStr(f"{self._scheme}://{bucket}/{key}")
+
+ max_objects = max_objects or DEFAULT_MAX_OBJECTS
+ if not checksum:
+ entry_path = name or (key if key != "" else bucket)
+ return [ArtifactManifestEntry(path=entry_path, ref=path, digest=path)]
+
+ # If an explicit version is specified, use that. Otherwise, use the head version.
+ objs = (
+ [self._s3.ObjectVersion(bucket, key, version).Object()]
+ if version
+ else [self._s3.Object(bucket, key)]
+ )
+ start_time = None
+ multi = False
+ if key != "":
+ try:
+ objs[0].load()
+ # S3 doesn't have real folders, however there are cases where the folder key has a valid file which will not
+ # trigger a recursive upload.
+ # we should check the object's metadata says it is a directory and do a multi file upload if it is
+ if "x-directory" in objs[0].content_type:
+ multi = True
+ except self._botocore.exceptions.ClientError as e:
+ if e.response["Error"]["Code"] == "404":
+ multi = True
+ else:
+ raise CommError(
+ f"Unable to connect to S3 ({e.response['Error']['Code']}): "
+ f"{e.response['Error']['Message']}. Check that your "
+ "authentication credentials are valid and that your region is "
+ "set correctly."
+ )
+ else:
+ multi = True
+
+ if multi:
+ start_time = time.monotonic()
+ termlog(
+ f'Generating checksum for up to {max_objects} objects in "{bucket}/{key}"... ',
+ newline=False,
+ )
+ if key != "":
+ objs = (
+ self._s3.Bucket(bucket)
+ .objects.filter(Prefix=key)
+ .limit(max_objects)
+ )
+ else:
+ objs = self._s3.Bucket(bucket).objects.limit(max_objects)
+ # Weird iterator scoping makes us assign this to a local function
+ size = self._size_from_obj
+ entries = [
+ self._entry_from_obj(obj, path, name, prefix=key, multi=multi)
+ for obj in objs
+ if size(obj) > 0
+ ]
+ if start_time is not None:
+ termlog("Done. %.1fs" % (time.monotonic() - start_time), prefix=False)
+ if len(entries) > max_objects:
+ raise ValueError(
+ f"Exceeded {max_objects} objects tracked, pass max_objects to add_reference"
+ )
+ return entries
+
+ def _size_from_obj(self, obj: boto3.s3.Object | boto3.s3.ObjectSummary) -> int:
+ # ObjectSummary has size, Object has content_length
+ size: int
+ if hasattr(obj, "size"):
+ size = obj.size
+ else:
+ size = obj.content_length
+ return size
+
+ def _entry_from_obj(
+ self,
+ obj: boto3.s3.Object | boto3.s3.ObjectSummary,
+ path: str,
+ name: StrPath | None = None,
+ prefix: str = "",
+ multi: bool = False,
+ ) -> ArtifactManifestEntry:
+ """Create an ArtifactManifestEntry from an S3 object.
+
+ Args:
+ obj: The S3 object
+ path: The S3-style path (e.g.: "s3://bucket/file.txt")
+ name: The user assigned name, or None if not specified
+ prefix: The prefix to add (will be the same as `path` for directories)
+ multi: Whether or not this is a multi-object add.
+ """
+ bucket, key, _ = self._parse_uri(path)
+
+ # Always use posix paths, since that's what S3 uses.
+ posix_key = PurePosixPath(obj.key) # the bucket key
+ posix_path = PurePosixPath(bucket) / key # the path, with the scheme stripped
+ posix_prefix = PurePosixPath(prefix) # the prefix, if adding a prefix
+ posix_name = PurePosixPath(name or "")
+ posix_ref = posix_path
+
+ if name is None:
+ # We're adding a directory (prefix), so calculate a relative path.
+ if str(posix_prefix) in str(posix_key) and posix_prefix != posix_key:
+ posix_name = posix_key.relative_to(posix_prefix)
+ posix_ref = posix_path / posix_name
+ else:
+ posix_name = PurePosixPath(posix_key.name)
+ posix_ref = posix_path
+ elif multi:
+ # We're adding a directory with a name override.
+ relpath = posix_key.relative_to(posix_prefix)
+ posix_name = posix_name / relpath
+ posix_ref = posix_path / relpath
+ return ArtifactManifestEntry(
+ path=posix_name,
+ ref=URIStr(f"{self._scheme}://{str(posix_ref)}"),
+ digest=ETag(self._etag_from_obj(obj)),
+ size=self._size_from_obj(obj),
+ extra=self._extra_from_obj(obj),
+ )
+
+ @staticmethod
+ def _etag_from_obj(obj: boto3.s3.Object | boto3.s3.ObjectSummary) -> ETag:
+ etag: ETag
+ etag = obj.e_tag[1:-1] # escape leading and trailing quote
+ return etag
+
+ def _extra_from_obj(
+ self, obj: boto3.s3.Object | boto3.s3.ObjectSummary
+ ) -> dict[str, str]:
+ extra = {
+ "etag": obj.e_tag[1:-1], # escape leading and trailing quote
+ }
+ if not hasattr(obj, "version_id"):
+ # Convert ObjectSummary to Object to get the version_id.
+ obj = self._s3.Object(obj.bucket_name, obj.key) # type: ignore[union-attr]
+ if hasattr(obj, "version_id") and obj.version_id and obj.version_id != "null":
+ extra["versionID"] = obj.version_id
+ return extra
+
+ _CW_LEGACY_NETLOC_REGEX: re.Pattern[str] = re.compile(
+ r"""
+ # accelerated endpoints like "accel-object..coreweave.com"
+ accel-object\.[a-z0-9-]+\.coreweave\.com
+ |
+ # URLs like "object..coreweave.com"
+ object\.[a-z0-9-]+\.coreweave\.com
+ """,
+ flags=re.VERBOSE,
+ )
+
+ def _is_coreweave_endpoint(self, endpoint_url: str) -> bool:
+ if not (url := endpoint_url.strip().rstrip("/")):
+ return False
+
+ # Only http://cwlota.com is supported using HTTP
+ if url == "http://cwlota.com":
+ return True
+
+ # Enforce HTTPS otherwise
+ https_url = ensureprefix(url, "https://")
+ netloc = urlparse(https_url).netloc
+ return bool(
+ # Match for https://cwobject.com
+ (netloc == "cwobject.com")
+ or
+ # Check for legacy endpoints
+ self._CW_LEGACY_NETLOC_REGEX.fullmatch(netloc)
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/tracking_handler.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/tracking_handler.py
new file mode 100644
index 0000000000000000000000000000000000000000..83f97db42c5636bab782ea6dcd14efcdade78aac
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/tracking_handler.py
@@ -0,0 +1,70 @@
+"""Tracking storage handler."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+from urllib.parse import urlparse
+
+from wandb.errors.term import termwarn
+from wandb.sdk.artifacts.artifact_manifest_entry import ArtifactManifestEntry
+from wandb.sdk.artifacts.storage_handler import StorageHandler
+from wandb.sdk.lib.paths import FilePathStr, StrPath, URIStr
+
+if TYPE_CHECKING:
+ from urllib.parse import ParseResult
+
+ from wandb.sdk.artifacts.artifact import Artifact
+
+
+class TrackingHandler(StorageHandler):
+ _scheme: str
+
+ def __init__(self, scheme: str = "") -> None:
+ """Track paths with no modification or special processing.
+
+ Useful when paths being tracked are on file systems mounted at a standardized
+ location.
+
+ For example, if the data to track is located on an NFS share mounted on
+ `/data`, then it is sufficient to just track the paths.
+ """
+ self._scheme = scheme
+
+ def can_handle(self, parsed_url: ParseResult) -> bool:
+ return parsed_url.scheme == self._scheme
+
+ def load_path(
+ self,
+ manifest_entry: ArtifactManifestEntry,
+ local: bool = False,
+ ) -> URIStr | FilePathStr:
+ if local:
+ # Likely a user error. The tracking handler is
+ # oblivious to the underlying paths, so it has
+ # no way of actually loading it.
+ url = urlparse(manifest_entry.ref)
+ raise ValueError(
+ f"Cannot download file at path {str(manifest_entry.ref)}, scheme {str(url.scheme)} not recognized"
+ )
+ # TODO(spencerpearson): should this go through util.to_native_slash_path
+ # instead of just getting typecast?
+ return FilePathStr(manifest_entry.path)
+
+ def store_path(
+ self,
+ artifact: Artifact,
+ path: URIStr | FilePathStr,
+ name: StrPath | None = None,
+ checksum: bool = True,
+ max_objects: int | None = None,
+ ) -> list[ArtifactManifestEntry]:
+ url = urlparse(path)
+ if name is None:
+ raise ValueError(
+ f'You must pass name="" when tracking references with unknown schemes. ref: {path}'
+ )
+ termwarn(
+ f"Artifact references with unsupported schemes cannot be checksummed: {path}"
+ )
+ name = name or url.path[1:] # strip leading slash
+ return [ArtifactManifestEntry(path=name, ref=path, digest=path)]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/wb_artifact_handler.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/wb_artifact_handler.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c0646734b1b42b81bf4212a395b426b46485a3c
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/wb_artifact_handler.py
@@ -0,0 +1,134 @@
+"""WB artifact storage handler."""
+
+from __future__ import annotations
+
+import os
+from typing import TYPE_CHECKING, Literal
+from urllib.parse import urlparse
+
+from wandb._strutils import removeprefix
+from wandb.apis import PublicApi
+from wandb.sdk.artifacts.artifact_file_cache import get_artifact_file_cache
+from wandb.sdk.artifacts.artifact_manifest_entry import ArtifactManifestEntry
+from wandb.sdk.artifacts.storage_handler import StorageHandler
+from wandb.sdk.lib.hashutil import b64_to_hex_id, hex_to_b64_id
+from wandb.sdk.lib.paths import FilePathStr, StrPath, URIStr
+
+if TYPE_CHECKING:
+ from urllib.parse import ParseResult
+
+ from wandb.sdk.artifacts.artifact import Artifact
+ from wandb.sdk.artifacts.artifact_file_cache import ArtifactFileCache
+
+
+class WBArtifactHandler(StorageHandler):
+ """Handles loading and storing Artifact reference-type files."""
+
+ _scheme: Literal["wandb-artifact"]
+ _cache: ArtifactFileCache
+ _client: PublicApi | None
+
+ def __init__(self) -> None:
+ self._scheme = "wandb-artifact"
+ self._cache = get_artifact_file_cache()
+ self._client = None
+
+ def can_handle(self, parsed_url: ParseResult) -> bool:
+ return parsed_url.scheme == self._scheme
+
+ @property
+ def client(self) -> PublicApi:
+ if self._client is None:
+ self._client = PublicApi()
+ return self._client
+
+ def load_path(
+ self,
+ manifest_entry: ArtifactManifestEntry,
+ local: bool = False,
+ ) -> URIStr | FilePathStr:
+ """Load the file in the specified artifact given its corresponding entry.
+
+ Download the referenced artifact; create and return a new symlink to the caller.
+
+ Args:
+ manifest_entry (ArtifactManifestEntry): The index entry to load
+
+ Returns:
+ (os.PathLike): A path to the file represented by `index_entry`
+ """
+ from wandb.sdk.artifacts.artifact import Artifact # avoids circular import
+
+ # We don't check for cache hits here. Since we have 0 for size (since this
+ # is a cross-artifact reference which and we've made the choice to store 0
+ # in the size field), we can't confirm if the file is complete. So we just
+ # rely on the dep_artifact entry's download() method to do its own cache
+ # check.
+
+ # Parse the reference path and download the artifact if needed
+ parsed = urlparse(manifest_entry.ref)
+ artifact_id = hex_to_b64_id(parsed.netloc)
+ artifact_file_path = removeprefix(str(parsed.path), "/")
+
+ dep_artifact = Artifact._from_id(artifact_id, self.client.client)
+ assert dep_artifact is not None
+ link_target_path: URIStr | FilePathStr
+ if local:
+ link_target_path = dep_artifact.get_entry(artifact_file_path).download()
+ else:
+ link_target_path = dep_artifact.get_entry(artifact_file_path).ref_target()
+ return link_target_path
+
+ def store_path(
+ self,
+ artifact: Artifact,
+ path: URIStr | FilePathStr,
+ name: StrPath | None = None,
+ checksum: bool = True,
+ max_objects: int | None = None,
+ ) -> list[ArtifactManifestEntry]:
+ """Store the file or directory at the given path into the specified artifact.
+
+ Recursively resolves the reference until the result is a concrete asset.
+
+ Args:
+ artifact: The artifact doing the storing path (str): The path to store name
+ (str): If specified, the logical name that should map to `path`
+
+ Returns:
+ (list[ArtifactManifestEntry]): A list of manifest entries to store within
+ the artifact
+ """
+ from wandb.sdk.artifacts.artifact import Artifact # avoids circular import
+
+ # Recursively resolve the reference until a concrete asset is found
+ # TODO: Consider resolving server-side for performance improvements.
+ curr_path: URIStr | FilePathStr | None = path
+ while curr_path and (parsed := urlparse(curr_path)).scheme == self._scheme:
+ artifact_id = hex_to_b64_id(parsed.netloc)
+ artifact_file_path = removeprefix(parsed.path, "/")
+
+ target_artifact = Artifact._from_id(artifact_id, self.client.client)
+ assert target_artifact is not None
+
+ entry = target_artifact.manifest.get_entry_by_path(artifact_file_path)
+ assert entry is not None
+ curr_path = entry.ref
+
+ # Create the path reference
+ assert target_artifact is not None
+ assert target_artifact.id is not None
+ path = (
+ f"{self._scheme}://{b64_to_hex_id(target_artifact.id)}/{artifact_file_path}"
+ )
+
+ # Return the new entry
+ assert entry is not None
+ return [
+ ArtifactManifestEntry(
+ path=name or os.path.basename(path),
+ ref=path,
+ size=0,
+ digest=entry.digest,
+ )
+ ]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/wb_local_artifact_handler.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/wb_local_artifact_handler.py
new file mode 100644
index 0000000000000000000000000000000000000000..7968163bde7483c41897113ef55bd9f0d8ef190b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/wb_local_artifact_handler.py
@@ -0,0 +1,76 @@
+"""WB local artifact storage handler."""
+
+from __future__ import annotations
+
+import os
+from typing import TYPE_CHECKING, Literal
+
+import wandb
+from wandb import util
+from wandb.sdk.artifacts.artifact_instance_cache import artifact_instance_cache
+from wandb.sdk.artifacts.artifact_manifest_entry import ArtifactManifestEntry
+from wandb.sdk.artifacts.storage_handler import StorageHandler
+from wandb.sdk.lib.paths import FilePathStr, StrPath, URIStr
+
+if TYPE_CHECKING:
+ from urllib.parse import ParseResult
+
+ from wandb.sdk.artifacts.artifact import Artifact
+
+
+class WBLocalArtifactHandler(StorageHandler):
+ """Handles loading and storing Artifact reference-type files."""
+
+ _scheme: Literal["wandb-client-artifact"]
+
+ def __init__(self) -> None:
+ self._scheme = "wandb-client-artifact"
+
+ def can_handle(self, parsed_url: ParseResult) -> bool:
+ return parsed_url.scheme == self._scheme
+
+ def load_path(
+ self,
+ manifest_entry: ArtifactManifestEntry,
+ local: bool = False,
+ ) -> URIStr | FilePathStr:
+ raise NotImplementedError(
+ "Should not be loading a path for an artifact entry with unresolved client id."
+ )
+
+ def store_path(
+ self,
+ artifact: Artifact,
+ path: URIStr | FilePathStr,
+ name: StrPath | None = None,
+ checksum: bool = True,
+ max_objects: int | None = None,
+ ) -> list[ArtifactManifestEntry]:
+ """Store the file or directory at the given path within the specified artifact.
+
+ Args:
+ artifact: The artifact doing the storing
+ path (str): The path to store
+ name (str): If specified, the logical name that should map to `path`
+
+ Returns:
+ (list[ArtifactManifestEntry]): A list of manifest entries to store within the artifact
+ """
+ client_id = util.host_from_path(path)
+ target_path = util.uri_from_path(path)
+ target_artifact = artifact_instance_cache.get(client_id)
+ if not isinstance(target_artifact, wandb.Artifact):
+ raise TypeError("Artifact passed to store_path() must be a wandb.Artifact.")
+ target_entry = target_artifact.manifest.entries[target_path] # type: ignore
+ if target_entry is None:
+ raise RuntimeError("Local entry not found - invalid reference")
+
+ # Return the new entry
+ return [
+ ArtifactManifestEntry(
+ path=name or os.path.basename(path),
+ ref=path,
+ size=0,
+ digest=target_entry.digest,
+ )
+ ]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_layout.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_layout.py
new file mode 100644
index 0000000000000000000000000000000000000000..7fb20c522ac667a83be3ad55abc74b32a453650f
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_layout.py
@@ -0,0 +1,8 @@
+"""Storage layout."""
+
+from __future__ import annotations
+
+
+class StorageLayout:
+ V1 = "V1"
+ V2 = "V2"
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_policies/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_policies/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d409bcf913dfde9b84f6cc53d3c980a2cbe02e2
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_policies/__init__.py
@@ -0,0 +1,4 @@
+from wandb.sdk.artifacts.storage_policies.register import WANDB_STORAGE_POLICY
+from wandb.sdk.artifacts.storage_policies.wandb_storage_policy import WandbStoragePolicy
+
+__all__ = ["WANDB_STORAGE_POLICY", "WandbStoragePolicy"]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_policies/_factories.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_policies/_factories.py
new file mode 100644
index 0000000000000000000000000000000000000000..f47f2505bcf20de63bcc7cb34c06067d90d463b5
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_policies/_factories.py
@@ -0,0 +1,63 @@
+from __future__ import annotations
+
+from typing import Final
+
+from requests import Response, Session
+from requests.adapters import HTTPAdapter
+from urllib3.util.retry import Retry
+
+from ..storage_handler import StorageHandler
+from ..storage_handlers.azure_handler import AzureHandler
+from ..storage_handlers.gcs_handler import GCSHandler
+from ..storage_handlers.http_handler import HTTPHandler
+from ..storage_handlers.local_file_handler import LocalFileHandler
+from ..storage_handlers.s3_handler import S3Handler
+from ..storage_handlers.wb_artifact_handler import WBArtifactHandler
+from ..storage_handlers.wb_local_artifact_handler import WBLocalArtifactHandler
+
+# Sleep length: 0, 2, 4, 8, 16, 32, 64, 120, 120, 120, 120, 120, 120, 120, 120, 120
+# seconds, i.e. a total of 20min 6s.
+HTTP_RETRY_STRATEGY: Final[Retry] = Retry(
+ backoff_factor=1,
+ total=16,
+ status_forcelist=(308, 408, 409, 429, 500, 502, 503, 504),
+)
+HTTP_POOL_CONNECTIONS: Final[int] = 64
+HTTP_POOL_MAXSIZE: Final[int] = 64
+
+
+def raise_for_status(response: Response, *_, **__) -> None:
+ """A `requests.Session` hook to raise for status on all requests."""
+ response.raise_for_status()
+
+
+def make_http_session() -> Session:
+ """A factory that returns a `requests.Session` for use with artifact storage handlers."""
+ session = Session()
+
+ # Explicitly configure the retry strategy for http/https adapters.
+ adapter = HTTPAdapter(
+ max_retries=HTTP_RETRY_STRATEGY,
+ pool_connections=HTTP_POOL_CONNECTIONS,
+ pool_maxsize=HTTP_POOL_MAXSIZE,
+ )
+ session.mount("http://", adapter)
+ session.mount("https://", adapter)
+
+ # Always raise on HTTP status errors.
+ session.hooks["response"].append(raise_for_status)
+ return session
+
+
+def make_storage_handlers(session: Session) -> list[StorageHandler]:
+ """A factory that returns the default artifact storage handlers."""
+ return [
+ S3Handler(), # s3
+ GCSHandler(), # gcs
+ AzureHandler(), # azure
+ HTTPHandler(session, scheme="http"), # http
+ HTTPHandler(session, scheme="https"), # https
+ WBArtifactHandler(), # artifact
+ WBLocalArtifactHandler(), # local_artifact
+ LocalFileHandler(), # file_handler
+ ]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_policies/_multipart.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_policies/_multipart.py
new file mode 100644
index 0000000000000000000000000000000000000000..421877b2ff08de7aaad50d729eab018960aaf51c
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_policies/_multipart.py
@@ -0,0 +1,187 @@
+"""Helpers and constants for multipart upload and download."""
+
+from __future__ import annotations
+
+import logging
+import math
+import threading
+from concurrent.futures import FIRST_EXCEPTION, Executor, wait
+from dataclasses import dataclass, field
+from queue import Queue
+from typing import Any, Final, Iterator, Union
+
+from requests import Session
+from typing_extensions import TypeAlias, TypeIs, final
+
+from wandb import env
+from wandb.sdk.artifacts.artifact_file_cache import Opener
+
+logger = logging.getLogger(__name__)
+
+KiB: Final[int] = 1024
+MiB: Final[int] = 1024**2
+GiB: Final[int] = 1024**3
+TiB: Final[int] = 1024**4
+
+# AWS S3 max upload parts without having to make additional requests for extra parts
+MAX_PARTS = 1_000
+MIN_MULTI_UPLOAD_SIZE = 2 * GiB
+MAX_MULTI_UPLOAD_SIZE = 5 * TiB
+
+# Minimum size to switch to multipart download, same threshold as upload.
+MIN_MULTI_DOWNLOAD_SIZE = MIN_MULTI_UPLOAD_SIZE
+
+# Multipart download part size is same as multpart upload size, which is hard coded to 100MB.
+# https://github.com/wandb/wandb/blob/7b2a13cb8efcd553317167b823c8e52d8c3f7c4e/core/pkg/artifacts/saver.go#L496
+# https://docs.aws.amazon.com/AmazonS3/latest/userguide/optimizing-performance-guidelines.html#optimizing-performance-guidelines-get-range
+MULTI_DEFAULT_PART_SIZE = 100 * MiB
+
+# Chunk size for reading http response and writing to disk.
+RSP_CHUNK_SIZE = 1 * MiB
+
+
+@final
+class _ChunkSentinel:
+ """Signals the end of the multipart chunk queue.
+
+ Queue consumer(s) (file writer) should terminate on receiving an item of this type from the queue.
+ Do not instantiate this class directly, use the `END_CHUNK` constant as a pseudo-singleton instead.
+
+ NOTE: As implemented, this should only be used in multi-threaded (not multi-process) contexts, as
+ it's not currently guaranteed to be process-safe.
+ """
+
+ def __repr__(self) -> str:
+ return "ChunkSentinel"
+
+
+END_CHUNK: Final[_ChunkSentinel] = _ChunkSentinel()
+
+
+def is_end_chunk(obj: Any) -> TypeIs[_ChunkSentinel]:
+ """Returns True if the object is the terminal queue item for multipart downloads."""
+ # Needed for type checking, since _ChunkSentinel isn't formally a singleton.
+ return obj is END_CHUNK
+
+
+@dataclass(frozen=True)
+class ChunkContent:
+ __slots__ = ("offset", "data") # slots=True only introduced in Python 3.10
+ offset: int
+ data: bytes
+
+
+QueuedChunk: TypeAlias = Union[ChunkContent, _ChunkSentinel]
+
+
+def should_multipart_download(size: int | None, override: bool | None = None) -> bool:
+ return ((size or 0) >= MIN_MULTI_DOWNLOAD_SIZE) if (override is None) else override
+
+
+def calc_part_size(file_size: int, min_part_size: int = MULTI_DEFAULT_PART_SIZE) -> int:
+ # Default to a chunk size of 100MiB. S3 has a cap of 10,000 upload parts.
+ return max(math.ceil(file_size / MAX_PARTS), min_part_size)
+
+
+def scan_chunks(path: str, chunk_size: int) -> Iterator[bytes]:
+ with open(path, "rb") as f:
+ while data := f.read(chunk_size):
+ yield data
+
+
+@dataclass
+class MultipartDownloadContext:
+ q: Queue[QueuedChunk]
+ cancel: threading.Event = field(default_factory=threading.Event)
+
+
+def multipart_download(
+ executor: Executor,
+ session: Session,
+ url: str,
+ size: int,
+ cached_open: Opener,
+ part_size: int = MULTI_DEFAULT_PART_SIZE,
+):
+ """Download file as multiple parts in parallel.
+
+ Only one thread for writing to file. Each part run one http request in one thread.
+ HTTP response chunk of a file part is sent to the writer thread via a queue.
+ """
+ # ------------------------------------------------------------------------------
+ # Shared between threads
+ ctx = MultipartDownloadContext(q=Queue(maxsize=500))
+
+ # Put cache_open at top so we remove the tmp file when there is network error.
+ with cached_open("wb") as f:
+
+ def download_chunk(start: int, end: int | None = None) -> None:
+ # Error from another thread, no need to start
+ if ctx.cancel.is_set():
+ return
+
+ # https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Range
+ # Start and end are both inclusive, empty end means use the actual end of the file.
+ # e.g. "bytes=0-499"
+ bytes_range = f"{start}-" if (end is None) else f"{start}-{end}"
+ headers = {"Range": f"bytes={bytes_range}"}
+ with session.get(url=url, headers=headers, stream=True) as rsp:
+ offset = start
+ for chunk in rsp.iter_content(chunk_size=RSP_CHUNK_SIZE):
+ if ctx.cancel.is_set():
+ return
+ ctx.q.put(ChunkContent(offset=offset, data=chunk))
+ offset += len(chunk)
+
+ def write_chunks() -> None:
+ # If all chunks are written or there's an error in another thread, shutdown
+ while not (ctx.cancel.is_set() or is_end_chunk(chunk := ctx.q.get())):
+ try:
+ # NOTE: Seek works without pre allocating the file on disk.
+ # It automatically creates a sparse file, e.g. ls -hl would show
+ # a bigger size compared to du -sh * because downloading different
+ # chunks is not a sequential write.
+ # See https://man7.org/linux/man-pages/man2/lseek.2.html
+ f.seek(chunk.offset)
+ f.write(chunk.data)
+
+ except Exception as e:
+ if env.is_debug():
+ logger.debug(f"Error writing chunk to file: {e}")
+ ctx.cancel.set()
+ raise
+
+ # Start writer thread first.
+ write_future = executor.submit(write_chunks)
+
+ # Start download threads for each chunk.
+ download_futures = set()
+ for start in range(0, size, part_size):
+ # https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Range
+ # Start and end are both inclusive, empty end means use the actual end of the file.
+ # e.g. bytes=0-499
+ end = end if (end := (start + part_size - 1)) < size else None
+ download_futures.add(executor.submit(download_chunk, start=start, end=end))
+
+ # Wait for download
+ done, not_done = wait(download_futures, return_when=FIRST_EXCEPTION)
+ try:
+ for fut in done:
+ fut.result()
+ except Exception as e:
+ if env.is_debug():
+ logger.debug(f"Error downloading file: {e}")
+ ctx.cancel.set()
+
+ # Cancel any pending futures. Note:
+ # - `Future.cancel()` does NOT stop the future if it's running, which is why
+ # there's a separate `threading.Event` to ensure cooperative cancellation.
+ # - Once Python 3.8 support is dropped, replace these `fut.cancel()`
+ # calls with `Executor.shutdown(cancel_futures=True)`.
+ for fut in not_done:
+ fut.cancel()
+ raise
+ finally:
+ # Always signal the writer to stop
+ ctx.q.put(END_CHUNK)
+ write_future.result()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_policies/register.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_policies/register.py
new file mode 100644
index 0000000000000000000000000000000000000000..84542d8a70fca03538985fa8aa9c6ef7ea86c2b5
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_policies/register.py
@@ -0,0 +1 @@
+WANDB_STORAGE_POLICY = "wandb-storage-policy-v1"
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_policies/wandb_storage_policy.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_policies/wandb_storage_policy.py
new file mode 100644
index 0000000000000000000000000000000000000000..d336aab43f850326288463efb04c4a10155e0361
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_policies/wandb_storage_policy.py
@@ -0,0 +1,344 @@
+"""WandB storage policy."""
+
+from __future__ import annotations
+
+import concurrent.futures
+import hashlib
+import logging
+import os
+import shutil
+from collections import deque
+from operator import itemgetter
+from typing import TYPE_CHECKING, Any
+from urllib.parse import quote
+
+import requests
+
+from wandb.errors.term import termwarn
+from wandb.proto.wandb_internal_pb2 import ServerFeature
+from wandb.sdk.artifacts.artifact_file_cache import (
+ ArtifactFileCache,
+ get_artifact_file_cache,
+)
+from wandb.sdk.artifacts.staging import get_staging_dir
+from wandb.sdk.artifacts.storage_handlers.multi_handler import MultiHandler
+from wandb.sdk.artifacts.storage_handlers.tracking_handler import TrackingHandler
+from wandb.sdk.artifacts.storage_layout import StorageLayout
+from wandb.sdk.artifacts.storage_policies._multipart import (
+ MAX_MULTI_UPLOAD_SIZE,
+ MIN_MULTI_UPLOAD_SIZE,
+ KiB,
+ calc_part_size,
+ multipart_download,
+ scan_chunks,
+)
+from wandb.sdk.artifacts.storage_policies.register import WANDB_STORAGE_POLICY
+from wandb.sdk.artifacts.storage_policy import StoragePolicy
+from wandb.sdk.internal.internal_api import Api as InternalApi
+from wandb.sdk.internal.thread_local_settings import _thread_local_api_settings
+from wandb.sdk.lib.hashutil import b64_to_hex_id, hex_to_b64_id
+from wandb.sdk.lib.paths import FilePathStr, URIStr
+
+from ._factories import make_http_session, make_storage_handlers
+
+if TYPE_CHECKING:
+ from wandb.filesync.step_prepare import StepPrepare
+ from wandb.sdk.artifacts.artifact import Artifact
+ from wandb.sdk.artifacts.artifact_manifest_entry import ArtifactManifestEntry
+ from wandb.sdk.internal import progress
+
+logger = logging.getLogger(__name__)
+
+
+class WandbStoragePolicy(StoragePolicy):
+ @classmethod
+ def name(cls) -> str:
+ return WANDB_STORAGE_POLICY
+
+ @classmethod
+ def from_config(
+ cls, config: dict[str, Any], api: InternalApi | None = None
+ ) -> WandbStoragePolicy:
+ return cls(config=config, api=api)
+
+ def __init__(
+ self,
+ config: dict[str, Any] | None = None,
+ cache: ArtifactFileCache | None = None,
+ api: InternalApi | None = None,
+ session: requests.Session | None = None,
+ ) -> None:
+ self._config = config or {}
+ if (storage_region := self._config.get("storageRegion")) is not None:
+ self._validate_storage_region(storage_region)
+ self._cache = cache or get_artifact_file_cache()
+ self._session = session or make_http_session()
+ self._api = api or InternalApi()
+ self._handler = MultiHandler(
+ handlers=make_storage_handlers(self._session),
+ default_handler=TrackingHandler(),
+ )
+
+ def _validate_storage_region(self, storage_region: Any) -> None:
+ if not isinstance(storage_region, str):
+ raise TypeError(
+ f"storageRegion must be a string, got {type(storage_region).__name__}: {storage_region!r}"
+ )
+ if not storage_region.strip():
+ raise ValueError("storageRegion must be a non-empty string")
+
+ def config(self) -> dict[str, Any]:
+ return self._config
+
+ def load_file(
+ self,
+ artifact: Artifact,
+ manifest_entry: ArtifactManifestEntry,
+ dest_path: str | None = None,
+ # FIXME: We should avoid passing the executor into multiple inner functions,
+ # it leads to confusing code and opaque tracebacks/call stacks.
+ executor: concurrent.futures.Executor | None = None,
+ ) -> FilePathStr:
+ """Use cache or download the file using signed url.
+
+ Args:
+ executor: Passed from caller, artifact has a thread pool for multi file download.
+ Reuse the thread pool for multi part download. The thread pool is closed when
+ artifact download is done.
+
+ If this is None, download the file serially.
+ """
+ if dest_path is not None:
+ self._cache._override_cache_path = dest_path
+
+ path, hit, cache_open = self._cache.check_md5_obj_path(
+ manifest_entry.digest,
+ size=manifest_entry.size or 0,
+ )
+ if hit:
+ return path
+
+ if url := manifest_entry._download_url:
+ # Use multipart parallel download for large file
+ if executor and (size := manifest_entry.size):
+ multipart_download(executor, self._session, url, size, cache_open)
+ return path
+
+ # Serial download
+ try:
+ response = self._session.get(url, stream=True)
+ except requests.HTTPError:
+ # Signed URL might have expired, fall back to fetching it one by one.
+ manifest_entry._download_url = None
+
+ if manifest_entry._download_url is None:
+ auth = None
+ headers = _thread_local_api_settings.headers
+ cookies = _thread_local_api_settings.cookies
+
+ # For auth, prefer using (in order): auth header, cookies, HTTP Basic Auth
+ if token := self._api.access_token:
+ headers = {**(headers or {}), "Authorization": f"Bearer {token}"}
+ elif cookies is not None:
+ pass
+ else:
+ auth = ("api", self._api.api_key or "")
+
+ file_url = self._file_url(self._api, artifact, manifest_entry)
+ response = self._session.get(
+ file_url, auth=auth, cookies=cookies, headers=headers, stream=True
+ )
+
+ with cache_open(mode="wb") as file:
+ for data in response.iter_content(chunk_size=16 * KiB):
+ file.write(data)
+ return path
+
+ def store_reference(
+ self,
+ artifact: Artifact,
+ path: URIStr | FilePathStr,
+ name: str | None = None,
+ checksum: bool = True,
+ max_objects: int | None = None,
+ ) -> list[ArtifactManifestEntry]:
+ return self._handler.store_path(
+ artifact, path, name=name, checksum=checksum, max_objects=max_objects
+ )
+
+ def load_reference(
+ self,
+ manifest_entry: ArtifactManifestEntry,
+ local: bool = False,
+ dest_path: str | None = None,
+ ) -> FilePathStr | URIStr:
+ assert manifest_entry.ref is not None
+ used_handler = self._handler._get_handler(manifest_entry.ref)
+ if hasattr(used_handler, "_cache") and (dest_path is not None):
+ used_handler._cache._override_cache_path = dest_path
+ return self._handler.load_path(manifest_entry, local)
+
+ def _file_url(
+ self,
+ api: InternalApi,
+ artifact: Artifact,
+ entry: ArtifactManifestEntry,
+ ) -> str:
+ layout = self._config.get("storageLayout", StorageLayout.V1)
+ region = self._config.get("storageRegion", "default")
+
+ entity_name = artifact.entity
+ project_name = artifact.project
+ artifact_name = artifact.name.split(":")[0]
+
+ md5_hex = b64_to_hex_id(entry.digest)
+
+ base_url: str = api.settings("base_url")
+
+ if layout == StorageLayout.V1:
+ return f"{base_url}/artifacts/{entity_name}/{md5_hex}"
+
+ if layout == StorageLayout.V2:
+ birth_artifact_id = entry.birth_artifact_id or ""
+ if api._server_supports(
+ ServerFeature.ARTIFACT_COLLECTION_MEMBERSHIP_FILE_DOWNLOAD_HANDLER
+ ):
+ return f"{base_url}/artifactsV2/{region}/{quote(entity_name)}/{quote(project_name)}/{quote(artifact_name)}/{quote(birth_artifact_id)}/{md5_hex}/{entry.path.name}"
+
+ return f"{base_url}/artifactsV2/{region}/{entity_name}/{quote(birth_artifact_id)}/{md5_hex}"
+
+ raise ValueError(f"unrecognized storage layout: {layout!r}")
+
+ def s3_multipart_file_upload(
+ self,
+ file_path: str,
+ chunk_size: int,
+ hex_digests: dict[int, str],
+ multipart_urls: dict[int, str],
+ extra_headers: dict[str, str],
+ ) -> list[dict[str, Any]]:
+ etags: deque[dict[str, Any]] = deque()
+ file_chunks = scan_chunks(file_path, chunk_size)
+ for num, data in enumerate(file_chunks, start=1):
+ rsp = self._api.upload_multipart_file_chunk_retry(
+ multipart_urls[num],
+ data,
+ extra_headers={
+ "content-md5": hex_to_b64_id(hex_digests[num]),
+ "content-length": str(len(data)),
+ "content-type": extra_headers.get("Content-Type") or "",
+ },
+ )
+ assert rsp is not None
+ etags.append({"partNumber": num, "hexMD5": rsp.headers["ETag"]})
+ return list(etags)
+
+ def default_file_upload(
+ self,
+ upload_url: str,
+ file_path: str,
+ extra_headers: dict[str, Any],
+ progress_callback: progress.ProgressFn | None = None,
+ ) -> None:
+ """Upload a file to the artifact store and write to cache."""
+ with open(file_path, "rb") as file:
+ # This fails if we don't send the first byte before the signed URL expires.
+ self._api.upload_file_retry(
+ upload_url, file, progress_callback, extra_headers=extra_headers
+ )
+
+ def store_file(
+ self,
+ artifact_id: str,
+ artifact_manifest_id: str,
+ entry: ArtifactManifestEntry,
+ preparer: StepPrepare,
+ progress_callback: progress.ProgressFn | None = None,
+ ) -> bool:
+ """Upload a file to the artifact store.
+
+ Returns:
+ True if the file was a duplicate (did not need to be uploaded),
+ False if it needed to be uploaded or was a reference (nothing to dedupe).
+ """
+ file_size = entry.size or 0
+ chunk_size = calc_part_size(file_size)
+ file_path = entry.local_path or ""
+ # Logic for AWS s3 multipart upload.
+ # Only chunk files if larger than 2 GiB. Currently can only support up to 5TiB.
+ if MIN_MULTI_UPLOAD_SIZE <= file_size <= MAX_MULTI_UPLOAD_SIZE:
+ file_chunks = scan_chunks(file_path, chunk_size)
+ upload_parts = [
+ {"partNumber": num, "hexMD5": hashlib.md5(data).hexdigest()}
+ for num, data in enumerate(file_chunks, start=1)
+ ]
+ hex_digests = dict(map(itemgetter("partNumber", "hexMD5"), upload_parts))
+ else:
+ upload_parts = []
+ hex_digests = {}
+
+ resp = preparer.prepare(
+ {
+ "artifactID": artifact_id,
+ "artifactManifestID": artifact_manifest_id,
+ "name": entry.path,
+ "md5": entry.digest,
+ "uploadPartsInput": upload_parts,
+ }
+ ).get()
+
+ entry.birth_artifact_id = resp.birth_artifact_id
+
+ if resp.upload_url is None:
+ return True
+ if entry.local_path is None:
+ return False
+
+ extra_headers = dict(hdr.split(":", 1) for hdr in (resp.upload_headers or []))
+
+ # This multipart upload isn't available, do a regular single url upload
+ if (multipart_urls := resp.multipart_upload_urls) is None and resp.upload_url:
+ self.default_file_upload(
+ resp.upload_url, file_path, extra_headers, progress_callback
+ )
+ elif multipart_urls is None:
+ raise ValueError(f"No multipart urls to upload for file: {file_path}")
+ else:
+ # Upload files using s3 multipart upload urls
+ etags = self.s3_multipart_file_upload(
+ file_path,
+ chunk_size,
+ hex_digests,
+ multipart_urls,
+ extra_headers,
+ )
+ assert resp.storage_path is not None
+ self._api.complete_multipart_upload_artifact(
+ artifact_id, resp.storage_path, etags, resp.upload_id
+ )
+ self._write_cache(entry)
+
+ return False
+
+ def _write_cache(self, entry: ArtifactManifestEntry) -> None:
+ if entry.local_path is None:
+ return
+
+ # Cache upon successful upload.
+ _, hit, cache_open = self._cache.check_md5_obj_path(
+ entry.digest,
+ size=entry.size or 0,
+ )
+
+ staging_dir = get_staging_dir()
+ try:
+ if not (entry.skip_cache or hit):
+ with cache_open("wb") as f, open(entry.local_path, "rb") as src:
+ shutil.copyfileobj(src, f)
+ if entry.local_path.startswith(staging_dir):
+ # Delete staged files here instead of waiting till
+ # all the files are uploaded
+ os.chmod(entry.local_path, 0o600)
+ os.remove(entry.local_path)
+ except OSError as e:
+ termwarn(f"Failed to cache {entry.local_path}, ignoring {e}")
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_policy.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_policy.py
new file mode 100644
index 0000000000000000000000000000000000000000..258839fc001f42bc886eb4008fe51148b9d13288
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/artifacts/storage_policy.py
@@ -0,0 +1,88 @@
+"""Storage policy."""
+
+from __future__ import annotations
+
+import concurrent.futures
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING, Any
+
+from wandb.sdk.internal.internal_api import Api as InternalApi
+from wandb.sdk.lib.paths import FilePathStr, URIStr
+
+if TYPE_CHECKING:
+ from wandb.filesync.step_prepare import StepPrepare
+ from wandb.sdk.artifacts.artifact import Artifact
+ from wandb.sdk.artifacts.artifact_manifest_entry import ArtifactManifestEntry
+ from wandb.sdk.internal.progress import ProgressFn
+
+
+_POLICY_REGISTRY: dict[str, type[StoragePolicy]] = {}
+
+
+class StoragePolicy(ABC):
+ def __init_subclass__(cls, **kwargs: Any) -> None:
+ super().__init_subclass__(**kwargs)
+ _POLICY_REGISTRY[cls.name()] = cls
+
+ @classmethod
+ def lookup_by_name(cls, name: str) -> type[StoragePolicy]:
+ if policy := _POLICY_REGISTRY.get(name):
+ return policy
+ raise ValueError(f"Failed to find storage policy {name!r}")
+
+ @classmethod
+ @abstractmethod
+ def name(cls) -> str:
+ raise NotImplementedError
+
+ @classmethod
+ @abstractmethod
+ def from_config(
+ cls, config: dict[str, Any], api: InternalApi | None = None
+ ) -> StoragePolicy:
+ raise NotImplementedError
+
+ @abstractmethod
+ def config(self) -> dict[str, Any]:
+ raise NotImplementedError
+
+ @abstractmethod
+ def load_file(
+ self,
+ artifact: Artifact,
+ manifest_entry: ArtifactManifestEntry,
+ dest_path: str | None = None,
+ executor: concurrent.futures.Executor | None = None,
+ ) -> FilePathStr:
+ raise NotImplementedError
+
+ @abstractmethod
+ def store_file(
+ self,
+ artifact_id: str,
+ artifact_manifest_id: str,
+ entry: ArtifactManifestEntry,
+ preparer: StepPrepare,
+ progress_callback: ProgressFn | None = None,
+ ) -> bool:
+ raise NotImplementedError
+
+ @abstractmethod
+ def store_reference(
+ self,
+ artifact: Artifact,
+ path: URIStr | FilePathStr,
+ name: str | None = None,
+ checksum: bool = True,
+ max_objects: int | None = None,
+ ) -> list[ArtifactManifestEntry]:
+ raise NotImplementedError
+
+ @abstractmethod
+ def load_reference(
+ self,
+ manifest_entry: ArtifactManifestEntry,
+ local: bool = False,
+ dest_path: str | None = None,
+ ) -> FilePathStr | URIStr:
+ raise NotImplementedError
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/backend/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/backend/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/backend/backend.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/backend/backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..87079251b0a18de4be064cddd6d92069d4c9d052
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/backend/backend.py
@@ -0,0 +1,57 @@
+"""Backend - Send to internal process.
+
+Manage backend.
+
+"""
+
+import logging
+from typing import TYPE_CHECKING, Optional
+
+from wandb.sdk.interface.interface import InterfaceBase
+from wandb.sdk.wandb_settings import Settings
+
+if TYPE_CHECKING:
+ from wandb.sdk.lib.service import service_connection
+
+logger = logging.getLogger("wandb")
+
+
+class Backend:
+ interface: Optional[InterfaceBase]
+
+ _settings: Settings
+
+ _done: bool
+
+ _service: Optional["service_connection.ServiceConnection"]
+
+ def __init__(
+ self,
+ settings: Settings,
+ service: Optional["service_connection.ServiceConnection"] = None,
+ ) -> None:
+ self._done = False
+
+ self.interface = None
+
+ self._settings = settings
+ self._service = service
+
+ def ensure_launched(self) -> None:
+ """Launch backend worker if not running."""
+ assert self._settings.run_id
+ assert self._service
+ self.interface = self._service.make_interface(
+ stream_id=self._settings.run_id,
+ )
+
+ def server_status(self) -> None:
+ """Report server status."""
+
+ def cleanup(self) -> None:
+ # TODO: make _done atomic
+ if self._done:
+ return
+ self._done = True
+ if self.interface:
+ self.interface.join()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/_dtypes.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/_dtypes.py
new file mode 100644
index 0000000000000000000000000000000000000000..015b6af0501266264dcf710ce6f883a3c0f7dad9
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/_dtypes.py
@@ -0,0 +1,914 @@
+import datetime
+import math
+import typing as t
+
+from wandb.util import (
+ _is_artifact_string,
+ _is_artifact_version_weave_dict,
+ get_module,
+ is_numpy_array,
+)
+
+np = get_module("numpy") # intentionally not required
+
+if t.TYPE_CHECKING:
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ConvertibleToType = t.Union["Type", t.Type["Type"], type, t.Any]
+
+
+class TypeRegistry:
+ """A resolver for python objects that can deserialize JSON dicts.
+
+ Additional types can be registered via the .add call.
+ """
+
+ _types_by_name = None
+ _types_by_class = None
+
+ @staticmethod
+ def types_by_name():
+ if TypeRegistry._types_by_name is None:
+ TypeRegistry._types_by_name = {}
+ return TypeRegistry._types_by_name
+
+ @staticmethod
+ def types_by_class():
+ if TypeRegistry._types_by_class is None:
+ TypeRegistry._types_by_class = {}
+ return TypeRegistry._types_by_class
+
+ @staticmethod
+ def add(wb_type: t.Type["Type"]) -> None:
+ assert issubclass(wb_type, Type)
+ TypeRegistry.types_by_name().update({wb_type.name: wb_type})
+ for name in wb_type.legacy_names:
+ TypeRegistry.types_by_name().update({name: wb_type})
+ TypeRegistry.types_by_class().update(
+ {_type: wb_type for _type in wb_type.types}
+ )
+
+ @staticmethod
+ def type_of(py_obj: t.Optional[t.Any]) -> "Type":
+ # Special case handler for common case of np.nans. np.nan
+ # is of type 'float', but should be treated as a None. This is
+ # because np.nan can co-exist with other types in dataframes,
+ # but will be ultimately treated as a None. Ignoring type since
+ # mypy does not trust that py_obj is a float by the time it is
+ # passed to isnan.
+ if py_obj.__class__ is float and math.isnan(py_obj): # type: ignore
+ return NoneType()
+
+ # TODO: generalize this to handle other config input types
+ if _is_artifact_string(py_obj) or _is_artifact_version_weave_dict(py_obj):
+ return TypeRegistry.types_by_name().get("artifactVersion")()
+
+ class_handler = TypeRegistry.types_by_class().get(py_obj.__class__)
+ _type = None
+ if class_handler:
+ _type = class_handler.from_obj(py_obj)
+ else:
+ _type = PythonObjectType.from_obj(py_obj)
+ return _type
+
+ @staticmethod
+ def type_from_dict(
+ json_dict: t.Dict[str, t.Any], artifact: t.Optional["Artifact"] = None
+ ) -> "Type":
+ wb_type = json_dict.get("wb_type")
+ if wb_type is None:
+ TypeError("json_dict must contain `wb_type` key")
+ _type = TypeRegistry.types_by_name().get(wb_type)
+ if _type is None:
+ TypeError(f"missing type handler for {wb_type}")
+ return _type.from_json(json_dict, artifact)
+
+ @staticmethod
+ def type_from_dtype(dtype: ConvertibleToType) -> "Type":
+ # The dtype is already an instance of Type
+ if isinstance(dtype, Type):
+ wbtype: Type = dtype
+
+ # The dtype is a subclass of Type
+ elif isinstance(dtype, type) and issubclass(dtype, Type):
+ wbtype = dtype()
+
+ # The dtype is a subclass of generic python type
+ elif isinstance(dtype, type):
+ handler = TypeRegistry.types_by_class().get(dtype)
+
+ # and we have a registered handler
+ if handler:
+ wbtype = handler()
+
+ # else, fallback to object type
+ else:
+ wbtype = PythonObjectType.from_obj(dtype)
+
+ # The dtype is a list, then we resolve the list notation
+ elif isinstance(dtype, list):
+ if len(dtype) == 0:
+ wbtype = ListType()
+ elif len(dtype) == 1:
+ wbtype = ListType(TypeRegistry.type_from_dtype(dtype[0]))
+
+ # lists of more than 1 are treated as unions
+ else:
+ wbtype = UnionType([TypeRegistry.type_from_dtype(dt) for dt in dtype])
+
+ # The dtype is a dict, then we resolve the dict notation
+ elif isinstance(dtype, dict):
+ wbtype = TypedDictType(
+ {key: TypeRegistry.type_from_dtype(dtype[key]) for key in dtype}
+ )
+
+ # The dtype is a concrete instance, which we will treat as a constant
+ else:
+ wbtype = ConstType(dtype)
+
+ return wbtype
+
+
+def _params_obj_to_json_obj(
+ params_obj: t.Any,
+ artifact: t.Optional["Artifact"] = None,
+) -> t.Any:
+ """Helper method."""
+ if params_obj.__class__ is dict:
+ return {
+ key: _params_obj_to_json_obj(params_obj[key], artifact)
+ for key in params_obj
+ }
+ elif params_obj.__class__ in [list, set, tuple, frozenset]:
+ return [_params_obj_to_json_obj(item, artifact) for item in list(params_obj)]
+ elif isinstance(params_obj, Type):
+ return params_obj.to_json(artifact)
+ else:
+ return params_obj
+
+
+def _json_obj_to_params_obj(
+ json_obj: t.Any, artifact: t.Optional["Artifact"] = None
+) -> t.Any:
+ """Helper method."""
+ if json_obj.__class__ is dict:
+ if "wb_type" in json_obj:
+ return TypeRegistry.type_from_dict(json_obj, artifact)
+ else:
+ return {
+ key: _json_obj_to_params_obj(json_obj[key], artifact)
+ for key in json_obj
+ }
+ elif json_obj.__class__ is list:
+ return [_json_obj_to_params_obj(item, artifact) for item in json_obj]
+ else:
+ return json_obj
+
+
+class Type:
+ """The most generic type that all types subclass.
+
+ It provides simple serialization and deserialization as well as equality checks.
+ A name class-level property must be uniquely set by subclasses.
+ """
+
+ # Subclasses must override with a unique name. This is used to identify the
+ # class during serializations and deserializations
+ name: t.ClassVar[str] = ""
+
+ # List of names by which this class can deserialize
+ legacy_names: t.ClassVar[t.List[str]] = []
+
+ # Subclasses may override with a list of `types` which this Type is capable
+ # of being initialized. This is used by the Type Registry when calling `TypeRegistry.type_of`.
+ # Some types will have an empty list - for example `Union`. There is no raw python type which
+ # inherently maps to a Union and therefore the list should be empty.
+ types: t.ClassVar[t.List[type]] = []
+
+ # Contains the further specification of the Type
+ _params: t.Dict[str, t.Any]
+
+ def __init__(*args, **kwargs):
+ pass
+
+ @property
+ def params(self):
+ if not hasattr(self, "_params") or self._params is None:
+ self._params = {}
+ return self._params
+
+ def assign(self, py_obj: t.Optional[t.Any] = None) -> "Type":
+ """Assign a python object to the type.
+
+ May to be overridden by subclasses
+
+ Args:
+ py_obj (any, optional): Any python object which the user wishes to assign to
+ this type
+
+ Returns:
+ Type: a new type representing the result of the assignment.
+ """
+ return self.assign_type(TypeRegistry.type_of(py_obj))
+
+ def assign_type(self, wb_type: "Type") -> "Type":
+ # Default - should be overridden
+ if isinstance(wb_type, self.__class__) and self.params == wb_type.params:
+ return self
+ else:
+ return InvalidType()
+
+ def to_json(self, artifact: t.Optional["Artifact"] = None) -> t.Dict[str, t.Any]:
+ """Generate a jsonable dictionary serialization the type.
+
+ If overridden by subclass, ensure that `from_json` is equivalently overridden.
+
+ Args:
+ artifact (wandb.Artifact, optional): If the serialization is being performed
+ for a particular artifact, pass that artifact. Defaults to None.
+
+ Returns:
+ dict: Representation of the type
+ """
+ res = {
+ "wb_type": self.name,
+ "params": _params_obj_to_json_obj(self.params, artifact),
+ }
+ if res["params"] is None or res["params"] == {}:
+ del res["params"]
+
+ return res
+
+ @classmethod
+ def from_json(
+ cls,
+ json_dict: t.Dict[str, t.Any],
+ artifact: t.Optional["Artifact"] = None,
+ ) -> "Type":
+ """Construct a new instance of the type using a JSON dictionary.
+
+ The mirror function of `to_json`. If overridden by subclass, ensure that
+ `to_json` is equivalently overridden.
+
+ Returns:
+ _Type: an instance of a subclass of the _Type class.
+ """
+ return cls(**_json_obj_to_params_obj(json_dict.get("params", {}), artifact))
+
+ @classmethod
+ def from_obj(cls, py_obj: t.Optional[t.Any] = None) -> "Type":
+ return cls()
+
+ def explain(self, other: t.Any, depth=0) -> str:
+ """Explain why an item is not assignable to a type.
+
+ Assumes that the caller has already validated that the assignment fails.
+
+ Args:
+ other (any): Any object depth (int, optional): depth of the type checking.
+ Defaults to 0.
+
+ Returns:
+ str: human-readable explanation
+ """
+ wbtype = TypeRegistry.type_of(other)
+ gap = "".join(["\t"] * depth)
+ if depth > 0:
+ return f"{gap}{wbtype} not assignable to {self}"
+ else:
+ return f"{gap}{other} of type {wbtype} is not assignable to {self}"
+
+ def __repr__(self):
+ rep = self.name.capitalize()
+ if len(self.params.keys()) > 0:
+ rep += "("
+ for ndx, key in enumerate(self.params.keys()):
+ if ndx > 0:
+ rep += ", "
+ rep += key + ":" + str(self.params[key])
+ rep += ")"
+ return rep
+
+ def __eq__(self, other):
+ return self is other or (
+ isinstance(self, Type)
+ and isinstance(other, Type)
+ and self.name == other.name
+ and self.params.keys() == other.params.keys()
+ and all([self.params[k] == other.params[k] for k in self.params])
+ )
+
+
+class InvalidType(Type):
+ """A disallowed type.
+
+ Assignments to a InvalidType result in a Never Type. InvalidType is basically the
+ invalid case.
+ """
+
+ name = "invalid"
+ types: t.ClassVar[t.List[type]] = []
+
+ def assign_type(self, wb_type: "Type") -> "InvalidType":
+ return self
+
+
+class AnyType(Type):
+ """An object that can be any type.
+
+ Assignments to an AnyType result in the AnyType except None which results in an
+ InvalidType.
+ """
+
+ name = "any"
+ types: t.ClassVar[t.List[type]] = []
+
+ def assign_type(self, wb_type: "Type") -> t.Union["AnyType", InvalidType]:
+ return (
+ self
+ if not (isinstance(wb_type, NoneType) or isinstance(wb_type, InvalidType))
+ else InvalidType()
+ )
+
+
+class UnknownType(Type):
+ """An object with an unknown type.
+
+ All assignments to an UnknownType result in the type of the assigned object except
+ `None` which results in a InvalidType.
+ """
+
+ name = "unknown"
+ types: t.ClassVar[t.List[type]] = []
+
+ def assign_type(self, wb_type: "Type") -> "Type":
+ return wb_type if not isinstance(wb_type, NoneType) else InvalidType()
+
+
+class NoneType(Type):
+ name = "none"
+ types: t.ClassVar[t.List[type]] = [None.__class__]
+
+
+class StringType(Type):
+ name = "string"
+ types: t.ClassVar[t.List[type]] = [str]
+
+
+class NumberType(Type):
+ name = "number"
+ types: t.ClassVar[t.List[type]] = [int, float]
+
+
+if np:
+ NumberType.types.append(np.byte)
+ NumberType.types.append(np.short)
+ NumberType.types.append(np.ushort)
+ NumberType.types.append(np.intc)
+ NumberType.types.append(np.uintc)
+ NumberType.types.append(np.int_)
+ NumberType.types.append(np.uint)
+ NumberType.types.append(np.longlong)
+ NumberType.types.append(np.ulonglong)
+ NumberType.types.append(np.half)
+ NumberType.types.append(np.float16)
+ NumberType.types.append(np.single)
+ NumberType.types.append(np.double)
+ NumberType.types.append(np.longdouble)
+ NumberType.types.append(np.csingle)
+ NumberType.types.append(np.cdouble)
+ NumberType.types.append(np.clongdouble)
+ NumberType.types.append(np.int8)
+ NumberType.types.append(np.int16)
+ NumberType.types.append(np.int32)
+ NumberType.types.append(np.int64)
+ NumberType.types.append(np.uint8)
+ NumberType.types.append(np.uint16)
+ NumberType.types.append(np.uint32)
+ NumberType.types.append(np.uint64)
+ NumberType.types.append(np.intp)
+ NumberType.types.append(np.uintp)
+ NumberType.types.append(np.float32)
+ NumberType.types.append(np.float64)
+ NumberType.types.append(np.complex64)
+ NumberType.types.append(np.complex128)
+
+ numpy_major_version = np.__version__.split(".")[0]
+ if int(numpy_major_version) < 2:
+ NumberType.types.append(np.float_)
+ NumberType.types.append(np.complex_)
+
+
+class TimestampType(Type):
+ name = "timestamp"
+ types: t.ClassVar[t.List[type]] = [datetime.datetime, datetime.date]
+
+
+if np:
+ TimestampType.types.append(np.datetime64)
+
+
+class BooleanType(Type):
+ name = "boolean"
+ types: t.ClassVar[t.List[type]] = [bool]
+
+
+if np:
+ BooleanType.types.append(np.bool_)
+
+
+class PythonObjectType(Type):
+ """A backup type that keeps track of the python object name."""
+
+ name = "pythonObject"
+ legacy_names = ["object"]
+ types: t.ClassVar[t.List[type]] = []
+
+ def __init__(self, class_name: str):
+ self.params.update({"class_name": class_name})
+
+ @classmethod
+ def from_obj(cls, py_obj: t.Optional[t.Any] = None) -> "PythonObjectType":
+ return cls(py_obj.__class__.__name__)
+
+
+class ConstType(Type):
+ """A constant value (currently only primitives supported)."""
+
+ name = "const"
+ types: t.ClassVar[t.List[type]] = []
+
+ def __init__(self, val: t.Optional[t.Any] = None, is_set: t.Optional[bool] = False):
+ if val.__class__ not in [str, int, float, bool, set, list, None.__class__]:
+ TypeError(
+ f"ConstType only supports str, int, float, bool, set, list, and None types. Found {val}"
+ )
+ if is_set or isinstance(val, set):
+ is_set = True
+ assert isinstance(val, set) or isinstance(val, list)
+ val = set(val)
+
+ self.params.update({"val": val, "is_set": is_set})
+
+ def assign(self, py_obj: t.Optional[t.Any] = None) -> "Type":
+ return self.assign_type(ConstType(py_obj))
+
+ @classmethod
+ def from_obj(cls, py_obj: t.Optional[t.Any] = None) -> "ConstType":
+ return cls(py_obj)
+
+ def __repr__(self):
+ return str(self.params["val"])
+
+
+def _flatten_union_types(wb_types: t.List[Type]) -> t.List[Type]:
+ final_types = []
+ for allowed_type in wb_types:
+ if isinstance(allowed_type, UnionType):
+ internal_types = _flatten_union_types(allowed_type.params["allowed_types"])
+ for internal_type in internal_types:
+ final_types.append(internal_type)
+ else:
+ final_types.append(allowed_type)
+ return final_types
+
+
+def _union_assigner(
+ allowed_types: t.List[Type],
+ obj_or_type: t.Union[Type, t.Optional[t.Any]],
+ type_mode=False,
+) -> t.Union[t.List[Type], InvalidType]:
+ resolved_types = []
+ valid = False
+ unknown_count = 0
+
+ for allowed_type in allowed_types:
+ if valid:
+ resolved_types.append(allowed_type)
+ else:
+ if isinstance(allowed_type, UnknownType):
+ unknown_count += 1
+ else:
+ if type_mode:
+ assert isinstance(obj_or_type, Type)
+ assigned_type = allowed_type.assign_type(obj_or_type)
+ else:
+ assigned_type = allowed_type.assign(obj_or_type)
+ if isinstance(assigned_type, InvalidType):
+ resolved_types.append(allowed_type)
+ else:
+ resolved_types.append(assigned_type)
+ valid = True
+
+ if not valid:
+ if unknown_count == 0:
+ return InvalidType()
+ else:
+ if type_mode:
+ assert isinstance(obj_or_type, Type)
+ new_type = obj_or_type
+ else:
+ new_type = UnknownType().assign(obj_or_type)
+ if isinstance(new_type, InvalidType):
+ return InvalidType()
+ else:
+ resolved_types.append(new_type)
+ unknown_count -= 1
+
+ for _ in range(unknown_count):
+ resolved_types.append(UnknownType())
+
+ resolved_types = _flatten_union_types(resolved_types)
+ resolved_types.sort(key=str)
+ return resolved_types
+
+
+class UnionType(Type):
+ """An "or" of types."""
+
+ name = "union"
+ types: t.ClassVar[t.List[type]] = []
+
+ def __init__(
+ self,
+ allowed_types: t.Optional[t.Sequence[ConvertibleToType]] = None,
+ ):
+ assert allowed_types is None or (allowed_types.__class__ is list)
+ if allowed_types is None:
+ wb_types = []
+ else:
+ wb_types = [TypeRegistry.type_from_dtype(dt) for dt in allowed_types]
+
+ wb_types = _flatten_union_types(wb_types)
+ wb_types.sort(key=str)
+ self.params.update({"allowed_types": wb_types})
+
+ def assign(
+ self, py_obj: t.Optional[t.Any] = None
+ ) -> t.Union["UnionType", InvalidType]:
+ resolved_types = _union_assigner(
+ self.params["allowed_types"], py_obj, type_mode=False
+ )
+ if isinstance(resolved_types, InvalidType):
+ return InvalidType()
+ return self.__class__(resolved_types)
+
+ def assign_type(self, wb_type: "Type") -> t.Union["UnionType", InvalidType]:
+ if isinstance(wb_type, UnionType):
+ assignees = wb_type.params["allowed_types"]
+ else:
+ assignees = [wb_type]
+
+ resolved_types = self.params["allowed_types"]
+ for assignee in assignees:
+ resolved_types = _union_assigner(resolved_types, assignee, type_mode=True)
+ if isinstance(resolved_types, InvalidType):
+ return InvalidType()
+
+ return self.__class__(resolved_types)
+
+ def explain(self, other: t.Any, depth=0) -> str:
+ exp = super().explain(other, depth)
+ for ndx, subtype in enumerate(self.params["allowed_types"]):
+ if ndx > 0:
+ exp += "\n{}and".format("".join(["\t"] * depth))
+ exp += "\n" + subtype.explain(other, depth=depth + 1)
+ return exp
+
+ def __repr__(self):
+ return "{}".format(" or ".join([str(t) for t in self.params["allowed_types"]]))
+
+
+def OptionalType(dtype: ConvertibleToType) -> UnionType: # noqa: N802
+ """Function that mimics the Type class API for constructing an "Optional Type".
+
+ This is just a Union[wb_type, NoneType].
+
+ Args:
+ dtype (Type): type to be optional
+
+ Returns:
+ Type: Optional version of the type.
+ """
+ return UnionType([TypeRegistry.type_from_dtype(dtype), NoneType()])
+
+
+class ListType(Type):
+ """A list of homogeneous types."""
+
+ name = "list"
+ types: t.ClassVar[t.List[type]] = [list, tuple, set, frozenset]
+
+ def __init__(
+ self,
+ element_type: t.Optional[ConvertibleToType] = None,
+ length: t.Optional[int] = None,
+ ):
+ if element_type is None:
+ wb_type: Type = UnknownType()
+ else:
+ wb_type = TypeRegistry.type_from_dtype(element_type)
+
+ self.params.update({"element_type": wb_type, "length": length})
+
+ @classmethod
+ def from_obj(cls, py_obj: t.Optional[t.Any] = None) -> "ListType":
+ if py_obj is None or not hasattr(py_obj, "__iter__"):
+ raise TypeError("ListType.from_obj expects py_obj to by list-like")
+ else:
+ if hasattr(py_obj, "tolist"):
+ py_list = py_obj.tolist()
+ else:
+ py_list = list(py_obj)
+
+ elm_type: Type
+ if None not in py_list:
+ elm_type = UnknownType()
+ else:
+ elm_type = OptionalType(UnknownType())
+
+ for item in py_list:
+ _elm_type = elm_type.assign(item)
+ # Commenting this out since we don't want to crash user code at this point, but rather
+ # retain an invalid internal list type.
+ # if isinstance(_elm_type, InvalidType):
+ # raise TypeError(
+ # "List contained incompatible types. Item at index {}: \n{}".format(
+ # ndx, elm_type.explain(item, 1)
+ # )
+ # )
+
+ elm_type = _elm_type
+
+ return cls(elm_type, len(py_list))
+
+ def assign_type(self, wb_type: "Type") -> t.Union["ListType", InvalidType]:
+ if isinstance(wb_type, ListType):
+ assigned_type = self.params["element_type"].assign_type(
+ wb_type.params["element_type"]
+ )
+ if not isinstance(assigned_type, InvalidType):
+ return ListType(
+ assigned_type,
+ None
+ if self.params["length"] != wb_type.params["length"]
+ else self.params["length"],
+ )
+
+ return InvalidType()
+
+ def assign(
+ self, py_obj: t.Optional[t.Any] = None
+ ) -> t.Union["ListType", InvalidType]:
+ if hasattr(py_obj, "__iter__"):
+ new_element_type = self.params["element_type"]
+ # The following ignore is needed since the above hasattr(py_obj, "__iter__") enforces iteration
+ # error: Argument 1 to "list" has incompatible type "Optional[Any]"; expected "Iterable[Any]"
+ py_list = list(py_obj) # type: ignore
+ for obj in py_list:
+ new_element_type = new_element_type.assign(obj)
+ if isinstance(new_element_type, InvalidType):
+ return InvalidType()
+ return ListType(new_element_type, len(py_list))
+
+ return InvalidType()
+
+ def explain(self, other: t.Any, depth=0) -> str:
+ exp = super().explain(other, depth)
+ gap = "".join(["\t"] * depth)
+ if ( # yes, this is a bit verbose, but the mypy typechecker likes it this way
+ isinstance(other, list)
+ or isinstance(other, tuple)
+ or isinstance(other, set)
+ or isinstance(other, frozenset)
+ ):
+ new_element_type = self.params["element_type"]
+ for ndx, obj in enumerate(list(other)):
+ _new_element_type = new_element_type.assign(obj)
+ if isinstance(_new_element_type, InvalidType):
+ exp += f"\n{gap}Index {ndx}:\n{new_element_type.explain(obj, depth + 1)}"
+ break
+ new_element_type = _new_element_type
+ return exp
+
+ def __repr__(self):
+ return "{}[]".format(self.params["element_type"])
+
+
+class NDArrayType(Type):
+ """Represents a list of homogeneous types."""
+
+ name = "ndarray"
+ types: t.ClassVar[t.List[type]] = [] # will manually add type if np is available
+ _serialization_path: t.Optional[t.Dict[str, str]]
+
+ def __init__(
+ self,
+ shape: t.Sequence[int],
+ serialization_path: t.Optional[t.Dict[str, str]] = None,
+ ):
+ self.params.update({"shape": list(shape)})
+ self._serialization_path = serialization_path
+
+ @classmethod
+ def from_obj(cls, py_obj: t.Optional[t.Any] = None) -> "NDArrayType":
+ if is_numpy_array(py_obj):
+ return cls(py_obj.shape) # type: ignore
+ elif isinstance(py_obj, list):
+ shape = []
+ target = py_obj
+ while isinstance(target, list):
+ dim = len(target)
+ shape.append(dim)
+ if dim > 0:
+ target = target[0]
+ return cls(shape)
+ else:
+ raise TypeError(
+ f"NDArrayType.from_obj expects py_obj to be ndarray or list, found {py_obj.__class__}"
+ )
+
+ def assign_type(self, wb_type: "Type") -> t.Union["NDArrayType", InvalidType]:
+ if (
+ isinstance(wb_type, NDArrayType)
+ and self.params["shape"] == wb_type.params["shape"]
+ ):
+ return self
+ elif isinstance(wb_type, ListType):
+ # Should we return error here?
+ return self
+
+ return InvalidType()
+
+ def assign(
+ self, py_obj: t.Optional[t.Any] = None
+ ) -> t.Union["NDArrayType", InvalidType]:
+ if is_numpy_array(py_obj) or isinstance(py_obj, list):
+ py_type = self.from_obj(py_obj)
+ return self.assign_type(py_type)
+
+ return InvalidType()
+
+ def to_json(self, artifact: t.Optional["Artifact"] = None) -> t.Dict[str, t.Any]:
+ # custom override to support serialization path outside of params internal dict
+ res = {
+ "wb_type": self.name,
+ "params": {
+ "shape": self.params["shape"],
+ "serialization_path": self._serialization_path,
+ },
+ }
+
+ return res
+
+ def _get_serialization_path(self) -> t.Optional[t.Dict[str, str]]:
+ return self._serialization_path
+
+ def _set_serialization_path(self, path: str, key: str) -> None:
+ self._serialization_path = {"path": path, "key": key}
+
+ def _clear_serialization_path(self) -> None:
+ self._serialization_path = None
+
+
+if np:
+ NDArrayType.types.append(np.ndarray)
+
+# class KeyPolicy:
+# EXACT = "E" # require exact key match
+# SUBSET = "S" # all known keys are optional and unknown keys are disallowed
+# UNRESTRICTED = "U" # all known keys are optional and unknown keys are Unknown
+
+
+class TypedDictType(Type):
+ """Represents a dictionary object where each key can have a type."""
+
+ name = "typedDict"
+ legacy_names = ["dictionary"]
+ types: t.ClassVar[t.List[type]] = [dict]
+
+ def __init__(
+ self,
+ type_map: t.Optional[t.Dict[str, ConvertibleToType]] = None,
+ ):
+ if type_map is None:
+ type_map = {}
+ self.params.update(
+ {
+ "type_map": {
+ key: TypeRegistry.type_from_dtype(type_map[key]) for key in type_map
+ }
+ }
+ )
+
+ @classmethod
+ def from_obj(cls, py_obj: t.Optional[t.Any] = None) -> "TypedDictType":
+ if not isinstance(py_obj, dict):
+ TypeError("TypedDictType.from_obj expects a dictionary")
+
+ assert isinstance(py_obj, dict) # helps mypy type checker
+ return cls({key: TypeRegistry.type_of(py_obj[key]) for key in py_obj})
+
+ def assign_type(self, wb_type: "Type") -> t.Union["TypedDictType", InvalidType]:
+ if (
+ isinstance(wb_type, TypedDictType)
+ and len(
+ set(wb_type.params["type_map"].keys())
+ - set(self.params["type_map"].keys())
+ )
+ == 0
+ ):
+ type_map = {}
+ for key in self.params["type_map"]:
+ type_map[key] = self.params["type_map"][key].assign_type(
+ wb_type.params["type_map"].get(key, UnknownType())
+ )
+ if isinstance(type_map[key], InvalidType):
+ return InvalidType()
+ return TypedDictType(type_map)
+
+ return InvalidType()
+
+ def assign(
+ self, py_obj: t.Optional[t.Any] = None
+ ) -> t.Union["TypedDictType", InvalidType]:
+ if (
+ isinstance(py_obj, dict)
+ and len(set(py_obj.keys()) - set(self.params["type_map"].keys())) == 0
+ ):
+ type_map = {}
+ for key in self.params["type_map"]:
+ type_map[key] = self.params["type_map"][key].assign(
+ py_obj.get(key, None)
+ )
+ if isinstance(type_map[key], InvalidType):
+ return InvalidType()
+ return TypedDictType(type_map)
+
+ return InvalidType()
+
+ def explain(self, other: t.Any, depth=0) -> str:
+ exp = super().explain(other, depth)
+ gap = "".join(["\t"] * depth)
+ if isinstance(other, dict):
+ extra_keys = set(other.keys()) - set(self.params["type_map"].keys())
+ if len(extra_keys) > 0:
+ exp += "\n{}Found extra keys: {}".format(
+ gap, ",".join(list(extra_keys))
+ )
+
+ for key in self.params["type_map"]:
+ val = other.get(key, None)
+ if isinstance(self.params["type_map"][key].assign(val), InvalidType):
+ exp += "\n{}Key '{}':\n{}".format(
+ gap,
+ key,
+ self.params["type_map"][key].explain(val, depth=depth + 1),
+ )
+ return exp
+
+ def __repr__(self):
+ return "{}".format(self.params["type_map"])
+
+
+# Special Types
+TypeRegistry.add(InvalidType)
+TypeRegistry.add(AnyType)
+TypeRegistry.add(UnknownType)
+
+# Types with default type mappings
+TypeRegistry.add(NoneType)
+TypeRegistry.add(StringType)
+TypeRegistry.add(TimestampType)
+TypeRegistry.add(NumberType)
+TypeRegistry.add(BooleanType)
+TypeRegistry.add(ListType)
+TypeRegistry.add(TypedDictType)
+
+# Types without default type mappings
+TypeRegistry.add(UnionType)
+TypeRegistry.add(PythonObjectType)
+TypeRegistry.add(ConstType)
+
+# Common Industry Types
+TypeRegistry.add(NDArrayType)
+
+__all__ = [
+ "TypeRegistry",
+ "InvalidType",
+ "UnknownType",
+ "AnyType",
+ "NoneType",
+ "StringType",
+ "NumberType",
+ "TimestampType",
+ "BooleanType",
+ "ListType",
+ "TypedDictType",
+ "UnionType",
+ "PythonObjectType",
+ "ConstType",
+ "OptionalType",
+ "Type",
+ "NDArrayType",
+]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/_private.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/_private.py
new file mode 100644
index 0000000000000000000000000000000000000000..887bc8a231014d06dbe65590663064ec792eeb84
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/_private.py
@@ -0,0 +1,10 @@
+import atexit
+import tempfile
+
+# Staging directory, so we can encode raw data into files, then hash them before
+# we put them into the Run directory to be uploaded.
+MEDIA_TMP = tempfile.TemporaryDirectory("wandb-media")
+
+
+def _cleanup_media_tmp_dir() -> None:
+ atexit.register(MEDIA_TMP.cleanup)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/audio.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/audio.py
new file mode 100644
index 0000000000000000000000000000000000000000..a77950ba13cc4fb8e14b28b6e32ea3a9074cee91
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/audio.py
@@ -0,0 +1,208 @@
+import hashlib
+import os
+import pathlib
+from typing import TYPE_CHECKING, Optional, Union
+
+from wandb import util
+from wandb.sdk.lib import filesystem, runid
+
+from . import _dtypes
+from ._private import MEDIA_TMP
+from .base_types.media import BatchableMedia
+
+if TYPE_CHECKING:
+ import numpy as np
+
+
+class Audio(BatchableMedia):
+ """W&B class for audio clips."""
+
+ _log_type = "audio-file"
+
+ def __init__(
+ self,
+ data_or_path: Union[
+ str,
+ pathlib.Path,
+ list,
+ "np.ndarray",
+ ],
+ sample_rate: Optional[int] = None,
+ caption: Optional[str] = None,
+ ):
+ """Accept a path to an audio file or a numpy array of audio data.
+
+ Args:
+ data_or_path: A path to an audio file or a NumPy array of audio data.
+ sample_rate: Sample rate, required when passing in raw NumPy array of audio data.
+ caption: Caption to display with audio.
+ """
+ super().__init__(caption=caption)
+ self._duration = None
+ self._sample_rate = sample_rate
+
+ if isinstance(data_or_path, (str, pathlib.Path)):
+ data_or_path = str(data_or_path)
+
+ if self.path_is_reference(data_or_path):
+ self._path = data_or_path
+ self._sha256 = hashlib.sha256(data_or_path.encode("utf-8")).hexdigest()
+ self._is_tmp = False
+ else:
+ self._set_file(data_or_path, is_tmp=False)
+ else:
+ if sample_rate is None:
+ raise ValueError(
+ 'Argument "sample_rate" is required when instantiating wandb.Audio with raw data.'
+ )
+
+ soundfile = util.get_module(
+ "soundfile",
+ required='Raw audio requires the soundfile package. To get it, run "pip install soundfile"',
+ )
+
+ tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ".wav")
+
+ soundfile.write(tmp_path, data_or_path, sample_rate)
+ self._duration = len(data_or_path) / float(sample_rate)
+
+ self._set_file(tmp_path, is_tmp=True)
+
+ @classmethod
+ def get_media_subdir(cls):
+ """Get media subdirectory.
+
+
+ """
+ return os.path.join("media", "audio")
+
+ @classmethod
+ def from_json(cls, json_obj, source_artifact):
+ """Deserialize JSON object into it's class representation.
+
+
+ """
+ return cls(
+ source_artifact.get_entry(json_obj["path"]).download(),
+ caption=json_obj["caption"],
+ )
+
+ def bind_to_run(
+ self, run, key, step, id_=None, ignore_copy_err: Optional[bool] = None
+ ):
+ """Bind this object to a run.
+
+
+ """
+ if self.path_is_reference(self._path):
+ raise ValueError(
+ "Audio media created by a reference to external storage cannot currently be added to a run"
+ )
+
+ return super().bind_to_run(run, key, step, id_, ignore_copy_err)
+
+ def to_json(self, run):
+ """Returns the JSON representation expected by the backend.
+
+
+ """
+ json_dict = super().to_json(run)
+ json_dict.update(
+ {
+ "_type": self._log_type,
+ }
+ )
+ return json_dict
+
+ @classmethod
+ def seq_to_json(cls, seq, run, key, step):
+ """Convert a sequence of Audio objects to a JSON representation.
+
+
+ """
+ audio_list = list(seq)
+
+ util.get_module(
+ "soundfile",
+ required="wandb.Audio requires the soundfile package. To get it, run: pip install soundfile",
+ )
+ base_path = os.path.join(run.dir, "media", "audio")
+ filesystem.mkdir_exists_ok(base_path)
+ meta = {
+ "_type": "audio",
+ "count": len(audio_list),
+ "audio": [a.to_json(run) for a in audio_list],
+ }
+ sample_rates = cls.sample_rates(audio_list)
+ if sample_rates:
+ meta["sampleRates"] = sample_rates
+ durations = cls.durations(audio_list)
+ if durations:
+ meta["durations"] = durations
+ captions = cls.captions(audio_list)
+ if captions:
+ meta["captions"] = captions
+
+ return meta
+
+ @classmethod
+ def durations(cls, audio_list):
+ """Calculate the duration of the audio files."""
+ return [a._duration for a in audio_list]
+
+ @classmethod
+ def sample_rates(cls, audio_list):
+ """Get sample rates of the audio files."""
+ return [a._sample_rate for a in audio_list]
+
+ @classmethod
+ def captions(cls, audio_list):
+ """Get the captions of the audio files.
+
+
+ """
+ captions = [a._caption for a in audio_list]
+ if all(c is None for c in captions):
+ return False
+ else:
+ return ["" if c is None else c for c in captions]
+
+ def resolve_ref(self):
+ """Resolve the reference to the actual file path.
+
+
+ """
+ if self.path_is_reference(self._path):
+ # this object was already created using a ref:
+ return self._path
+ source_artifact = self._artifact_source.artifact
+
+ resolved_name = source_artifact._local_path_to_name(self._path)
+ if resolved_name is not None:
+ target_entry = source_artifact.manifest.get_entry_by_path(resolved_name)
+ if target_entry is not None:
+ return target_entry.ref
+
+ return None
+
+ def __eq__(self, other):
+ if self.path_is_reference(self._path) or self.path_is_reference(other._path):
+ # one or more of these objects is an unresolved reference -- we'll compare
+ # their reference paths instead of their SHAs:
+ return (
+ self.resolve_ref() == other.resolve_ref()
+ and self._caption == other._caption
+ )
+
+ return super().__eq__(other) and self._caption == other._caption
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+
+class _AudioFileType(_dtypes.Type):
+ name = "audio-file"
+ types = [Audio]
+
+
+_dtypes.TypeRegistry.add(_AudioFileType)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/base_types/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/base_types/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/base_types/json_metadata.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/base_types/json_metadata.py
new file mode 100644
index 0000000000000000000000000000000000000000..b644584abcf1a640c35a1c98e7b7083999f3b446
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/base_types/json_metadata.py
@@ -0,0 +1,55 @@
+import codecs
+import os
+from typing import TYPE_CHECKING, Type, Union
+
+from wandb import util
+from wandb.sdk.lib import runid
+
+from .._private import MEDIA_TMP
+from .media import Media
+
+if TYPE_CHECKING: # pragma: no cover
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ from ...wandb_run import Run as LocalRun
+
+
+# Allows encoding of arbitrary JSON structures
+# as a file
+#
+# This class should be used as an abstract class
+# extended to have validation methods
+
+
+class JSONMetadata(Media):
+ """JSONMetadata is a type for encoding arbitrary metadata as files."""
+
+ def __init__(self, val: dict) -> None:
+ super().__init__()
+
+ self.validate(val)
+ self._val = val
+
+ ext = "." + self.type_name() + ".json"
+ tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ext)
+ with codecs.open(tmp_path, "w", encoding="utf-8") as fp:
+ util.json_dump_uncompressed(self._val, fp)
+ self._set_file(tmp_path, is_tmp=True, extension=ext)
+
+ @classmethod
+ def get_media_subdir(cls: Type["JSONMetadata"]) -> str:
+ return os.path.join("media", "metadata", cls.type_name())
+
+ def to_json(self, run_or_artifact: Union["LocalRun", "Artifact"]) -> dict:
+ json_dict = super().to_json(run_or_artifact)
+ json_dict["_type"] = self.type_name()
+
+ return json_dict
+
+ # These methods should be overridden in the child class
+ @classmethod
+ def type_name(cls) -> str:
+ return "metadata"
+
+ def validate(self, val: dict) -> bool:
+ return True
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/base_types/media.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/base_types/media.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd827d38afd68327bca529e1ce15488b54432df9
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/base_types/media.py
@@ -0,0 +1,339 @@
+import hashlib
+import os
+import pathlib
+import re
+import shutil
+from typing import TYPE_CHECKING, Any, Dict, Optional, Sequence, Type, Union, cast
+
+import wandb
+from wandb import util
+from wandb.sdk.lib import filesystem
+from wandb.sdk.lib.paths import LogicalPath
+
+from .wb_value import WBValue
+
+if TYPE_CHECKING: # pragma: no cover
+ import numpy as np
+
+ from wandb.sdk.artifacts.artifact import Artifact
+
+
+def _wb_filename(
+ key: Union[str, int], step: Union[str, int], id: Union[str, int], extension: str
+) -> str:
+ r"""Generates a safe filename/path for storing media files, using the provided key, step, and id.
+
+ If the key contains slashes (e.g. 'images/cats/fluffy.jpg'), subdirectories will be created:
+ media/
+ images/
+ cats/
+ fluffy.jpg_step_id.ext
+
+ Args:
+ key: Name/path for the media file
+ step: Training step number
+ id: Unique identifier
+ extension: File extension (e.g. '.jpg', '.mp3')
+
+ Returns:
+ A sanitized filename string in the format: key_step_id.extension
+
+ Raises:
+ ValueError: If running on Windows and the key contains invalid filename characters
+ (\\, :, *, ?, ", <, >, |)
+ """
+ key = util.make_file_path_upload_safe(str(key))
+
+ return f"{str(key)}_{str(step)}_{str(id)}{extension}"
+
+
+class Media(WBValue):
+ """A WBValue stored as a file outside JSON that can be rendered in a media panel.
+
+ If necessary, we move or copy the file into the Run's media directory so that it
+ gets uploaded.
+ """
+
+ _path: Optional[str]
+ _run: Optional["wandb.Run"]
+ _caption: Optional[str]
+ _is_tmp: Optional[bool]
+ _extension: Optional[str]
+ _sha256: Optional[str]
+ _size: Optional[int]
+
+ def __init__(self, caption: Optional[str] = None) -> None:
+ super().__init__()
+ self._path = None
+ # The run under which this object is bound, if any.
+ self._run = None
+ self._caption = caption
+
+ def _set_file(
+ self,
+ path: str,
+ is_tmp: bool = False,
+ extension: Optional[str] = None,
+ ) -> None:
+ self._path = path
+ self._is_tmp = is_tmp
+ self._extension = extension
+ assert extension is None or path.endswith(extension), (
+ f'Media file extension "{extension}" must occur at the end of path "{path}".'
+ )
+
+ with open(self._path, "rb") as f:
+ self._sha256 = hashlib.sha256(f.read()).hexdigest()
+ self._size = os.path.getsize(self._path)
+
+ @classmethod
+ def get_media_subdir(cls: Type["Media"]) -> str:
+ raise NotImplementedError
+
+ @staticmethod
+ def captions(
+ media_items: Sequence["Media"],
+ ) -> Union[bool, Sequence[Optional[str]]]:
+ if media_items[0]._caption is not None:
+ return [m._caption for m in media_items]
+ else:
+ return False
+
+ def is_bound(self) -> bool:
+ return self._run is not None
+
+ def file_is_set(self) -> bool:
+ return self._path is not None and self._sha256 is not None
+
+ def bind_to_run(
+ self,
+ run: "wandb.Run",
+ key: Union[int, str],
+ step: Union[int, str],
+ id_: Optional[Union[int, str]] = None,
+ ignore_copy_err: Optional[bool] = None,
+ ) -> None:
+ """Bind this object to a particular Run.
+
+ Calling this function is necessary so that we have somewhere specific to put the
+ file associated with this object, from which other Runs can refer to it.
+ """
+ assert self.file_is_set(), "bind_to_run called before _set_file"
+
+ # The following two assertions are guaranteed to pass
+ # by definition file_is_set, but are needed for
+ # mypy to understand that these are strings below.
+ assert isinstance(self._path, str)
+ assert isinstance(self._sha256, str)
+
+ assert run is not None, 'Argument "run" must not be None.'
+ self._run = run
+
+ if self._extension is None:
+ _, extension = os.path.splitext(os.path.basename(self._path))
+ else:
+ extension = self._extension
+
+ if id_ is None:
+ id_ = self._sha256[:20]
+
+ file_path = _wb_filename(key, step, id_, extension)
+ media_path = os.path.join(self.get_media_subdir(), file_path)
+ new_path = os.path.join(self._run.dir, media_path)
+ filesystem.mkdir_exists_ok(os.path.dirname(new_path))
+
+ if self._is_tmp:
+ shutil.move(self._path, new_path)
+ self._path = new_path
+ self._is_tmp = False
+ run._publish_file(media_path)
+ else:
+ try:
+ shutil.copy(self._path, new_path)
+ except shutil.SameFileError:
+ if not ignore_copy_err:
+ raise
+ self._path = new_path
+ run._publish_file(media_path)
+
+ def to_json(self, run: Union["wandb.Run", "Artifact"]) -> dict:
+ """Serialize the object into a JSON blob.
+
+ Uses run or artifact to store additional data. If `run_or_artifact` is a
+ wandb.Run then `self.bind_to_run()` must have been previously been called.
+
+ Args:
+ run_or_artifact (wandb.Run | wandb.Artifact): the Run or Artifact for which
+ this object should be generating JSON for - this is useful to store
+ additional data if needed.
+
+ Returns:
+ dict: JSON representation
+ """
+ # NOTE: uses of Audio in this class are a temporary hack -- when Ref support moves up
+ # into Media itself we should get rid of them
+ from wandb import Image
+ from wandb.data_types import Audio
+
+ json_obj: Dict[str, Any] = {}
+
+ if self._caption is not None:
+ json_obj["caption"] = self._caption
+
+ if isinstance(run, wandb.Run):
+ json_obj.update(
+ {
+ "_type": "file", # TODO(adrian): This isn't (yet) a real media type we support on the frontend.
+ "sha256": self._sha256,
+ "size": self._size,
+ }
+ )
+
+ artifact_entry_url = self._get_artifact_entry_ref_url()
+ if artifact_entry_url is not None:
+ json_obj["artifact_path"] = artifact_entry_url
+ artifact_entry_latest_url = self._get_artifact_entry_latest_ref_url()
+ if artifact_entry_latest_url is not None:
+ json_obj["_latest_artifact_path"] = artifact_entry_latest_url
+
+ if artifact_entry_url is None or self.is_bound():
+ assert self.is_bound(), (
+ f"Value of type {type(self).__name__} must be bound to a run with bind_to_run() before being serialized to JSON."
+ )
+
+ assert self._run is run, (
+ "We don't support referring to media files across runs."
+ )
+
+ # The following two assertions are guaranteed to pass
+ # by definition is_bound, but are needed for
+ # mypy to understand that these are strings below.
+ assert isinstance(self._path, str)
+ json_obj["path"] = LogicalPath(
+ os.path.relpath(self._path, self._run.dir)
+ )
+
+ elif isinstance(run, wandb.Artifact):
+ if self.file_is_set():
+ # The following two assertions are guaranteed to pass
+ # by definition of the call above, but are needed for
+ # mypy to understand that these are strings below.
+ assert isinstance(self._path, str)
+ assert isinstance(self._sha256, str)
+ artifact = run # Checks if the concrete image has already been added to this artifact
+ name = artifact.get_added_local_path_name(self._path)
+ if name is None:
+ if self._is_tmp:
+ name = os.path.join(
+ self.get_media_subdir(), os.path.basename(self._path)
+ )
+ else:
+ # If the files is not temporary, include the first 8 characters of the file's SHA256 to
+ # avoid name collisions. This way, if there are two images `dir1/img.png` and `dir2/img.png`
+ # we end up with a unique path for each.
+ name = os.path.join(
+ self.get_media_subdir(),
+ self._sha256[:20],
+ os.path.basename(self._path),
+ )
+
+ # if not, check to see if there is a source artifact for this object
+ if (
+ self._artifact_source is not None
+ # and self._artifact_source.artifact != artifact
+ ):
+ default_root = self._artifact_source.artifact._default_root()
+ # if there is, get the name of the entry (this might make sense to move to a helper off artifact)
+ if self._path.startswith(default_root):
+ name = self._path[len(default_root) :]
+ name = name.lstrip(os.sep)
+
+ # Add this image as a reference
+ path = self._artifact_source.artifact.get_entry(name)
+ artifact.add_reference(path.ref_url(), name=name)
+ elif (
+ isinstance(self, Audio) or isinstance(self, Image)
+ ) and self.path_is_reference(self._path):
+ artifact.add_reference(self._path, name=name)
+ else:
+ entry = artifact.add_file(
+ self._path, name=name, is_tmp=self._is_tmp
+ )
+ name = entry.path
+
+ json_obj["path"] = name
+ json_obj["sha256"] = self._sha256
+ json_obj["_type"] = self._log_type
+ return json_obj
+
+ @classmethod
+ def from_json(
+ cls: Type["Media"], json_obj: dict, source_artifact: "Artifact"
+ ) -> "Media":
+ """Likely will need to override for any more complicated media objects."""
+ return cls(source_artifact.get_entry(json_obj["path"]).download())
+
+ def __eq__(self, other: object) -> bool:
+ """Likely will need to override for any more complicated media objects."""
+ return (
+ isinstance(other, self.__class__)
+ and hasattr(self, "_sha256")
+ and hasattr(other, "_sha256")
+ and self._sha256 == other._sha256
+ )
+
+ @staticmethod
+ def path_is_reference(path: Optional[Union[str, pathlib.Path]]) -> bool:
+ if path is None or isinstance(path, pathlib.Path):
+ return False
+
+ return bool(path and re.match(r"^(gs|s3|https?)://", path))
+
+
+class BatchableMedia(Media):
+ """Media that is treated in batches.
+
+ E.g. images and thumbnails. Apart from images, we just use these batches to help
+ organize files by name in the media directory.
+ """
+
+ def __init__(
+ self,
+ caption: Optional[str] = None,
+ ) -> None:
+ super().__init__(caption=caption)
+
+ @classmethod
+ def seq_to_json(
+ cls: Type["BatchableMedia"],
+ seq: Sequence["BatchableMedia"],
+ run: "wandb.Run",
+ key: str,
+ step: Union[int, str],
+ ) -> dict:
+ raise NotImplementedError
+
+
+def _numpy_arrays_to_lists(
+ payload: Union[dict, Sequence, "np.ndarray"],
+) -> Union[Sequence, dict, str, int, float, bool]:
+ # Casts all numpy arrays to lists so we don't convert them to histograms, primarily for Plotly
+
+ if isinstance(payload, dict):
+ res = {}
+ for key, val in payload.items():
+ res[key] = _numpy_arrays_to_lists(val)
+ return res
+ elif isinstance(payload, Sequence) and not isinstance(payload, str):
+ return [_numpy_arrays_to_lists(v) for v in payload]
+ elif util.is_numpy_array(payload):
+ if TYPE_CHECKING:
+ payload = cast("np.ndarray", payload)
+ return [
+ _numpy_arrays_to_lists(v)
+ for v in (payload.tolist() if payload.ndim > 0 else [payload.tolist()])
+ ]
+ # Protects against logging non serializable objects
+ elif isinstance(payload, Media):
+ return str(payload.__class__.__name__)
+ return payload # type: ignore
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/base_types/wb_value.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/base_types/wb_value.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a2c20f435f0319bab431b56cf35199ed065e2f5
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/base_types/wb_value.py
@@ -0,0 +1,295 @@
+from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Type, Union
+
+from wandb import util
+from wandb.sdk import wandb_setup
+
+if TYPE_CHECKING: # pragma: no cover
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ from ...wandb_run import Run as LocalRun
+
+ TypeMappingType = Dict[str, Type["WBValue"]]
+
+
+def _is_maybe_offline() -> bool:
+ """Guess whether wandb is configured to be offline.
+
+ This is an anti-pattern because there is no library-level "offline" mode:
+ only runs can be offline. Online and offline runs can exist in the same
+ process. This function is a heuristic that works only if there is at most
+ one run in the process, and could otherwise produce unexpected results.
+
+ Returns:
+ Whether the user likely configured wandb to be offline.
+ """
+ singleton = wandb_setup.singleton()
+
+ # First check: if there's a run, check if it is offline.
+ #
+ # This covers uses like `wandb.init(mode="offline")` which don't modify
+ # the singleton's settings.
+ if run := singleton.most_recent_active_run:
+ return run.offline
+
+ # Second check: default to global defaults derived from environment
+ # variables or passed explicitly to `wandb.setup()`.
+ return singleton.settings._offline
+
+
+def _server_accepts_client_ids() -> bool:
+ from packaging.version import parse
+
+ # There are versions of W&B Server that cannot accept client IDs. Those versions of
+ # the backend have a max_cli_version of less than "0.11.0." If the backend cannot
+ # accept client IDs, manifests and artifact data would never be resolvable and lead
+ # to failed uploads. Our position in 2021/06/29 was to never lose data - and instead take the
+ # tradeoff in the UI. The results in tables not displaying media correctly, but
+ # the table can still be accessed via the .artifact op.
+ #
+ # The latest SDK version that is < "0.11.0" was released on 2021/06/29.
+ # AS OF NOW, 2024/11/06, we assume that all customer's server deployments accept
+ # client IDs.
+
+ if _is_maybe_offline():
+ singleton = wandb_setup.singleton()
+
+ if run := singleton.most_recent_active_run:
+ return run._settings.allow_offline_artifacts
+ else:
+ return singleton.settings.allow_offline_artifacts
+
+ # If the script is online, request the max_cli_version and ensure the server
+ # is of a high enough version.
+ max_cli_version = util._get_max_cli_version()
+ if max_cli_version is None:
+ return False
+ accepts_client_ids: bool = parse(max_cli_version) >= parse("0.11.0")
+ return accepts_client_ids
+
+
+class _WBValueArtifactSource:
+ artifact: "Artifact"
+ name: Optional[str]
+
+ def __init__(self, artifact: "Artifact", name: Optional[str] = None) -> None:
+ self.artifact = artifact
+ self.name = name
+
+
+class _WBValueArtifactTarget:
+ artifact: "Artifact"
+ name: Optional[str]
+
+ def __init__(self, artifact: "Artifact", name: Optional[str] = None) -> None:
+ self.artifact = artifact
+ self.name = name
+
+
+class WBValue:
+ """Typed objects that can be logged with `wandb.log()` and visualized by wandb.
+
+ The objects will be serialized as JSON and always have a _type attribute that
+ indicates how to interpret the other fields.
+ """
+
+ # Class Attributes
+ _type_mapping: ClassVar[Optional["TypeMappingType"]] = None
+ # override _log_type to indicate the type which the subclass deserializes
+ _log_type: ClassVar[Optional[str]] = None
+
+ # Instance Attributes
+ _artifact_source: Optional[_WBValueArtifactSource]
+ _artifact_target: Optional[_WBValueArtifactTarget]
+
+ def __init__(self) -> None:
+ self._artifact_source = None
+ self._artifact_target = None
+
+ def to_json(self, run_or_artifact: Union["LocalRun", "Artifact"]) -> dict:
+ """Serialize the object into a JSON blob.
+
+ Uses current run or artifact to store additional data.
+
+ Args:
+ run_or_artifact (wandb.Run | wandb.Artifact): the Run or Artifact for which
+ this object should be generating JSON for - this is useful to to store
+ additional data if needed.
+
+ Returns:
+ dict: JSON representation
+ """
+ raise NotImplementedError
+
+ @classmethod
+ def from_json(cls, json_obj: dict, source_artifact: "Artifact") -> "WBValue":
+ """Deserialize a `json_obj` into it's class representation.
+
+ If additional resources were stored in the `run_or_artifact` artifact during the
+ `to_json` call, then those resources should be in the `source_artifact`.
+
+ Args:
+ json_obj (dict): A JSON dictionary to deserialize source_artifact
+ (wandb.Artifact): An artifact which will hold any additional
+ resources which were stored during the `to_json` function.
+ """
+ raise NotImplementedError
+
+ @classmethod
+ def with_suffix(cls: Type["WBValue"], name: str, filetype: str = "json") -> str:
+ """Get the name with the appropriate suffix.
+
+ Args:
+ name (str): the name of the file
+ filetype (str, optional): the filetype to use. Defaults to "json".
+
+ Returns:
+ str: a filename which is suffixed with it's `_log_type` followed by the
+ filetype.
+ """
+ if cls._log_type is not None:
+ suffix = cls._log_type + "." + filetype
+ else:
+ suffix = filetype
+ if not name.endswith(suffix):
+ return name + "." + suffix
+ return name
+
+ @staticmethod
+ def init_from_json(
+ json_obj: dict, source_artifact: "Artifact"
+ ) -> Optional["WBValue"]:
+ """Initialize a `WBValue` from a JSON blob based on the class that created it.
+
+ Looks through all subclasses and tries to match the json obj with the class
+ which created it. It will then call that subclass' `from_json` method.
+ Importantly, this function will set the return object's `source_artifact`
+ attribute to the passed in source artifact. This is critical for artifact
+ bookkeeping. If you choose to create a wandb.Value via it's `from_json` method,
+ make sure to properly set this `artifact_source` to avoid data duplication.
+
+ Args:
+ json_obj (dict): A JSON dictionary to deserialize. It must contain a `_type`
+ key. This is used to lookup the correct subclass to use.
+ source_artifact (wandb.Artifact): An artifact which will hold any additional
+ resources which were stored during the `to_json` function.
+
+ Returns:
+ wandb.Value: a newly created instance of a subclass of wandb.Value
+ """
+ class_option = WBValue.type_mapping().get(json_obj["_type"])
+ if class_option is not None:
+ obj = class_option.from_json(json_obj, source_artifact)
+ obj._set_artifact_source(source_artifact)
+ return obj
+
+ return None
+
+ @staticmethod
+ def type_mapping() -> "TypeMappingType":
+ """Return a map from `_log_type` to subclass. Used to lookup correct types for deserialization.
+
+ Returns:
+ dict: dictionary of str:class
+ """
+ if WBValue._type_mapping is None:
+ WBValue._type_mapping = {}
+ frontier = [WBValue]
+ explored = set()
+ while len(frontier) > 0:
+ class_option = frontier.pop()
+ explored.add(class_option)
+ if class_option._log_type is not None:
+ WBValue._type_mapping[class_option._log_type] = class_option
+ for subclass in class_option.__subclasses__():
+ if subclass not in explored:
+ frontier.append(subclass)
+ return WBValue._type_mapping
+
+ def __eq__(self, other: object) -> bool:
+ return id(self) == id(other)
+
+ def __ne__(self, other: object) -> bool:
+ return not self.__eq__(other)
+
+ def to_data_array(self) -> List[Any]:
+ """Convert the object to a list of primitives representing the underlying data."""
+ raise NotImplementedError
+
+ def _set_artifact_source(
+ self, artifact: "Artifact", name: Optional[str] = None
+ ) -> None:
+ assert self._artifact_source is None, (
+ f"Cannot update artifact_source. Existing source: {self._artifact_source.artifact}/{self._artifact_source.name}"
+ )
+ self._artifact_source = _WBValueArtifactSource(artifact, name)
+
+ def _set_artifact_target(
+ self, artifact: "Artifact", name: Optional[str] = None
+ ) -> None:
+ assert self._artifact_target is None, (
+ f"Cannot update artifact_target. Existing target: {self._artifact_target.artifact}/{self._artifact_target.name}"
+ )
+ self._artifact_target = _WBValueArtifactTarget(artifact, name)
+
+ def _get_artifact_entry_ref_url(self) -> Optional[str]:
+ # If the object is coming from another artifact
+ if self._artifact_source and self._artifact_source.name:
+ ref_entry = self._artifact_source.artifact.get_entry(
+ type(self).with_suffix(self._artifact_source.name)
+ )
+ return str(ref_entry.ref_url())
+ # Else, if the object is destined for another artifact and we support client IDs
+ elif (
+ self._artifact_target
+ and self._artifact_target.name
+ and self._artifact_target.artifact._client_id is not None
+ and self._artifact_target.artifact._final
+ and _server_accepts_client_ids()
+ ):
+ return f"wandb-client-artifact://{self._artifact_target.artifact._client_id}/{type(self).with_suffix(self._artifact_target.name)}"
+ # Else if we do not support client IDs, but online, then block on upload
+ # Note: this is old behavior just to stay backwards compatible
+ # with older server versions. This code path should be removed
+ # once those versions are no longer supported. This path uses a .wait
+ # which blocks the user process on artifact upload.
+ elif (
+ self._artifact_target
+ and self._artifact_target.name
+ and self._artifact_target.artifact._is_draft_save_started()
+ and not _is_maybe_offline()
+ and not _server_accepts_client_ids()
+ ):
+ self._artifact_target.artifact.wait()
+ ref_entry = self._artifact_target.artifact.get_entry(
+ type(self).with_suffix(self._artifact_target.name)
+ )
+ return str(ref_entry.ref_url())
+ return None
+
+ def _get_artifact_entry_latest_ref_url(self) -> Optional[str]:
+ if (
+ self._artifact_target
+ and self._artifact_target.name
+ and self._artifact_target.artifact._client_id is not None
+ and self._artifact_target.artifact._final
+ and _server_accepts_client_ids()
+ ):
+ return f"wandb-client-artifact://{self._artifact_target.artifact._sequence_client_id}:latest/{type(self).with_suffix(self._artifact_target.name)}"
+ # Else if we do not support client IDs, then block on upload
+ # Note: this is old behavior just to stay backwards compatible
+ # with older server versions. This code path should be removed
+ # once those versions are no longer supported. This path uses a .wait
+ # which blocks the user process on artifact upload.
+ elif (
+ self._artifact_target
+ and self._artifact_target.name
+ and self._artifact_target.artifact._is_draft_save_started()
+ and not _is_maybe_offline()
+ and not _server_accepts_client_ids()
+ ):
+ self._artifact_target.artifact.wait()
+ ref_entry = self._artifact_target.artifact.get_entry(
+ type(self).with_suffix(self._artifact_target.name)
+ )
+ return str(ref_entry.ref_url())
+ return None
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/bokeh.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/bokeh.py
new file mode 100644
index 0000000000000000000000000000000000000000..96b7650fc6e0f5281f4fe11a8fcc5f0b80a311e3
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/bokeh.py
@@ -0,0 +1,91 @@
+import codecs
+import json
+import os
+import pathlib
+from typing import TYPE_CHECKING, Union
+
+from wandb import util
+from wandb._strutils import nameof
+from wandb.sdk.lib import runid
+
+from . import _dtypes
+from ._private import MEDIA_TMP
+from .base_types.media import Media
+
+if TYPE_CHECKING:
+ from bokeh import document, model
+
+
+class Bokeh(Media):
+ """Wandb class for Bokeh plots.
+
+ Args:
+ val: Bokeh plot
+ """
+
+ _log_type = "bokeh-file"
+
+ def __init__(
+ self,
+ data_or_path: Union[
+ str,
+ pathlib.Path,
+ "document.Document",
+ "model.Model",
+ ],
+ ):
+ super().__init__()
+ bokeh = util.get_module(
+ "bokeh",
+ required=f"{nameof(Bokeh)!r} requires the bokeh package. Please install it with `pip install bokeh`.",
+ )
+ if isinstance(data_or_path, (str, pathlib.Path)) and os.path.exists(
+ data_or_path
+ ):
+ data_or_path = str(data_or_path)
+
+ with open(data_or_path) as file:
+ b_json = json.load(file)
+ self.b_obj = bokeh.document.Document.from_json(b_json)
+ self._set_file(data_or_path, is_tmp=False, extension=".bokeh.json")
+ elif isinstance(data_or_path, bokeh.model.Model):
+ _data = bokeh.document.Document()
+ _data.add_root(data_or_path)
+ # serialize/deserialize pairing followed by sorting attributes ensures
+ # that the file's sha's are equivalent in subsequent calls
+ self.b_obj = bokeh.document.Document.from_json(_data.to_json())
+ b_json = self.b_obj.to_json()
+ if "references" in b_json["roots"]:
+ b_json["roots"]["references"].sort(key=lambda x: x["id"])
+
+ tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ".bokeh.json")
+ with codecs.open(tmp_path, "w", encoding="utf-8") as fp:
+ util.json_dump_safer(b_json, fp)
+ self._set_file(tmp_path, is_tmp=True, extension=".bokeh.json")
+ elif not isinstance(data_or_path, bokeh.document.Document):
+ raise TypeError(
+ "Bokeh constructor accepts Bokeh document/model or path to Bokeh json file"
+ )
+
+ def get_media_subdir(self):
+ return os.path.join("media", "bokeh")
+
+ def to_json(self, run):
+ # TODO: (tss) this is getting redundant for all the media objects. We can probably
+ # pull this into Media#to_json and remove this type override for all the media types.
+ # There are only a few cases where the type is different between artifacts and runs.
+ json_dict = super().to_json(run)
+ json_dict["_type"] = self._log_type
+ return json_dict
+
+ @classmethod
+ def from_json(cls, json_obj, source_artifact):
+ return cls(source_artifact.get_entry(json_obj["path"]).download())
+
+
+class _BokehFileType(_dtypes.Type):
+ name = "bokeh-file"
+ types = [Bokeh]
+
+
+_dtypes.TypeRegistry.add(_BokehFileType)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/graph.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/graph.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc59f31f51b48406cc4dd80ad8f2f5c71f438fbb
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/graph.py
@@ -0,0 +1,439 @@
+import codecs
+import os
+import pprint
+
+from wandb import util
+from wandb.sdk.data_types._private import MEDIA_TMP
+from wandb.sdk.data_types.base_types.media import Media, _numpy_arrays_to_lists
+from wandb.sdk.data_types.base_types.wb_value import WBValue
+from wandb.sdk.lib import runid
+
+
+def _nest(thing):
+ # Use tensorflows nest function if available, otherwise just wrap object in an array"""
+
+ tfutil = util.get_module("tensorflow.python.util")
+ if tfutil:
+ return tfutil.nest.flatten(thing)
+ else:
+ return [thing]
+
+
+class Edge(WBValue):
+ """Edge used in `Graph`."""
+
+ def __init__(self, from_node, to_node):
+ self._attributes = {}
+ self.from_node = from_node
+ self.to_node = to_node
+
+ def __repr__(self):
+ temp_attr = dict(self._attributes)
+ del temp_attr["from_node"]
+ del temp_attr["to_node"]
+ temp_attr["from_id"] = self.from_node.id
+ temp_attr["to_id"] = self.to_node.id
+ return str(temp_attr)
+
+ def to_json(self, run=None):
+ return [self.from_node.id, self.to_node.id]
+
+ @property
+ def name(self):
+ """Optional, not necessarily unique."""
+ return self._attributes.get("name")
+
+ @name.setter
+ def name(self, val):
+ self._attributes["name"] = val
+ return val
+
+ @property
+ def from_node(self):
+ return self._attributes.get("from_node")
+
+ @from_node.setter
+ def from_node(self, val):
+ self._attributes["from_node"] = val
+ return val
+
+ @property
+ def to_node(self):
+ return self._attributes.get("to_node")
+
+ @to_node.setter
+ def to_node(self, val):
+ self._attributes["to_node"] = val
+ return val
+
+
+class Node(WBValue):
+ """Node used in `Graph`."""
+
+ def __init__(
+ self,
+ id=None,
+ name=None,
+ class_name=None,
+ size=None,
+ parameters=None,
+ output_shape=None,
+ is_output=None,
+ num_parameters=None,
+ node=None,
+ ):
+ self._attributes = {"name": None}
+ self.in_edges = {} # indexed by source node id
+ self.out_edges = {} # indexed by dest node id
+ # optional object (e.g. PyTorch Parameter or Module) that this Node represents
+ self.obj = None
+
+ if node is not None:
+ self._attributes.update(node._attributes)
+ del self._attributes["id"]
+ self.obj = node.obj
+
+ if id is not None:
+ self.id = id
+ if name is not None:
+ self.name = name
+ if class_name is not None:
+ self.class_name = class_name
+ if size is not None:
+ self.size = size
+ if parameters is not None:
+ self.parameters = parameters
+ if output_shape is not None:
+ self.output_shape = output_shape
+ if is_output is not None:
+ self.is_output = is_output
+ if num_parameters is not None:
+ self.num_parameters = num_parameters
+
+ def to_json(self, run=None):
+ return self._attributes
+
+ def __repr__(self):
+ return repr(self._attributes)
+
+ @property
+ def id(self):
+ """Must be unique in the graph."""
+ return self._attributes.get("id")
+
+ @id.setter
+ def id(self, val):
+ self._attributes["id"] = val
+ return val
+
+ @property
+ def name(self):
+ """Usually the type of layer or sublayer."""
+ return self._attributes.get("name")
+
+ @name.setter
+ def name(self, val):
+ self._attributes["name"] = val
+ return val
+
+ @property
+ def class_name(self):
+ """Usually the type of layer or sublayer."""
+ return self._attributes.get("class_name")
+
+ @class_name.setter
+ def class_name(self, val):
+ self._attributes["class_name"] = val
+ return val
+
+ @property
+ def functions(self):
+ return self._attributes.get("functions", [])
+
+ @functions.setter
+ def functions(self, val):
+ self._attributes["functions"] = val
+ return val
+
+ @property
+ def parameters(self):
+ return self._attributes.get("parameters", [])
+
+ @parameters.setter
+ def parameters(self, val):
+ self._attributes["parameters"] = val
+ return val
+
+ @property
+ def size(self):
+ return self._attributes.get("size")
+
+ @size.setter
+ def size(self, val):
+ """Tensor size."""
+ self._attributes["size"] = tuple(val)
+ return val
+
+ @property
+ def output_shape(self):
+ return self._attributes.get("output_shape")
+
+ @output_shape.setter
+ def output_shape(self, val):
+ """Tensor output_shape."""
+ self._attributes["output_shape"] = val
+ return val
+
+ @property
+ def is_output(self):
+ return self._attributes.get("is_output")
+
+ @is_output.setter
+ def is_output(self, val):
+ """Tensor is_output."""
+ self._attributes["is_output"] = val
+ return val
+
+ @property
+ def num_parameters(self):
+ return self._attributes.get("num_parameters")
+
+ @num_parameters.setter
+ def num_parameters(self, val):
+ """Tensor num_parameters."""
+ self._attributes["num_parameters"] = val
+ return val
+
+ @property
+ def child_parameters(self):
+ return self._attributes.get("child_parameters")
+
+ @child_parameters.setter
+ def child_parameters(self, val):
+ """Tensor child_parameters."""
+ self._attributes["child_parameters"] = val
+ return val
+
+ @property
+ def is_constant(self):
+ return self._attributes.get("is_constant")
+
+ @is_constant.setter
+ def is_constant(self, val):
+ """Tensor is_constant."""
+ self._attributes["is_constant"] = val
+ return val
+
+ @classmethod
+ def from_keras(cls, layer):
+ node = cls()
+
+ try:
+ output_shape = layer.output_shape
+ except AttributeError:
+ output_shape = ["multiple"]
+
+ node.id = layer.name
+ node.name = layer.name
+ node.class_name = layer.__class__.__name__
+ node.output_shape = output_shape
+ node.num_parameters = layer.count_params()
+
+ return node
+
+
+class Graph(Media):
+ """W&B class for graphs.
+
+ This class is typically used for saving and displaying neural net models.
+ It represents the graph as an array of nodes and edges. The nodes can have
+ labels that can be visualized by wandb.
+
+ Attributes:
+ format (string): Format to help wandb display the graph nicely.
+ nodes ([wandb.Node]): List of `wandb.Nodes`.
+ nodes_by_id (dict): dict of ids -> nodes
+ edges ([(wandb.Node, wandb.Node)]): List of pairs of nodes interpreted
+ as edges.
+ loaded (boolean): Flag to tell whether the graph is completely loaded.
+ root (wandb.Node): Root node of the graph.
+
+ Examples:
+ Import a keras model.
+
+ ```python
+ import wandb
+
+ wandb.Graph.from_keras(keras_model)
+ ```
+ """
+
+ _log_type = "graph-file"
+
+ def __init__(self, format="keras"):
+ super().__init__()
+ # LB: TODO: I think we should factor criterion and criterion_passed out
+ self.format = format
+ self.nodes = []
+ self.nodes_by_id = {}
+ self.edges = []
+ self.loaded = False
+ self.criterion = None
+ self.criterion_passed = False
+ self.root = None # optional root Node if applicable
+
+ def _to_graph_json(self, run=None):
+ # Needs to be its own function for tests
+ return {
+ "format": self.format,
+ "nodes": [node.to_json() for node in self.nodes],
+ "edges": [edge.to_json() for edge in self.edges],
+ }
+
+ def bind_to_run(self, *args, **kwargs):
+ """Bind this object to a run.
+
+
+ """
+ data = self._to_graph_json()
+ tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ".graph.json")
+ data = _numpy_arrays_to_lists(data)
+ with codecs.open(tmp_path, "w", encoding="utf-8") as fp:
+ util.json_dump_safer(data, fp)
+ self._set_file(tmp_path, is_tmp=True, extension=".graph.json")
+ if self.is_bound():
+ return
+ super().bind_to_run(*args, **kwargs)
+
+ @classmethod
+ def get_media_subdir(cls):
+ """Get media subdirectory.
+
+ "
+ """
+ return os.path.join("media", "graph")
+
+ def to_json(self, run):
+ """Returns the JSON representation expected by the backend.
+
+
+ """
+ json_dict = super().to_json(run)
+ json_dict["_type"] = self._log_type
+ return json_dict
+
+ def __getitem__(self, nid):
+ return self.nodes_by_id[nid]
+
+ def pprint(self):
+ """Pretty print the graph.
+
+
+ """
+ for edge in self.edges:
+ pprint.pprint(edge.attributes) # noqa: T203
+ for node in self.nodes:
+ pprint.pprint(node.attributes) # noqa: T203
+
+ def add_node(self, node=None, **node_kwargs):
+ """Add a node to the graph.
+
+
+ """
+ if node is None:
+ node = Node(**node_kwargs)
+ elif node_kwargs:
+ raise ValueError(
+ f"Only pass one of either node ({node}) or other keyword arguments ({node_kwargs})"
+ )
+ self.nodes.append(node)
+ self.nodes_by_id[node.id] = node
+
+ return node
+
+ def add_edge(self, from_node, to_node):
+ """Add an edge to the graph.
+
+
+ """
+ edge = Edge(from_node, to_node)
+ self.edges.append(edge)
+
+ return edge
+
+ @classmethod
+ def from_keras(cls, model):
+ """Create a graph from a Keras model.
+
+ This method is not supported for Keras 3.0.0 and above.
+ Requires a refactor.
+
+ "
+ """
+ graph = cls()
+ # Shamelessly copied (then modified) from keras/keras/utils/layer_utils.py
+ sequential_like = cls._is_sequential(model)
+
+ relevant_nodes = None
+ if not sequential_like:
+ relevant_nodes = []
+ for v in model._nodes_by_depth.values():
+ relevant_nodes += v
+
+ layers = model.layers
+ for i in range(len(layers)):
+ node = Node.from_keras(layers[i])
+ if hasattr(layers[i], "_inbound_nodes"):
+ for in_node in layers[i]._inbound_nodes:
+ if relevant_nodes and in_node not in relevant_nodes:
+ # node is not part of the current network
+ continue
+ for in_layer in _nest(in_node.inbound_layers):
+ inbound_keras_node = Node.from_keras(in_layer)
+
+ if inbound_keras_node.id not in graph.nodes_by_id:
+ graph.add_node(inbound_keras_node)
+ inbound_node = graph.nodes_by_id[inbound_keras_node.id]
+
+ graph.add_edge(inbound_node, node)
+ graph.add_node(node)
+ return graph
+
+ @classmethod
+ def _is_sequential(cls, model):
+ sequential_like = True
+
+ if (
+ model.__class__.__name__ != "Sequential"
+ and hasattr(model, "_is_graph_network")
+ and model._is_graph_network
+ ):
+ nodes_by_depth = model._nodes_by_depth.values()
+ nodes = []
+ for v in nodes_by_depth:
+ # TensorFlow2 doesn't insure inbound is always a list
+ inbound = v[0].inbound_layers
+ if not hasattr(inbound, "__len__"):
+ inbound = [inbound]
+ if (len(v) > 1) or (len(v) == 1 and len(inbound) > 1):
+ # if the model has multiple nodes
+ # or if the nodes have multiple inbound_layers
+ # the model is no longer sequential
+ sequential_like = False
+ break
+ nodes += v
+ if sequential_like:
+ # search for shared layers
+ for layer in model.layers:
+ flag = False
+ if hasattr(layer, "_inbound_nodes"):
+ for node in layer._inbound_nodes:
+ if node in nodes:
+ if flag:
+ sequential_like = False
+ break
+ else:
+ flag = True
+ if not sequential_like:
+ break
+ return sequential_like
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/helper_types/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/helper_types/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/helper_types/bounding_boxes_2d.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/helper_types/bounding_boxes_2d.py
new file mode 100644
index 0000000000000000000000000000000000000000..663eee14800a44d7aab30e459f2cdad991409bbb
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/helper_types/bounding_boxes_2d.py
@@ -0,0 +1,327 @@
+import numbers
+from typing import TYPE_CHECKING, Optional, Type, Union
+
+import wandb
+from wandb import util
+from wandb.util import has_num
+
+from ..base_types.json_metadata import JSONMetadata
+
+if TYPE_CHECKING: # pragma: no cover
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ from ...wandb_run import Run as LocalRun
+
+
+def _convert_pytorch_tensor_to_list(box_data):
+ for box in box_data:
+ if (
+ "position" in box
+ and "middle" in box["position"]
+ and util.is_pytorch_tensor_typename(
+ util.get_full_typename(box["position"]["middle"])
+ )
+ ):
+ box["position"]["middle"] = box["position"]["middle"].tolist()
+
+
+class BoundingBoxes2D(JSONMetadata):
+ """Format images with 2D bounding box overlays for logging to W&B.
+
+ Args:
+ val: (dictionary) A dictionary of the following form:
+ box_data: (list of dictionaries) One dictionary for each bounding box, containing:
+ position: (dictionary) the position and size of the bounding box, in one of two formats
+ Note that boxes need not all use the same format.
+ {"minX", "minY", "maxX", "maxY"}: (dictionary) A set of coordinates defining
+ the upper and lower bounds of the box (the bottom left and top right corners)
+ {"middle", "width", "height"}: (dictionary) A set of coordinates defining the
+ center and dimensions of the box, with "middle" as a list [x, y] for the
+ center point and "width" and "height" as numbers
+ domain: (string) One of two options for the bounding box coordinate domain
+ null: By default, or if no argument is passed, the coordinate domain
+ is assumed to be relative to the original image, expressing this box as a fraction
+ or percentage of the original image. This means all coordinates and dimensions
+ passed into the "position" argument are floating point numbers between 0 and 1.
+ "pixel": (string literal) The coordinate domain is set to the pixel space. This means all
+ coordinates and dimensions passed into "position" are integers within the bounds
+ of the image dimensions.
+ class_id: (integer) The class label id for this box
+ scores: (dictionary of string to number, optional) A mapping of named fields
+ to numerical values (float or int), can be used for filtering boxes in the UI
+ based on a range of values for the corresponding field
+ box_caption: (string, optional) A string to be displayed as the label text above this
+ box in the UI, often composed of the class label, class name, and/or scores
+
+ class_labels: (dictionary, optional) A map of integer class labels to their readable class names
+
+ key: (string)
+ The readable name or id for this set of bounding boxes (e.g. predictions, ground_truth)
+
+ Examples:
+ ### Log bounding boxes for a single image
+
+ ```python
+ import numpy as np
+ import wandb
+
+ run = wandb.init()
+ image = np.random.randint(low=0, high=256, size=(200, 300, 3))
+
+ class_labels = {0: "person", 1: "car", 2: "road", 3: "building"}
+
+ img = wandb.Image(
+ image,
+ boxes={
+ "predictions": {
+ "box_data": [
+ {
+ # one box expressed in the default relative/fractional domain
+ "position": {
+ "minX": 0.1,
+ "maxX": 0.2,
+ "minY": 0.3,
+ "maxY": 0.4,
+ },
+ "class_id": 1,
+ "box_caption": class_labels[1],
+ "scores": {"acc": 0.2, "loss": 1.2},
+ },
+ {
+ # another box expressed in the pixel domain
+ "position": {
+ "middle": [150, 20],
+ "width": 68,
+ "height": 112,
+ },
+ "domain": "pixel",
+ "class_id": 3,
+ "box_caption": "a building",
+ "scores": {"acc": 0.5, "loss": 0.7},
+ },
+ # Log as many boxes an as needed
+ ],
+ "class_labels": class_labels,
+ }
+ },
+ )
+
+ run.log({"driving_scene": img})
+ ```
+
+ ### Log a bounding box overlay to a Table
+
+ ```python
+ import numpy as np
+ import wandb
+
+ run = wandb.init()
+ image = np.random.randint(low=0, high=256, size=(200, 300, 3))
+
+ class_labels = {0: "person", 1: "car", 2: "road", 3: "building"}
+
+ class_set = wandb.Classes(
+ [
+ {"name": "person", "id": 0},
+ {"name": "car", "id": 1},
+ {"name": "road", "id": 2},
+ {"name": "building", "id": 3},
+ ]
+ )
+
+ img = wandb.Image(
+ image,
+ boxes={
+ "predictions": {
+ "box_data": [
+ {
+ # one box expressed in the default relative/fractional domain
+ "position": {
+ "minX": 0.1,
+ "maxX": 0.2,
+ "minY": 0.3,
+ "maxY": 0.4,
+ },
+ "class_id": 1,
+ "box_caption": class_labels[1],
+ "scores": {"acc": 0.2, "loss": 1.2},
+ },
+ {
+ # another box expressed in the pixel domain
+ "position": {
+ "middle": [150, 20],
+ "width": 68,
+ "height": 112,
+ },
+ "domain": "pixel",
+ "class_id": 3,
+ "box_caption": "a building",
+ "scores": {"acc": 0.5, "loss": 0.7},
+ },
+ # Log as many boxes an as needed
+ ],
+ "class_labels": class_labels,
+ }
+ },
+ classes=class_set,
+ )
+
+ table = wandb.Table(columns=["image"])
+ table.add_data(img)
+ run.log({"driving_scene": table})
+ ```
+ """
+
+ _log_type = "bounding-boxes"
+ # TODO: when the change is made to have this produce a dict with a _type, define
+ # it here as _log_type, associate it in to_json
+
+ def __init__(self, val: dict, key: str) -> None:
+ """Initialize a BoundingBoxes object.
+
+ The input dictionary `val` should contain the keys:
+ box_data: a list of dictionaries, each of which describes a bounding box.
+ class_labels: (optional) A map of integer class labels to their readable
+ class names.
+
+ Each bounding box dictionary should contain the following keys:
+ position: (dictionary) the position and size of the bounding box.
+ domain: (string) One of two options for the bounding box coordinate domain.
+ class_id: (integer) The class label id for this box.
+ scores: (dictionary of string to number, optional) A mapping of named fields
+ to numerical values (float or int).
+ box_caption: (optional) The label text, often composed of the class label,
+ class name, and/or scores.
+
+ The position dictionary should be in one of two formats:
+ {"minX", "minY", "maxX", "maxY"}: (dictionary) A set of coordinates defining
+ the upper and lower bounds of the box (the bottom left and top right
+ corners).
+ {"middle", "width", "height"}: (dictionary) A set of coordinates defining
+ the center and dimensions of the box, with "middle" as a list [x, y] for
+ the center point and "width" and "height" as numbers.
+ Note that boxes need not all use the same format.
+
+ Args:
+ val: (dictionary) A dictionary containing the bounding box data.
+ key: (string) The readable name or id for this set of bounding boxes (e.g.
+ predictions, ground_truth)
+ """
+ # Pytorch tensors are not serializable to json,
+ # so we convert them to lists to avoid errors later on.
+ _convert_pytorch_tensor_to_list(val.get("box_data", []))
+ super().__init__(val)
+
+ self._val = val["box_data"]
+ self._key = key
+ # Add default class mapping
+ if "class_labels" not in val:
+ np = util.get_module(
+ "numpy", required="Bounding box support requires numpy"
+ )
+ classes = (
+ np.unique(list(box["class_id"] for box in val["box_data"]))
+ .astype(np.int32)
+ .tolist()
+ )
+ class_labels = {c: "class_" + str(c) for c in classes}
+ self._class_labels = class_labels
+ else:
+ self._class_labels = val["class_labels"]
+
+ def bind_to_run(
+ self,
+ run: "LocalRun",
+ key: Union[int, str],
+ step: Union[int, str],
+ id_: Optional[Union[int, str]] = None,
+ ignore_copy_err: Optional[bool] = None,
+ ) -> None:
+ # bind_to_run key argument is the Image parent key
+ # the self._key value is the mask's sub key
+ super().bind_to_run(run, key, step, id_=id_, ignore_copy_err=ignore_copy_err)
+ run._add_singleton(
+ "bounding_box/class_labels",
+ str(key) + "_wandb_delimeter_" + self._key,
+ self._class_labels,
+ )
+
+ @classmethod
+ def type_name(cls) -> str:
+ return "boxes2D"
+
+ def validate(self, val: dict) -> bool:
+ # Optional argument
+ if "class_labels" in val:
+ for k, v in list(val["class_labels"].items()):
+ if (not isinstance(k, numbers.Number)) or (not isinstance(v, str)):
+ raise TypeError(
+ "Class labels must be a dictionary of numbers to string"
+ )
+
+ boxes = val["box_data"]
+ if not isinstance(boxes, list):
+ raise TypeError("Boxes must be a list")
+
+ for box in boxes:
+ # Required arguments
+ error_str = (
+ "Each box must contain a position with: middle, width, and height or \
+ \nminX, maxX, minY, maxY."
+ )
+ if "position" not in box:
+ raise TypeError(error_str)
+ else:
+ valid = False
+ if (
+ "middle" in box["position"]
+ and len(box["position"]["middle"]) == 2
+ and has_num(box["position"], "width")
+ and has_num(box["position"], "height")
+ ):
+ valid = True
+ elif (
+ has_num(box["position"], "minX")
+ and has_num(box["position"], "maxX")
+ and has_num(box["position"], "minY")
+ and has_num(box["position"], "maxY")
+ ):
+ valid = True
+
+ if not valid:
+ raise TypeError(error_str)
+
+ # Optional arguments
+ if ("scores" in box) and not isinstance(box["scores"], dict):
+ raise TypeError("Box scores must be a dictionary")
+ elif "scores" in box:
+ for k, v in list(box["scores"].items()):
+ if not isinstance(k, str):
+ raise TypeError("A score key must be a string")
+ if not isinstance(v, numbers.Number):
+ raise TypeError("A score value must be a number")
+
+ if ("class_id" in box) and not isinstance(box["class_id"], int):
+ raise TypeError("A box's class_id must be an integer")
+
+ # Optional
+ if ("box_caption" in box) and not isinstance(box["box_caption"], str):
+ raise TypeError("A box's caption must be a string")
+ return True
+
+ def to_json(self, run_or_artifact: Union["LocalRun", "Artifact"]) -> dict:
+ if isinstance(run_or_artifact, wandb.Run):
+ return super().to_json(run_or_artifact)
+ elif isinstance(run_or_artifact, wandb.Artifact):
+ # TODO (tim): I would like to log out a proper dictionary representing this object, but don't
+ # want to mess with the visualizations that are currently available in the UI. This really should output
+ # an object with a _type key. Will need to push this change to the UI first to ensure backwards compat
+ return self._val
+ else:
+ raise TypeError("to_json accepts wandb_run.Run or wandb.Artifact")
+
+ @classmethod
+ def from_json(
+ cls: Type["BoundingBoxes2D"], json_obj: dict, source_artifact: "Artifact"
+ ) -> "BoundingBoxes2D":
+ return cls({"box_data": json_obj}, "")
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/helper_types/classes.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/helper_types/classes.py
new file mode 100644
index 0000000000000000000000000000000000000000..54a22054aa44ad58de5b46a72b1123d73bc8836d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/helper_types/classes.py
@@ -0,0 +1,159 @@
+import os
+from typing import TYPE_CHECKING, Any, Dict, Optional, Sequence, Type, Union
+
+from .. import _dtypes
+from ..base_types.media import Media
+
+if TYPE_CHECKING: # pragma: no cover
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ from ...wandb_run import Run as LocalRun
+
+
+class Classes(Media):
+ _log_type = "classes"
+
+ _class_set: Sequence[dict]
+
+ def __init__(self, class_set: Sequence[dict]) -> None:
+ """Classes is holds class metadata intended to be used in concert with other objects when visualizing artifacts.
+
+ Args:
+ class_set (list): list of dicts in the form of {"id":int|str, "name":str}
+ """
+ super().__init__()
+ for class_obj in class_set:
+ assert "id" in class_obj and "name" in class_obj
+ self._class_set = class_set
+
+ @classmethod
+ def from_json(
+ cls: Type["Classes"],
+ json_obj: dict,
+ source_artifact: Optional["Artifact"],
+ ) -> "Classes":
+ return cls(json_obj.get("class_set")) # type: ignore
+
+ def to_json(self, run_or_artifact: Optional[Union["LocalRun", "Artifact"]]) -> dict:
+ json_obj = {}
+ # This is a bit of a hack to allow _ClassesIdType to
+ # be able to operate fully without an artifact in play.
+ # In all other cases, artifact should be a true artifact.
+ if run_or_artifact is not None:
+ json_obj = super().to_json(run_or_artifact)
+ json_obj["_type"] = Classes._log_type
+ json_obj["class_set"] = self._class_set
+ return json_obj
+
+ def get_type(self) -> "_ClassesIdType":
+ return _ClassesIdType(self)
+
+ def __ne__(self, other: object) -> bool:
+ return not self.__eq__(other)
+
+ def __eq__(self, other: object) -> bool:
+ if isinstance(other, Classes):
+ return self._class_set == other._class_set
+ else:
+ return False
+
+
+class _ClassesIdType(_dtypes.Type):
+ name = "classesId"
+ legacy_names = ["wandb.Classes_id"]
+ types = [Classes]
+
+ def __init__(
+ self,
+ classes_obj: Optional[Classes] = None,
+ valid_ids: Optional["_dtypes.UnionType"] = None,
+ ):
+ if valid_ids is None:
+ valid_ids = _dtypes.UnionType()
+ elif isinstance(valid_ids, list):
+ valid_ids = _dtypes.UnionType(
+ [_dtypes.ConstType(item) for item in valid_ids]
+ )
+ elif isinstance(valid_ids, _dtypes.UnionType):
+ valid_ids = valid_ids
+ else:
+ raise TypeError("valid_ids must be None, list, or UnionType")
+
+ if classes_obj is None:
+ classes_obj = Classes(
+ [
+ {"id": _id.params["val"], "name": str(_id.params["val"])}
+ for _id in valid_ids.params["allowed_types"]
+ ]
+ )
+ elif not isinstance(classes_obj, Classes):
+ raise TypeError("valid_ids must be None, or instance of Classes")
+ else:
+ valid_ids = _dtypes.UnionType(
+ [
+ _dtypes.ConstType(class_obj["id"])
+ for class_obj in classes_obj._class_set
+ ]
+ )
+
+ self.wb_classes_obj_ref = classes_obj
+ self.params.update({"valid_ids": valid_ids})
+
+ def assign(self, py_obj: Optional[Any] = None) -> "_dtypes.Type":
+ return self.assign_type(_dtypes.ConstType(py_obj))
+
+ def assign_type(self, wb_type: "_dtypes.Type") -> "_dtypes.Type":
+ valid_ids = self.params["valid_ids"].assign_type(wb_type)
+ if not isinstance(valid_ids, _dtypes.InvalidType):
+ return self
+
+ return _dtypes.InvalidType()
+
+ @classmethod
+ def from_obj(cls, py_obj: Optional[Any] = None) -> "_dtypes.Type":
+ return cls(py_obj)
+
+ def to_json(self, artifact: Optional["Artifact"] = None) -> Dict[str, Any]:
+ cl_dict = super().to_json(artifact)
+ # TODO (tss): Refactor this block with the similar one in wandb.Image.
+ # This is a bit of a smell that the classes object does not follow
+ # the same file-pattern as other media types.
+ if artifact is not None:
+ class_name = os.path.join("media", "cls")
+ classes_entry = artifact.add(self.wb_classes_obj_ref, class_name)
+ cl_dict["params"]["classes_obj"] = {
+ "type": "classes-file",
+ "path": classes_entry.path,
+ "digest": classes_entry.digest, # is this needed really?
+ }
+ else:
+ cl_dict["params"]["classes_obj"] = self.wb_classes_obj_ref.to_json(artifact)
+ return cl_dict
+
+ @classmethod
+ def from_json(
+ cls,
+ json_dict: Dict[str, Any],
+ artifact: Optional["Artifact"] = None,
+ ) -> "_dtypes.Type":
+ classes_obj = None
+ if (
+ json_dict.get("params", {}).get("classes_obj", {}).get("type")
+ == "classes-file"
+ ):
+ if artifact is not None:
+ classes_obj = artifact.get(
+ json_dict.get("params", {}).get("classes_obj", {}).get("path")
+ )
+ assert classes_obj is None or isinstance(classes_obj, Classes)
+ else:
+ raise RuntimeError("Expected artifact to be non-null.")
+ else:
+ classes_obj = Classes.from_json(
+ json_dict["params"]["classes_obj"], artifact
+ )
+
+ return cls(classes_obj)
+
+
+_dtypes.TypeRegistry.add(_ClassesIdType)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/helper_types/image_mask.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/helper_types/image_mask.py
new file mode 100644
index 0000000000000000000000000000000000000000..e005911142fd21e6b222f0c3facdfbd4dc46a09f
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/helper_types/image_mask.py
@@ -0,0 +1,251 @@
+import numbers
+import os
+from typing import TYPE_CHECKING, Optional, Type, Union
+
+import wandb
+from wandb import util
+from wandb.sdk.lib import runid
+
+from .._private import MEDIA_TMP
+from ..base_types.media import Media
+
+if TYPE_CHECKING: # pragma: no cover
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ from ...wandb_run import Run as LocalRun
+
+
+class ImageMask(Media):
+ """Format image masks or overlays for logging to W&B.
+
+ Args:
+ val: (dictionary)
+ One of these two keys to represent the image:
+ mask_data : (2D numpy array) The mask containing an integer class label
+ for each pixel in the image
+ path : (string) The path to a saved image file of the mask
+ class_labels : (dictionary of integers to strings, optional) A mapping of the
+ integer class labels in the mask to readable class names. These will default
+ to class_0, class_1, class_2, etc.
+
+ key: (string)
+ The readable name or id for this mask type (e.g. predictions, ground_truth)
+
+ Examples:
+ ### Logging a single masked image
+
+ ```python
+ import numpy as np
+ import wandb
+
+ run = wandb.init()
+ image = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8)
+ predicted_mask = np.empty((100, 100), dtype=np.uint8)
+ ground_truth_mask = np.empty((100, 100), dtype=np.uint8)
+
+ predicted_mask[:50, :50] = 0
+ predicted_mask[50:, :50] = 1
+ predicted_mask[:50, 50:] = 2
+ predicted_mask[50:, 50:] = 3
+
+ ground_truth_mask[:25, :25] = 0
+ ground_truth_mask[25:, :25] = 1
+ ground_truth_mask[:25, 25:] = 2
+ ground_truth_mask[25:, 25:] = 3
+
+ class_labels = {0: "person", 1: "tree", 2: "car", 3: "road"}
+
+ masked_image = wandb.Image(
+ image,
+ masks={
+ "predictions": {
+ "mask_data": predicted_mask,
+ "class_labels": class_labels,
+ },
+ "ground_truth": {
+ "mask_data": ground_truth_mask,
+ "class_labels": class_labels,
+ },
+ },
+ )
+ run.log({"img_with_masks": masked_image})
+ ```
+
+ ### Log a masked image inside a Table
+
+ ```python
+ import numpy as np
+ import wandb
+
+ run = wandb.init()
+ image = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8)
+ predicted_mask = np.empty((100, 100), dtype=np.uint8)
+ ground_truth_mask = np.empty((100, 100), dtype=np.uint8)
+
+ predicted_mask[:50, :50] = 0
+ predicted_mask[50:, :50] = 1
+ predicted_mask[:50, 50:] = 2
+ predicted_mask[50:, 50:] = 3
+
+ ground_truth_mask[:25, :25] = 0
+ ground_truth_mask[25:, :25] = 1
+ ground_truth_mask[:25, 25:] = 2
+ ground_truth_mask[25:, 25:] = 3
+
+ class_labels = {0: "person", 1: "tree", 2: "car", 3: "road"}
+
+ class_set = wandb.Classes(
+ [
+ {"name": "person", "id": 0},
+ {"name": "tree", "id": 1},
+ {"name": "car", "id": 2},
+ {"name": "road", "id": 3},
+ ]
+ )
+
+ masked_image = wandb.Image(
+ image,
+ masks={
+ "predictions": {
+ "mask_data": predicted_mask,
+ "class_labels": class_labels,
+ },
+ "ground_truth": {
+ "mask_data": ground_truth_mask,
+ "class_labels": class_labels,
+ },
+ },
+ classes=class_set,
+ )
+
+ table = wandb.Table(columns=["image"])
+ table.add_data(masked_image)
+ run.log({"random_field": table})
+ ```
+ """
+
+ _log_type = "mask"
+
+ def __init__(self, val: dict, key: str) -> None:
+ """Initialize an ImageMask object.
+
+ Args:
+ val: (dictionary) One of these two keys to represent the image:
+ mask_data : (2D numpy array) The mask containing an integer class label
+ for each pixel in the image
+ path : (string) The path to a saved image file of the mask
+ class_labels : (dictionary of integers to strings, optional) A mapping
+ of the integer class labels in the mask to readable class names.
+ These will default to class_0, class_1, class_2, etc.
+
+ key: (string)
+ The readable name or id for this mask type (e.g. predictions, ground_truth)
+ """
+ super().__init__()
+
+ if "path" in val:
+ self._set_file(val["path"])
+ else:
+ np = util.get_module("numpy", required="Image mask support requires numpy")
+
+ if util.is_pytorch_tensor_typename(
+ util.get_full_typename(val["mask_data"])
+ ):
+ val["mask_data"] = val["mask_data"].cpu().numpy()
+
+ # Add default class mapping
+ if "class_labels" not in val:
+ classes = np.unique(val["mask_data"]).astype(np.int32).tolist()
+ class_labels = {c: "class_" + str(c) for c in classes}
+ val["class_labels"] = class_labels
+
+ self.validate(val)
+ self._val = val
+ self._key = key
+
+ ext = "." + self.type_name() + ".png"
+ tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ext)
+
+ pil_image = util.get_module(
+ "PIL.Image",
+ required='wandb.Image needs the PIL package. To get it, run "pip install pillow".',
+ )
+ image = pil_image.fromarray(val["mask_data"].astype(np.int8), mode="L")
+
+ image.save(tmp_path, transparency=None)
+ self._set_file(tmp_path, is_tmp=True, extension=ext)
+
+ def bind_to_run(
+ self,
+ run: "LocalRun",
+ key: Union[int, str],
+ step: Union[int, str],
+ id_: Optional[Union[int, str]] = None,
+ ignore_copy_err: Optional[bool] = None,
+ ) -> None:
+ # bind_to_run key argument is the Image parent key
+ # the self._key value is the mask's sub key
+ super().bind_to_run(run, key, step, id_=id_, ignore_copy_err=ignore_copy_err)
+ if hasattr(self, "_val") and "class_labels" in self._val:
+ class_labels = self._val["class_labels"]
+
+ run._add_singleton(
+ "mask/class_labels",
+ str(key) + "_wandb_delimeter_" + self._key,
+ class_labels,
+ )
+
+ @classmethod
+ def get_media_subdir(cls: Type["ImageMask"]) -> str:
+ return os.path.join("media", "images", cls.type_name())
+
+ @classmethod
+ def from_json(
+ cls: Type["ImageMask"], json_obj: dict, source_artifact: "Artifact"
+ ) -> "ImageMask":
+ return cls(
+ {"path": source_artifact.get_entry(json_obj["path"]).download()},
+ key="",
+ )
+
+ def to_json(self, run_or_artifact: Union["LocalRun", "Artifact"]) -> dict:
+ json_dict = super().to_json(run_or_artifact)
+
+ if isinstance(run_or_artifact, wandb.Run):
+ json_dict["_type"] = self.type_name()
+ return json_dict
+ elif isinstance(run_or_artifact, wandb.Artifact):
+ # Nothing special to add (used to add "digest", but no longer used.)
+ return json_dict
+ else:
+ raise TypeError("to_json accepts wandb_run.Run or wandb.Artifact")
+
+ @classmethod
+ def type_name(cls: Type["ImageMask"]) -> str:
+ return cls._log_type
+
+ def validate(self, val: dict) -> bool:
+ np = util.get_module("numpy", required="Image mask support requires numpy")
+ # 2D Make this work with all tensor(like) types
+ if "mask_data" not in val:
+ raise TypeError(
+ 'Missing key "mask_data": An image mask requires mask data: a 2D array representing the predictions'
+ )
+ else:
+ error_str = "mask_data must be a 2D array"
+ shape = val["mask_data"].shape
+ if len(shape) != 2:
+ raise TypeError(error_str)
+ if not (
+ (val["mask_data"] >= 0).all() and (val["mask_data"] <= 255).all()
+ ) and issubclass(val["mask_data"].dtype.type, np.integer):
+ raise TypeError("Mask data must be integers between 0 and 255")
+
+ # Optional argument
+ if "class_labels" in val:
+ for k, v in list(val["class_labels"].items()):
+ if (not isinstance(k, numbers.Number)) or (not isinstance(v, str)):
+ raise TypeError(
+ "Class labels must be a dictionary of numbers to strings"
+ )
+ return True
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/histogram.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/histogram.py
new file mode 100644
index 0000000000000000000000000000000000000000..7151b39e88f3a00a85d9f2fd8128d4279779f3af
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/histogram.py
@@ -0,0 +1,107 @@
+import sys
+from typing import TYPE_CHECKING, Optional, Sequence, Tuple, Union
+
+from wandb import util
+
+from .base_types.wb_value import WBValue
+
+if TYPE_CHECKING: # pragma: no cover
+ import numpy as np
+
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ from ..wandb_run import Run as LocalRun
+
+ NumpyHistogram = Tuple[np.ndarray, np.ndarray]
+
+
+class Histogram(WBValue):
+ """W&B class for histograms.
+
+ This object works just like numpy's histogram function
+ https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html
+
+ Attributes:
+ bins ([float]): Edges of bins
+ histogram ([int]): Number of elements falling in each bin.
+ """
+
+ MAX_LENGTH: int = 512
+ _log_type = "histogram"
+
+ def __init__(
+ self,
+ sequence: Optional[Sequence] = None,
+ np_histogram: Optional["NumpyHistogram"] = None,
+ num_bins: int = 64,
+ ) -> None:
+ """Initialize a Histogram object.
+
+ Args:
+ sequence: Input data for histogram.
+ np_histogram: Alternative input of a precomputed histogram.
+ num_bins: Number of bins for the histogram. The default number of bins
+ is 64. The maximum number of bins is 512.
+
+ Examples:
+ Generate histogram from a sequence.
+
+ ```python
+ import wandb
+
+ wandb.Histogram([1, 2, 3])
+ ```
+
+ Efficiently initialize from np.histogram.
+
+ ```python
+ import numpy as np
+ import wandb
+
+ hist = np.histogram(data)
+ wandb.Histogram(np_histogram=hist)
+ ```
+ """
+ if np_histogram:
+ if len(np_histogram) == 2:
+ self.histogram = (
+ np_histogram[0].tolist()
+ if hasattr(np_histogram[0], "tolist")
+ else np_histogram[0]
+ )
+ self.bins = (
+ np_histogram[1].tolist()
+ if hasattr(np_histogram[1], "tolist")
+ else np_histogram[1]
+ )
+ else:
+ raise ValueError(
+ "Expected np_histogram to be a tuple of (values, bin_edges) or sequence to be specified"
+ )
+ else:
+ np = util.get_module(
+ "numpy", required="Auto creation of histograms requires numpy"
+ )
+
+ histogram, bins = np.histogram(sequence, bins=num_bins)
+ self.histogram = histogram.tolist()
+ self.bins = bins.tolist()
+ if len(self.histogram) > self.MAX_LENGTH:
+ raise ValueError(f"The maximum length of a histogram is {self.MAX_LENGTH}")
+ if len(self.histogram) + 1 != len(self.bins):
+ raise ValueError("len(bins) must be len(histogram) + 1")
+
+ def to_json(self, run: Optional[Union["LocalRun", "Artifact"]] = None) -> dict:
+ """Returns the JSON representation expected by the backend.
+
+
+ """
+ return {"_type": self._log_type, "values": self.histogram, "bins": self.bins}
+
+ def __sizeof__(self) -> int:
+ """Estimated size in bytes.
+
+ Currently the factor of 1.7 is used to account for the JSON encoding. We use
+ this in tb_watcher.TBHistory.
+ """
+ return int((sys.getsizeof(self.histogram) + sys.getsizeof(self.bins)) * 1.7)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/html.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/html.py
new file mode 100644
index 0000000000000000000000000000000000000000..8eb79416ebe08e1e150f152e8baef112cf56a9cc
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/html.py
@@ -0,0 +1,165 @@
+import os
+import pathlib
+from typing import TYPE_CHECKING, Sequence, Type, Union
+
+from wandb.sdk.lib import filesystem, runid
+
+from . import _dtypes
+from ._private import MEDIA_TMP
+from .base_types.media import BatchableMedia
+
+if TYPE_CHECKING: # pragma: no cover
+ from typing import TextIO
+
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ from ..wandb_run import Run as LocalRun
+
+
+class Html(BatchableMedia):
+ """W&B class for logging HTML content to W&B."""
+
+ _log_type = "html-file"
+
+ def __init__(
+ self,
+ data: Union[str, pathlib.Path, "TextIO"],
+ inject: bool = True,
+ data_is_not_path: bool = False,
+ ) -> None:
+ """Creates a W&B HTML object.
+
+ Args:
+ data:
+ A string that is a path to a file with the extension ".html",
+ or a string or IO object containing literal HTML.
+ inject: Add a stylesheet to the HTML object. If set
+ to False the HTML will pass through unchanged.
+ data_is_not_path: If set to False, the data will be
+ treated as a path to a file.
+
+ Examples:
+ It can be initialized by providing a path to a file:
+
+ ```python
+ with wandb.init() as run:
+ run.log({"html": wandb.Html("./index.html")})
+ ```
+
+ Alternatively, it can be initialized by providing literal HTML,
+ in either a string or IO object:
+
+ ```python
+ with wandb.init() as run:
+ run.log({"html": wandb.Html("
Hello, world!
")})
+ ```
+ """
+ super().__init__()
+ data_is_path = (
+ isinstance(data, (str, pathlib.Path))
+ and os.path.isfile(data)
+ and os.path.splitext(data)[1] == ".html"
+ ) and not data_is_not_path
+ data_path = ""
+ if data_is_path:
+ data_path = str(data)
+ with open(data_path, encoding="utf-8") as file:
+ self.html = file.read()
+ elif isinstance(data, str):
+ self.html = data
+ elif hasattr(data, "read"):
+ if hasattr(data, "seek"):
+ data.seek(0)
+ self.html = data.read()
+ else:
+ raise ValueError("data must be a string or an io object")
+
+ if inject:
+ self.inject_head()
+
+ if inject or not data_is_path:
+ tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ".html")
+ with open(tmp_path, "w", encoding="utf-8") as out:
+ out.write(self.html)
+
+ self._set_file(tmp_path, is_tmp=True)
+ else:
+ self._set_file(data_path, is_tmp=False)
+
+ def inject_head(self) -> None:
+ """Inject a tag into the HTML.
+
+
+ """
+ join = ""
+ if "" in self.html:
+ parts = self.html.split("", 1)
+ parts[0] = parts[0] + ""
+ elif "" in self.html:
+ parts = self.html.split("", 1)
+ parts[0] = parts[0] + ""
+ parts[1] = "" + parts[1]
+ else:
+ parts = ["", self.html]
+ parts.insert(
+ 1,
+ '',
+ )
+ self.html = join.join(parts).strip()
+
+ @classmethod
+ def get_media_subdir(cls: Type["Html"]) -> str:
+ """Get media subdirectory.
+
+ "
+ """
+ return os.path.join("media", "html")
+
+ def to_json(self, run_or_artifact: Union["LocalRun", "Artifact"]) -> dict:
+ """Returns the JSON representation expected by the backend.
+
+
+ """
+ json_dict = super().to_json(run_or_artifact)
+ json_dict["_type"] = self._log_type
+ return json_dict
+
+ @classmethod
+ def from_json(
+ cls: Type["Html"], json_obj: dict, source_artifact: "Artifact"
+ ) -> "Html":
+ """Deserialize a JSON object into it's class representation.
+
+ "
+ """
+ return cls(source_artifact.get_entry(json_obj["path"]).download(), inject=False)
+
+ @classmethod
+ def seq_to_json(
+ cls: Type["Html"],
+ seq: Sequence["BatchableMedia"],
+ run: "LocalRun",
+ key: str,
+ step: Union[int, str],
+ ) -> dict:
+ """Convert a sequence of HTML objects to a JSON representation.
+
+ "
+ """
+ base_path = os.path.join(run.dir, cls.get_media_subdir())
+ filesystem.mkdir_exists_ok(base_path)
+
+ meta = {
+ "_type": "html",
+ "count": len(seq),
+ "html": [h.to_json(run) for h in seq],
+ }
+ return meta
+
+
+class _HtmlFileType(_dtypes.Type):
+ name = "html-file"
+ types = [Html]
+
+
+_dtypes.TypeRegistry.add(_HtmlFileType)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/image.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/image.py
new file mode 100644
index 0000000000000000000000000000000000000000..9dcb7934aa9e0df28481698215c249393b33b20b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/image.py
@@ -0,0 +1,985 @@
+import hashlib
+import logging
+import os
+import pathlib
+from io import BytesIO
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Type, Union, cast
+from urllib import parse
+
+from packaging.version import parse as parse_version
+
+import wandb
+from wandb import util
+from wandb.sdk.lib import hashutil, runid
+from wandb.sdk.lib.paths import LogicalPath
+
+from . import _dtypes
+from ._private import MEDIA_TMP
+from .base_types.media import BatchableMedia, Media
+from .helper_types.bounding_boxes_2d import BoundingBoxes2D
+from .helper_types.classes import Classes
+from .helper_types.image_mask import ImageMask
+
+if TYPE_CHECKING: # pragma: no cover
+ import matplotlib # type: ignore
+ import numpy as np
+ import torch # type: ignore
+ from PIL.Image import Image as PILImage
+
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ ImageDataType = Union[
+ "matplotlib.artist.Artist", "PILImage", "TorchTensorType", "np.ndarray"
+ ]
+ ImageDataOrPathType = Union[str, pathlib.Path, "Image", ImageDataType]
+ TorchTensorType = Union["torch.Tensor", "torch.Variable"]
+
+
+def _warn_on_invalid_data_range(
+ data: "np.ndarray",
+ normalize: bool = True,
+) -> None:
+ if not normalize:
+ return
+
+ np = util.get_module(
+ "numpy",
+ required="wandb.Image requires numpy if not supplying PIL Images: pip install numpy",
+ )
+
+ if np.min(data) < 0 or np.max(data) > 255:
+ wandb.termwarn(
+ "Data passed to `wandb.Image` should consist of values in the range [0, 255], "
+ "image data will be normalized to this range, "
+ "but behavior will be removed in a future version of wandb.",
+ repeat=False,
+ )
+
+
+def _guess_and_rescale_to_0_255(data: "np.ndarray") -> "np.ndarray":
+ """Guess the image's format and rescale its values to the range [0, 255].
+
+ This is an unfortunate design flaw carried forward for backward
+ compatibility. A better design would have been to document the expected
+ data format and not mangle the data provided by the user.
+
+ If given data in the range [0, 1], we multiply all values by 255
+ and round down to get integers.
+
+ If given data in the range [-1, 1], we rescale it by mapping -1 to 0 and
+ 1 to 255, then round down to get integers.
+
+ We clip and round all other data.
+ """
+ try:
+ import numpy as np
+ except ImportError:
+ raise wandb.Error(
+ "wandb.Image requires numpy if not supplying PIL images: pip install numpy"
+ ) from None
+
+ data_min: float = data.min()
+ data_max: float = data.max()
+
+ if 0 <= data_min and data_max <= 1:
+ return (data * 255).astype(np.uint8)
+
+ elif -1 <= data_min and data_max <= 1:
+ return (255 * 0.5 * (data + 1)).astype(np.uint8)
+
+ else:
+ return data.clip(0, 255).astype(np.uint8)
+
+
+def _convert_to_uint8(data: "np.ndarray") -> "np.ndarray":
+ np = util.get_module(
+ "numpy",
+ required="wandb.Image requires numpy if not supplying PIL Images: pip install numpy",
+ )
+ return data.astype(np.uint8)
+
+
+def _server_accepts_image_filenames(run: "wandb.Run") -> bool:
+ if run.offline:
+ return True
+
+ # Newer versions of wandb accept large image filenames arrays
+ # but older versions would have issues with this.
+ max_cli_version = util._get_max_cli_version()
+ if max_cli_version is None:
+ return False
+
+ accepts_image_filenames: bool = parse_version(max_cli_version) >= parse_version(
+ "0.12.10"
+ )
+ return accepts_image_filenames
+
+
+def _server_accepts_artifact_path(run: "wandb.Run") -> bool:
+ if run.offline:
+ return False
+
+ max_cli_version = util._get_max_cli_version()
+ if max_cli_version is None:
+ return False
+
+ return parse_version(max_cli_version) >= parse_version("0.12.14")
+
+
+class Image(BatchableMedia):
+ """A class for logging images to W&B."""
+
+ MAX_ITEMS = 108
+
+ # PIL limit
+ MAX_DIMENSION = 65500
+
+ _log_type = "image-file"
+
+ format: Optional[str]
+ _grouping: Optional[int]
+ _caption: Optional[str]
+ _width: Optional[int]
+ _height: Optional[int]
+ _image: Optional["PILImage"]
+ _classes: Optional["Classes"]
+ _boxes: Optional[Dict[str, "BoundingBoxes2D"]]
+ _masks: Optional[Dict[str, "ImageMask"]]
+ _file_type: Optional[str]
+
+ def __init__(
+ self,
+ data_or_path: "ImageDataOrPathType",
+ mode: Optional[str] = None,
+ caption: Optional[str] = None,
+ grouping: Optional[int] = None,
+ classes: Optional[Union["Classes", Sequence[dict]]] = None,
+ boxes: Optional[Union[Dict[str, "BoundingBoxes2D"], Dict[str, dict]]] = None,
+ masks: Optional[Union[Dict[str, "ImageMask"], Dict[str, dict]]] = None,
+ file_type: Optional[str] = None,
+ normalize: bool = True,
+ ) -> None:
+ """Initialize a `wandb.Image` object.
+
+ This class handles various image data formats and automatically normalizes
+ pixel values to the range [0, 255] when needed, ensuring compatibility
+ with the W&B backend.
+
+ * Data in range [0, 1] is multiplied by 255 and converted to uint8
+ * Data in range [-1, 1] is rescaled from [-1, 1] to [0, 255] by mapping
+ -1 to 0 and 1 to 255, then converted to uint8
+ * Data outside [-1, 1] but not in [0, 255] is clipped to [0, 255] and
+ converted to uint8 (with a warning if values fall outside [0, 255])
+ * Data already in [0, 255] is converted to uint8 without modification
+
+ Args:
+ data_or_path: Accepts NumPy array/pytorch tensor of image data,
+ a PIL image object, or a path to an image file. If a NumPy
+ array or pytorch tensor is provided,
+ the image data will be saved to the given file type.
+ If the values are not in the range [0, 255] or all values are in the range [0, 1],
+ the image pixel values will be normalized to the range [0, 255]
+ unless `normalize` is set to `False`.
+ - pytorch tensor should be in the format (channel, height, width)
+ - NumPy array should be in the format (height, width, channel)
+ mode: The PIL mode for an image. Most common are "L", "RGB",
+ "RGBA". Full explanation at https://pillow.readthedocs.io/en/stable/handbook/concepts.html#modes
+ caption: Label for display of image.
+ grouping: The grouping number for the image.
+ classes: A list of class information for the image,
+ used for labeling bounding boxes, and image masks.
+ boxes: A dictionary containing bounding box information for the image.
+ see https://docs.wandb.ai/ref/python/data-types/boundingboxes2d/
+ masks: A dictionary containing mask information for the image.
+ see https://docs.wandb.ai/ref/python/data-types/imagemask/
+ file_type: The file type to save the image as.
+ This parameter has no effect if `data_or_path` is a path to an image file.
+ normalize: If `True`, normalize the image pixel values to fall within the range of [0, 255].
+ Normalize is only applied if `data_or_path` is a numpy array or pytorch tensor.
+
+ Examples:
+ Create a wandb.Image from a numpy array
+
+ ```python
+ import numpy as np
+ import wandb
+
+ with wandb.init() as run:
+ examples = []
+ for i in range(3):
+ pixels = np.random.randint(low=0, high=256, size=(100, 100, 3))
+ image = wandb.Image(pixels, caption=f"random field {i}")
+ examples.append(image)
+ run.log({"examples": examples})
+ ```
+
+ Create a wandb.Image from a PILImage
+
+ ```python
+ import numpy as np
+ from PIL import Image as PILImage
+ import wandb
+
+ with wandb.init() as run:
+ examples = []
+ for i in range(3):
+ pixels = np.random.randint(
+ low=0, high=256, size=(100, 100, 3), dtype=np.uint8
+ )
+ pil_image = PILImage.fromarray(pixels, mode="RGB")
+ image = wandb.Image(pil_image, caption=f"random field {i}")
+ examples.append(image)
+ run.log({"examples": examples})
+ ```
+
+ Log .jpg rather than .png (default)
+
+ ```python
+ import numpy as np
+ import wandb
+
+ with wandb.init() as run:
+ examples = []
+ for i in range(3):
+ pixels = np.random.randint(low=0, high=256, size=(100, 100, 3))
+ image = wandb.Image(
+ pixels, caption=f"random field {i}", file_type="jpg"
+ )
+ examples.append(image)
+ run.log({"examples": examples})
+ ```
+ """
+ super().__init__(caption=caption)
+ # TODO: We should remove grouping, it's a terrible name and I don't
+ # think anyone uses it.
+
+ self._grouping = None
+ self._width = None
+ self._height = None
+ self._image = None
+ self._classes = None
+ self._boxes = None
+ self._masks = None
+ self._file_type = None
+
+ # Allows the user to pass an Image object as the first parameter and have a perfect copy,
+ # only overriding additional metadata passed in. If this pattern is compelling, we can generalize.
+ if isinstance(data_or_path, Image):
+ self._initialize_from_wbimage(data_or_path)
+ elif isinstance(data_or_path, (str, pathlib.Path)):
+ data_or_path = str(data_or_path)
+
+ if self.path_is_reference(data_or_path):
+ self._initialize_from_reference(data_or_path)
+ else:
+ self._initialize_from_path(data_or_path)
+ else:
+ self._initialize_from_data(data_or_path, mode, file_type, normalize)
+ self._set_initialization_meta(
+ grouping, caption, classes, boxes, masks, file_type
+ )
+
+ def _set_initialization_meta(
+ self,
+ grouping: Optional[int] = None,
+ caption: Optional[str] = None,
+ classes: Optional[Union["Classes", Sequence[dict]]] = None,
+ boxes: Optional[Union[Dict[str, "BoundingBoxes2D"], Dict[str, dict]]] = None,
+ masks: Optional[Union[Dict[str, "ImageMask"], Dict[str, dict]]] = None,
+ file_type: Optional[str] = None,
+ ) -> None:
+ if grouping is not None:
+ self._grouping = grouping
+
+ total_classes = {}
+
+ if boxes:
+ if not isinstance(boxes, dict):
+ raise ValueError('Images "boxes" argument must be a dictionary')
+ boxes_final: Dict[str, BoundingBoxes2D] = {}
+ for key in boxes:
+ box_item = boxes[key]
+ if isinstance(box_item, BoundingBoxes2D):
+ boxes_final[key] = box_item
+ elif isinstance(box_item, dict):
+ # TODO: Consider injecting top-level classes if user-provided is empty
+ boxes_final[key] = BoundingBoxes2D(box_item, key)
+ total_classes.update(boxes_final[key]._class_labels)
+ self._boxes = boxes_final
+
+ if masks:
+ if not isinstance(masks, dict):
+ raise ValueError('Images "masks" argument must be a dictionary')
+ masks_final: Dict[str, ImageMask] = {}
+ for key in masks:
+ mask_item = masks[key]
+ if isinstance(mask_item, ImageMask):
+ masks_final[key] = mask_item
+ elif isinstance(mask_item, dict):
+ # TODO: Consider injecting top-level classes if user-provided is empty
+ masks_final[key] = ImageMask(mask_item, key)
+ if hasattr(masks_final[key], "_val"):
+ total_classes.update(masks_final[key]._val["class_labels"])
+ self._masks = masks_final
+
+ if classes is not None:
+ if isinstance(classes, Classes):
+ total_classes.update(
+ {val["id"]: val["name"] for val in classes._class_set}
+ )
+ else:
+ total_classes.update({val["id"]: val["name"] for val in classes})
+
+ if len(total_classes.keys()) > 0:
+ self._classes = Classes(
+ [
+ {"id": key, "name": total_classes[key]}
+ for key in total_classes.keys()
+ ]
+ )
+ if self.image is not None:
+ self._width, self._height = self.image.size
+ self._free_ram()
+
+ def _initialize_from_wbimage(self, wbimage: "Image") -> None:
+ self._grouping = wbimage._grouping
+ self._caption = wbimage._caption
+ self._width = wbimage._width
+ self._height = wbimage._height
+ self._image = wbimage._image
+ self._classes = wbimage._classes
+ self._path = wbimage._path
+ self._is_tmp = wbimage._is_tmp
+ self._extension = wbimage._extension
+ self._sha256 = wbimage._sha256
+ self._size = wbimage._size
+ self.format = wbimage.format
+ self._file_type = wbimage._file_type
+ self._artifact_source = wbimage._artifact_source
+ self._artifact_target = wbimage._artifact_target
+
+ # We do not want to implicitly copy boxes or masks, just the image-related data.
+ # self._boxes = wbimage._boxes
+ # self._masks = wbimage._masks
+
+ def _initialize_from_path(self, path: str) -> None:
+ pil_image = util.get_module(
+ "PIL.Image",
+ required='wandb.Image needs the PIL package. To get it, run "pip install pillow".',
+ )
+ self._set_file(path, is_tmp=False)
+ self._image = pil_image.open(path)
+ assert self._image is not None
+ self._image.load()
+ ext = os.path.splitext(path)[1][1:]
+ self.format = ext
+
+ def _initialize_from_reference(self, path: str) -> None:
+ self._path = path
+ self._is_tmp = False
+ self._sha256 = hashlib.sha256(path.encode("utf-8")).hexdigest()
+ path = parse.urlparse(path).path
+ ext = path.split("/")[-1].split(".")[-1]
+ self.format = ext
+
+ def _initialize_from_data(
+ self,
+ data: "ImageDataType",
+ mode: Optional[str] = None,
+ file_type: Optional[str] = None,
+ normalize: bool = True,
+ ) -> None:
+ pil_image = util.get_module(
+ "PIL.Image",
+ required='wandb.Image needs the PIL package. To get it, run "pip install pillow".',
+ )
+
+ accepted_formats = ["png", "jpg", "jpeg", "bmp"]
+ self.format = file_type or "png"
+
+ if self.format not in accepted_formats:
+ raise ValueError(f"file_type must be one of {accepted_formats}")
+
+ tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + "." + self.format)
+
+ if util.is_matplotlib_typename(util.get_full_typename(data)):
+ buf = BytesIO()
+ util.ensure_matplotlib_figure(data).savefig(buf, format=self.format)
+ self._image = pil_image.open(buf)
+ elif isinstance(data, pil_image.Image):
+ self._image = data
+ elif util.is_pytorch_tensor_typename(util.get_full_typename(data)):
+ if hasattr(data, "requires_grad") and data.requires_grad:
+ data = data.detach() # type: ignore
+ if hasattr(data, "dtype") and str(data.dtype) == "torch.uint8":
+ data = data.to(float) # type: ignore [union-attr]
+ mode = mode or self.guess_mode(data, file_type)
+ data = data.permute(1, 2, 0).cpu().numpy() # type: ignore [union-attr]
+
+ _warn_on_invalid_data_range(data, normalize)
+
+ data = _guess_and_rescale_to_0_255(data) if normalize else data # type: ignore [arg-type]
+ data = _convert_to_uint8(data)
+
+ if data.ndim > 2:
+ data = data.squeeze()
+
+ self._image = pil_image.fromarray(
+ data,
+ mode=mode,
+ )
+ else:
+ if hasattr(data, "numpy"): # TF data eager tensors
+ data = data.numpy()
+ if data.ndim > 2: # type: ignore [union-attr]
+ # get rid of trivial dimensions as a convenience
+ data = data.squeeze() # type: ignore [union-attr]
+
+ _warn_on_invalid_data_range(data, normalize) # type: ignore [arg-type]
+
+ mode = mode or self.guess_mode(data, file_type)
+ data = _guess_and_rescale_to_0_255(data) if normalize else data # type: ignore [arg-type]
+ data = _convert_to_uint8(data) # type: ignore [arg-type]
+ self._image = pil_image.fromarray(
+ data,
+ mode=mode,
+ )
+
+ assert self._image is not None
+ self._image.save(tmp_path, transparency=None)
+ self._set_file(tmp_path, is_tmp=True)
+
+ @classmethod
+ def from_json(
+ cls: Type["Image"], json_obj: dict, source_artifact: "Artifact"
+ ) -> "Image":
+ """Factory method to create an Audio object from a JSON object.
+
+ "
+ """
+ classes: Optional[Classes] = None
+ if json_obj.get("classes") is not None:
+ value = source_artifact.get(json_obj["classes"]["path"])
+ assert isinstance(value, (type(None), Classes))
+ classes = value
+
+ masks = json_obj.get("masks")
+ _masks: Optional[Dict[str, ImageMask]] = None
+ if masks:
+ _masks = {}
+ for key in masks:
+ _masks[key] = ImageMask.from_json(masks[key], source_artifact)
+ _masks[key]._set_artifact_source(source_artifact)
+ _masks[key]._key = key
+
+ boxes = json_obj.get("boxes")
+ _boxes: Optional[Dict[str, BoundingBoxes2D]] = None
+ if boxes:
+ _boxes = {}
+ for key in boxes:
+ _boxes[key] = BoundingBoxes2D.from_json(boxes[key], source_artifact)
+ _boxes[key]._key = key
+
+ return cls(
+ source_artifact.get_entry(json_obj["path"]).download(),
+ caption=json_obj.get("caption"),
+ grouping=json_obj.get("grouping"),
+ classes=classes,
+ boxes=_boxes,
+ masks=_masks,
+ )
+
+ @classmethod
+ def get_media_subdir(cls: Type["Image"]) -> str:
+ """Get media subdirectory.
+
+ "
+ """
+ return os.path.join("media", "images")
+
+ def bind_to_run(
+ self,
+ run: "wandb.Run",
+ key: Union[int, str],
+ step: Union[int, str],
+ id_: Optional[Union[int, str]] = None,
+ ignore_copy_err: Optional[bool] = None,
+ ) -> None:
+ """Bind this object to a run.
+
+
+ """
+ # For Images, we are going to avoid copying the image file to the run.
+ # We should make this common functionality for all media types, but that
+ # requires a broader UI refactor. This model can easily be moved to the
+ # higher level Media class, but that will require every UI surface area
+ # that depends on the `path` to be able to instead consume
+ # `artifact_path`. I (Tim) think the media panel makes up most of this
+ # space, but there are also custom charts, and maybe others. Let's
+ # commit to getting all that fixed up before moving this to the top
+ # level Media class.
+ if self.path_is_reference(self._path):
+ raise ValueError(
+ "Image media created by a reference to external storage cannot currently be added to a run"
+ )
+
+ if (
+ not _server_accepts_artifact_path(run)
+ or self._get_artifact_entry_ref_url() is None
+ ):
+ super().bind_to_run(run, key, step, id_, ignore_copy_err=ignore_copy_err)
+ if self._boxes is not None:
+ for i, k in enumerate(self._boxes):
+ id_ = f"{id_}{i}" if id_ is not None else None
+ self._boxes[k].bind_to_run(
+ run, key, step, id_, ignore_copy_err=ignore_copy_err
+ )
+
+ if self._masks is not None:
+ for i, k in enumerate(self._masks):
+ id_ = f"{id_}{i}" if id_ is not None else None
+ self._masks[k].bind_to_run(
+ run, key, step, id_, ignore_copy_err=ignore_copy_err
+ )
+
+ def to_json(self, run_or_artifact: Union["wandb.Run", "Artifact"]) -> dict:
+ """Returns the JSON representation expected by the backend.
+
+
+ """
+ json_dict = super().to_json(run_or_artifact)
+ json_dict["_type"] = Image._log_type
+ json_dict["format"] = self.format
+
+ if self._width is not None:
+ json_dict["width"] = self._width
+ if self._height is not None:
+ json_dict["height"] = self._height
+ if self._grouping:
+ json_dict["grouping"] = self._grouping
+
+ if isinstance(run_or_artifact, wandb.Artifact):
+ artifact = run_or_artifact
+ if (
+ self._masks is not None or self._boxes is not None
+ ) and self._classes is None:
+ raise ValueError(
+ "classes must be passed to wandb.Image which have masks or bounding boxes when adding to artifacts"
+ )
+
+ if self._classes is not None:
+ class_id = hashutil._md5(
+ str(self._classes._class_set).encode("utf-8")
+ ).hexdigest()
+ class_name = os.path.join(
+ "media",
+ "classes",
+ class_id + "_cls",
+ )
+ classes_entry = artifact.add(self._classes, class_name)
+ json_dict["classes"] = {
+ "type": "classes-file",
+ "path": classes_entry.path,
+ "digest": classes_entry.digest,
+ }
+
+ elif not isinstance(run_or_artifact, wandb.Run):
+ raise TypeError("to_json accepts wandb.Run or wandb_artifact.Artifact")
+
+ if self._boxes:
+ json_dict["boxes"] = {
+ k: box.to_json(run_or_artifact) for (k, box) in self._boxes.items()
+ }
+ if self._masks:
+ json_dict["masks"] = {
+ k: mask.to_json(run_or_artifact) for (k, mask) in self._masks.items()
+ }
+ return json_dict
+
+ def guess_mode(
+ self,
+ data: Union["np.ndarray", "torch.Tensor"],
+ file_type: Optional[str] = None,
+ ) -> str:
+ """Guess what type of image the np.array is representing.
+
+
+ """
+ # TODO: do we want to support dimensions being at the beginning of the array?
+ ndims = data.ndim
+ if util.is_pytorch_tensor_typename(util.get_full_typename(data)):
+ # Torch tenors typically have the channels dimension first
+ num_channels = data.shape[0]
+ else:
+ num_channels = data.shape[-1]
+
+ if ndims == 2 or num_channels == 1:
+ return "L"
+ elif num_channels == 3:
+ return "RGB"
+ elif num_channels == 4:
+ if file_type in ["jpg", "jpeg"]:
+ wandb.termwarn(
+ "JPEG format does not support transparency. "
+ "Ignoring alpha channel.",
+ repeat=False,
+ )
+ return "RGB"
+ else:
+ return "RGBA"
+ else:
+ raise ValueError(
+ f"Un-supported shape for image conversion {list(data.shape)}"
+ )
+
+ @classmethod
+ def seq_to_json(
+ cls: Type["Image"],
+ seq: Sequence["BatchableMedia"],
+ run: "wandb.Run",
+ key: str,
+ step: Union[int, str],
+ ) -> dict:
+ """Convert a sequence of Image objects to a JSON representation.
+
+ "
+ """
+ if TYPE_CHECKING:
+ seq = cast(Sequence["Image"], seq)
+
+ jsons = [obj.to_json(run) for obj in seq]
+
+ media_dir = cls.get_media_subdir()
+
+ for obj in jsons:
+ expected = LogicalPath(media_dir)
+ if "path" in obj and not obj["path"].startswith(expected):
+ raise ValueError(
+ "Files in an array of Image's must be in the {} directory, not {}".format(
+ cls.get_media_subdir(), obj["path"]
+ )
+ )
+
+ num_images_to_log = len(seq)
+ width, height = seq[0].image.size # type: ignore
+ format = jsons[0]["format"]
+
+ def size_equals_image(image: "Image") -> bool:
+ img_width, img_height = image.image.size # type: ignore
+ return img_width == width and img_height == height
+
+ sizes_match = all(size_equals_image(img) for img in seq)
+ if not sizes_match:
+ logging.warning(
+ "Images sizes do not match. This will causes images to be display incorrectly in the UI."
+ )
+
+ meta = {
+ "_type": "images/separated",
+ "width": width,
+ "height": height,
+ "format": format,
+ "count": num_images_to_log,
+ }
+ if _server_accepts_image_filenames(run):
+ meta["filenames"] = [
+ obj.get("path", obj.get("artifact_path")) for obj in jsons
+ ]
+ else:
+ wandb.termwarn(
+ "Unable to log image array filenames. In some cases, this can prevent images from being "
+ "viewed in the UI. Please upgrade your wandb server",
+ repeat=False,
+ )
+
+ captions = Image.all_captions(seq)
+
+ if captions:
+ meta["captions"] = captions
+
+ all_masks = Image.all_masks(seq, run, key, step)
+
+ if all_masks:
+ meta["all_masks"] = all_masks
+
+ all_boxes = Image.all_boxes(seq, run, key, step)
+
+ if all_boxes:
+ meta["all_boxes"] = all_boxes
+
+ return meta
+
+ @classmethod
+ def all_masks(
+ cls: Type["Image"],
+ images: Sequence["Image"],
+ run: "wandb.Run",
+ run_key: str,
+ step: Union[int, str],
+ ) -> Union[List[Optional[dict]], bool]:
+ """Collect all masks from a list of images.
+
+ "
+ """
+ all_mask_groups: List[Optional[dict]] = []
+ for image in images:
+ if image._masks:
+ mask_group = {}
+ for k in image._masks:
+ mask = image._masks[k]
+ mask_group[k] = mask.to_json(run)
+ all_mask_groups.append(mask_group)
+ else:
+ all_mask_groups.append(None)
+ if all_mask_groups and not all(x is None for x in all_mask_groups):
+ return all_mask_groups
+ else:
+ return False
+
+ @classmethod
+ def all_boxes(
+ cls: Type["Image"],
+ images: Sequence["Image"],
+ run: "wandb.Run",
+ run_key: str,
+ step: Union[int, str],
+ ) -> Union[List[Optional[dict]], bool]:
+ """Collect all boxes from a list of images.
+
+ "
+ """
+ all_box_groups: List[Optional[dict]] = []
+ for image in images:
+ if image._boxes:
+ box_group = {}
+ for k in image._boxes:
+ box = image._boxes[k]
+ box_group[k] = box.to_json(run)
+ all_box_groups.append(box_group)
+ else:
+ all_box_groups.append(None)
+ if all_box_groups and not all(x is None for x in all_box_groups):
+ return all_box_groups
+ else:
+ return False
+
+ @classmethod
+ def all_captions(
+ cls: Type["Image"], images: Sequence["Media"]
+ ) -> Union[bool, Sequence[Optional[str]]]:
+ """Get captions from a list of images.
+
+ "
+ """
+ return cls.captions(images)
+
+ def __ne__(self, other: object) -> bool:
+ return not self.__eq__(other)
+
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, Image):
+ return False
+ else:
+ if self.path_is_reference(self._path) and self.path_is_reference(
+ other._path
+ ):
+ return self._path == other._path
+ self_image = self.image
+ other_image = other.image
+ if self_image is not None:
+ self_image = list(self_image.getdata()) # type: ignore
+ if other_image is not None:
+ other_image = list(other_image.getdata()) # type: ignore
+
+ return (
+ self._grouping == other._grouping
+ and self._caption == other._caption
+ and self._width == other._width
+ and self._height == other._height
+ and self_image == other_image
+ and self._classes == other._classes
+ )
+
+ def to_data_array(self) -> List[Any]:
+ """Convert to data array.
+
+
+ """
+ res = []
+ if self.image is not None:
+ data = list(self.image.getdata())
+ for i in range(self.image.height):
+ res.append(data[i * self.image.width : (i + 1) * self.image.width])
+ self._free_ram()
+ return res
+
+ def _free_ram(self) -> None:
+ if self._path is not None:
+ self._image = None
+
+ @property
+ def image(self) -> Optional["PILImage"]:
+ if self._image is None:
+ if self._path is not None and not self.path_is_reference(self._path):
+ pil_image = util.get_module(
+ "PIL.Image",
+ required='wandb.Image needs the PIL package. To get it, run "pip install pillow".',
+ )
+ self._image = pil_image.open(self._path)
+ self._image.load()
+ return self._image
+
+
+# Custom dtypes for typing system
+class _ImageFileType(_dtypes.Type):
+ name = "image-file"
+ legacy_names = ["wandb.Image"]
+ types = [Image]
+
+ def __init__(
+ self,
+ box_layers=None,
+ box_score_keys=None,
+ mask_layers=None,
+ class_map=None,
+ **kwargs,
+ ):
+ box_layers = box_layers or {}
+ box_score_keys = box_score_keys or []
+ mask_layers = mask_layers or {}
+ class_map = class_map or {}
+
+ if isinstance(box_layers, _dtypes.ConstType):
+ box_layers = box_layers._params["val"]
+ if not isinstance(box_layers, dict):
+ raise TypeError("box_layers must be a dict")
+ else:
+ box_layers = _dtypes.ConstType(
+ {layer_key: set(box_layers[layer_key]) for layer_key in box_layers}
+ )
+
+ if isinstance(mask_layers, _dtypes.ConstType):
+ mask_layers = mask_layers._params["val"]
+ if not isinstance(mask_layers, dict):
+ raise TypeError("mask_layers must be a dict")
+ else:
+ mask_layers = _dtypes.ConstType(
+ {layer_key: set(mask_layers[layer_key]) for layer_key in mask_layers}
+ )
+
+ if isinstance(box_score_keys, _dtypes.ConstType):
+ box_score_keys = box_score_keys._params["val"]
+ if not isinstance(box_score_keys, list) and not isinstance(box_score_keys, set):
+ raise TypeError("box_score_keys must be a list or a set")
+ else:
+ box_score_keys = _dtypes.ConstType(set(box_score_keys))
+
+ if isinstance(class_map, _dtypes.ConstType):
+ class_map = class_map._params["val"]
+ if not isinstance(class_map, dict):
+ raise TypeError("class_map must be a dict")
+ else:
+ class_map = _dtypes.ConstType(class_map)
+
+ self.params.update(
+ {
+ "box_layers": box_layers,
+ "box_score_keys": box_score_keys,
+ "mask_layers": mask_layers,
+ "class_map": class_map,
+ }
+ )
+
+ def assign_type(self, wb_type=None):
+ if isinstance(wb_type, _ImageFileType):
+ box_layers_self = self.params["box_layers"].params["val"] or {}
+ box_score_keys_self = self.params["box_score_keys"].params["val"] or []
+ mask_layers_self = self.params["mask_layers"].params["val"] or {}
+ class_map_self = self.params["class_map"].params["val"] or {}
+
+ box_layers_other = wb_type.params["box_layers"].params["val"] or {}
+ box_score_keys_other = wb_type.params["box_score_keys"].params["val"] or []
+ mask_layers_other = wb_type.params["mask_layers"].params["val"] or {}
+ class_map_other = wb_type.params["class_map"].params["val"] or {}
+
+ # Merge the class_ids from each set of box_layers
+ box_layers = {
+ str(key): set(
+ list(box_layers_self.get(key, []))
+ + list(box_layers_other.get(key, []))
+ )
+ for key in set(
+ list(box_layers_self.keys()) + list(box_layers_other.keys())
+ )
+ }
+
+ # Merge the class_ids from each set of mask_layers
+ mask_layers = {
+ str(key): set(
+ list(mask_layers_self.get(key, []))
+ + list(mask_layers_other.get(key, []))
+ )
+ for key in set(
+ list(mask_layers_self.keys()) + list(mask_layers_other.keys())
+ )
+ }
+
+ # Merge the box score keys
+ box_score_keys = set(list(box_score_keys_self) + list(box_score_keys_other))
+
+ # Merge the class_map
+ class_map = {
+ str(key): class_map_self.get(key, class_map_other.get(key, None))
+ for key in set(
+ list(class_map_self.keys()) + list(class_map_other.keys())
+ )
+ }
+
+ return _ImageFileType(box_layers, box_score_keys, mask_layers, class_map)
+
+ return _dtypes.InvalidType()
+
+ @classmethod
+ def from_obj(cls, py_obj):
+ if not isinstance(py_obj, Image):
+ raise TypeError("py_obj must be a wandb.Image")
+ else:
+ if hasattr(py_obj, "_boxes") and py_obj._boxes:
+ box_layers = {
+ str(key): set(py_obj._boxes[key]._class_labels.keys())
+ for key in py_obj._boxes.keys()
+ }
+ box_score_keys = {
+ key
+ for val in py_obj._boxes.values()
+ for box in val._val
+ for key in box.get("scores", {}).keys()
+ }
+
+ else:
+ box_layers = {}
+ box_score_keys = set()
+
+ if hasattr(py_obj, "_masks") and py_obj._masks:
+ mask_layers = {
+ str(key): set(
+ py_obj._masks[key]._val["class_labels"].keys()
+ if hasattr(py_obj._masks[key], "_val")
+ else []
+ )
+ for key in py_obj._masks.keys()
+ }
+ else:
+ mask_layers = {}
+
+ if hasattr(py_obj, "_classes") and py_obj._classes:
+ class_set = {
+ str(item["id"]): item["name"] for item in py_obj._classes._class_set
+ }
+ else:
+ class_set = {}
+
+ return cls(box_layers, box_score_keys, mask_layers, class_set)
+
+
+_dtypes.TypeRegistry.add(_ImageFileType)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/molecule.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/molecule.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2129d4b64e0e34138d58de081e15850e3e66a16
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/molecule.py
@@ -0,0 +1,250 @@
+import io
+import os
+import pathlib
+from typing import TYPE_CHECKING, Optional, Sequence, Type, Union
+
+from wandb import util
+from wandb.sdk.lib import runid
+from wandb.sdk.lib.paths import LogicalPath
+
+from ._private import MEDIA_TMP
+from .base_types.media import BatchableMedia, Media
+
+if TYPE_CHECKING: # pragma: no cover
+ from typing import TextIO
+
+ import rdkit.Chem # type: ignore
+
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ from ..wandb_run import Run as LocalRun
+
+ RDKitDataType = Union[str, "rdkit.Chem.rdchem.Mol"]
+
+
+class Molecule(BatchableMedia):
+ """W&B class for 3D Molecular data."""
+
+ SUPPORTED_TYPES = {
+ "pdb",
+ "pqr",
+ "mmcif",
+ "mcif",
+ "cif",
+ "sdf",
+ "sd",
+ "gro",
+ "mol2",
+ "mmtf",
+ }
+ SUPPORTED_RDKIT_TYPES = {"mol", "sdf"}
+ _log_type = "molecule-file"
+
+ def __init__(
+ self,
+ data_or_path: Union[str, pathlib.Path, "TextIO"],
+ caption: Optional[str] = None,
+ **kwargs: str,
+ ) -> None:
+ """Initialize a Molecule object.
+
+ Args:
+ data_or_path: Molecule can be initialized from a file name or an io object.
+ caption: Caption associated with the molecule for display.
+ """
+ super().__init__(caption=caption)
+
+ if hasattr(data_or_path, "name"):
+ # if the file has a path, we just detect the type and copy it from there
+ data_or_path = data_or_path.name
+
+ if hasattr(data_or_path, "read"):
+ if hasattr(data_or_path, "seek"):
+ data_or_path.seek(0)
+ molecule = data_or_path.read()
+
+ extension = kwargs.pop("file_type", None)
+ if extension is None:
+ raise ValueError(
+ "Must pass file_type keyword argument when using io objects."
+ )
+ if extension not in Molecule.SUPPORTED_TYPES:
+ raise ValueError(
+ "Molecule 3D only supports files of the type: "
+ + ", ".join(Molecule.SUPPORTED_TYPES)
+ )
+
+ tmp_path = os.path.join(
+ MEDIA_TMP.name, runid.generate_id() + "." + extension
+ )
+ with open(tmp_path, "w") as f:
+ f.write(molecule)
+
+ self._set_file(tmp_path, is_tmp=True)
+ elif isinstance(data_or_path, (str, pathlib.Path)):
+ data_or_path = str(data_or_path)
+
+ extension = os.path.splitext(data_or_path)[1][1:]
+ if extension not in Molecule.SUPPORTED_TYPES:
+ raise ValueError(
+ "Molecule only supports files of the type: "
+ + ", ".join(Molecule.SUPPORTED_TYPES)
+ )
+
+ self._set_file(data_or_path, is_tmp=False)
+ else:
+ raise ValueError("Data must be file name or a file object")
+
+ @classmethod
+ def from_rdkit(
+ cls,
+ data_or_path: "RDKitDataType",
+ caption: Optional[str] = None,
+ convert_to_3d_and_optimize: bool = True,
+ mmff_optimize_molecule_max_iterations: int = 200,
+ ) -> "Molecule":
+ """Convert RDKit-supported file/object types to wandb.Molecule.
+
+ Args:
+ data_or_path: (string, rdkit.Chem.rdchem.Mol)
+ Molecule can be initialized from a file name or an rdkit.Chem.rdchem.Mol object.
+ caption: (string)
+ Caption associated with the molecule for display.
+ convert_to_3d_and_optimize: (bool)
+ Convert to rdkit.Chem.rdchem.Mol with 3D coordinates.
+ This is an expensive operation that may take a long time for complicated molecules.
+ mmff_optimize_molecule_max_iterations: (int)
+ Number of iterations to use in rdkit.Chem.AllChem.MMFFOptimizeMolecule
+
+
+ """
+ rdkit_chem = util.get_module(
+ "rdkit.Chem",
+ required='wandb.Molecule needs the rdkit-pypi package. To get it, run "pip install rdkit-pypi".',
+ )
+ rdkit_chem_all_chem = util.get_module(
+ "rdkit.Chem.AllChem",
+ required='wandb.Molecule needs the rdkit-pypi package. To get it, run "pip install rdkit-pypi".',
+ )
+
+ if isinstance(data_or_path, str):
+ # path to a file?
+ path = pathlib.Path(data_or_path)
+ extension = path.suffix.split(".")[-1]
+ if extension not in Molecule.SUPPORTED_RDKIT_TYPES:
+ raise ValueError(
+ "Molecule.from_rdkit only supports files of the type: "
+ + ", ".join(Molecule.SUPPORTED_RDKIT_TYPES)
+ )
+ # use the appropriate method
+ if extension == "sdf":
+ with rdkit_chem.SDMolSupplier(data_or_path) as supplier:
+ molecule = next(supplier) # get only the first molecule
+ else:
+ molecule = getattr(rdkit_chem, f"MolFrom{extension.capitalize()}File")(
+ data_or_path
+ )
+ elif isinstance(data_or_path, rdkit_chem.rdchem.Mol):
+ molecule = data_or_path
+ else:
+ raise TypeError("Data must be file name or an rdkit.Chem.rdchem.Mol object")
+
+ if convert_to_3d_and_optimize:
+ molecule = rdkit_chem.AddHs(molecule)
+ rdkit_chem_all_chem.EmbedMolecule(molecule)
+ rdkit_chem_all_chem.MMFFOptimizeMolecule(
+ molecule,
+ maxIters=mmff_optimize_molecule_max_iterations,
+ )
+ # convert to the pdb format supported by Molecule
+ pdb_block = rdkit_chem.rdmolfiles.MolToPDBBlock(molecule)
+
+ return cls(io.StringIO(pdb_block), caption=caption, file_type="pdb")
+
+ @classmethod
+ def from_smiles(
+ cls,
+ data: str,
+ caption: Optional[str] = None,
+ sanitize: bool = True,
+ convert_to_3d_and_optimize: bool = True,
+ mmff_optimize_molecule_max_iterations: int = 200,
+ ) -> "Molecule":
+ """Convert SMILES string to wandb.Molecule.
+
+ Args:
+ data: SMILES string.
+ caption: Caption associated with the molecule for display.
+ sanitize: Check if the molecule is chemically reasonable by
+ the RDKit's definition.
+ convert_to_3d_and_optimize: Convert to rdkit.Chem.rdchem.Mol
+ with 3D coordinates. This is a computationally intensive
+ operation that may take a long time for complicated molecules.
+ mmff_optimize_molecule_max_iterations: Number of iterations to
+ use in rdkit.Chem.AllChem.MMFFOptimizeMolecule.
+
+
+ """
+ rdkit_chem = util.get_module(
+ "rdkit.Chem",
+ required='wandb.Molecule needs the rdkit-pypi package. To get it, run "pip install rdkit-pypi".',
+ )
+ molecule = rdkit_chem.MolFromSmiles(data, sanitize=sanitize)
+ if molecule is None:
+ raise ValueError("Unable to parse the SMILES string.")
+
+ return cls.from_rdkit(
+ data_or_path=molecule,
+ caption=caption,
+ convert_to_3d_and_optimize=convert_to_3d_and_optimize,
+ mmff_optimize_molecule_max_iterations=mmff_optimize_molecule_max_iterations,
+ )
+
+ @classmethod
+ def get_media_subdir(cls: Type["Molecule"]) -> str:
+ """Get media subdirectory.
+
+
+ """
+ return os.path.join("media", "molecule")
+
+ def to_json(self, run_or_artifact: Union["LocalRun", "Artifact"]) -> dict:
+ """Returns the JSON representation expected by the backend.
+
+
+ """
+ json_dict = super().to_json(run_or_artifact)
+ json_dict["_type"] = self._log_type
+ return json_dict
+
+ @classmethod
+ def seq_to_json(
+ cls: Type["Molecule"],
+ seq: Sequence["BatchableMedia"],
+ run: "LocalRun",
+ key: str,
+ step: Union[int, str],
+ ) -> dict:
+ """Convert a sequence of Molecule objects to a JSON representation.
+
+
+ """
+ seq = list(seq)
+
+ jsons = [obj.to_json(run) for obj in seq]
+
+ for obj in jsons:
+ expected = LogicalPath(cls.get_media_subdir())
+ if not obj["path"].startswith(expected):
+ raise ValueError(
+ "Files in an array of Molecule's must be in the {} directory, not {}".format(
+ cls.get_media_subdir(), obj["path"]
+ )
+ )
+
+ return {
+ "_type": "molecule",
+ "filenames": [obj["path"] for obj in jsons],
+ "count": len(jsons),
+ "captions": Media.captions(seq),
+ }
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/object_3d.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/object_3d.py
new file mode 100644
index 0000000000000000000000000000000000000000..4924a861793ec3db9fbbe9f8d0e2901807a06110
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/object_3d.py
@@ -0,0 +1,560 @@
+import codecs
+import itertools
+import json
+import os
+import pathlib
+from typing import (
+ TYPE_CHECKING,
+ ClassVar,
+ Literal,
+ Optional,
+ Sequence,
+ Set,
+ TextIO,
+ Tuple,
+ Type,
+ TypedDict,
+ Union,
+)
+
+import wandb
+from wandb import util
+from wandb.sdk.lib import runid
+from wandb.sdk.lib.paths import LogicalPath
+
+from . import _dtypes
+from ._private import MEDIA_TMP
+from .base_types.media import BatchableMedia
+
+if TYPE_CHECKING: # pragma: no cover
+ import numpy as np
+ import numpy.typing as npt
+
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ from ..wandb_run import Run as LocalRun
+
+ numeric = Union[int, float, np.integer, np.float64]
+ FileFormat3D = Literal[
+ "obj",
+ "gltf",
+ "glb",
+ "babylon",
+ "stl",
+ "pts.json",
+ ]
+ Point3D = Tuple[numeric, numeric, numeric]
+ Point3DWithCategory = Tuple[numeric, numeric, numeric, numeric]
+ Point3DWithColors = Tuple[numeric, numeric, numeric, numeric, numeric, numeric]
+ Point = Union[Point3D, Point3DWithCategory, Point3DWithColors]
+ PointCloudType = Literal["lidar/beta"]
+ RGBColor = Tuple[numeric, numeric, numeric]
+
+ Quaternion = Tuple[numeric, numeric, numeric, numeric]
+
+ class Box3D(TypedDict):
+ corners: Tuple[
+ Point3D,
+ Point3D,
+ Point3D,
+ Point3D,
+ Point3D,
+ Point3D,
+ Point3D,
+ Point3D,
+ ]
+ label: Optional[str]
+ color: RGBColor
+ score: Optional[numeric]
+
+ class Vector3D(TypedDict):
+ start: Sequence[Point3D]
+ end: Sequence[Point3D]
+
+ class Camera(TypedDict):
+ viewpoint: Sequence[Point3D]
+ target: Sequence[Point3D]
+
+
+def _install_numpy_error() -> "wandb.Error":
+ return wandb.Error(
+ "wandb.Object3D requires NumPy. To get it, run 'pip install numpy'."
+ )
+
+
+def _normalize_vec(x: "np.ndarray") -> "np.ndarray":
+ """Normalizes a non-zero 1-dimensional array."""
+ try:
+ import numpy as np
+ except ImportError as e:
+ raise _install_numpy_error() from e
+
+ x = abs(x)
+ argmax = x.argmax()
+
+ if x[argmax] == 0:
+ raise ValueError("Unexpected zero quaternion.")
+
+ # Rescale by the largest component first to be more numerically
+ # stable than dividing by the norm directly.
+ x = x / x[argmax]
+ return x / np.linalg.norm(x)
+
+
+def _quaternion_to_rotation(quaternion: "np.ndarray") -> "np.ndarray":
+ """Returns the rotation matrix corresponding to a non-zero quaternion.
+
+ The corresponding rotation matrix transforms column vectors by
+ post-multiplication: `x @ R`. This way, it can be used to
+ transform an Nx3 NumPy array of points as `points @ R`.
+ """
+ try:
+ import numpy as np
+ except ImportError as e:
+ raise _install_numpy_error() from e
+
+ # Precompute a few products to simplify the expression below.
+ qr, qi, qj, qk = _normalize_vec(quaternion)
+ qii, qjj, qkk = qi**2, qj**2, qk**2
+ qij, qik, qjk = qi * qj, qi * qk, qj * qk
+ qir, qjr, qkr = qi * qr, qj * qr, qk * qr
+
+ return np.array(
+ (
+ (1 - 2 * (qjj + qkk), 2 * (qij + qkr), 2 * (qik - qjr)),
+ (2 * (qij - qkr), 1 - 2 * (qii + qkk), 2 * (qjk + qir)),
+ (2 * (qik + qjr), 2 * (qjk - qir), 1 - 2 * (qii + qjj)),
+ ),
+ dtype=np.float64,
+ )
+
+
+def box3d(
+ *,
+ center: "npt.ArrayLike",
+ size: "npt.ArrayLike",
+ orientation: "npt.ArrayLike",
+ color: "RGBColor",
+ label: "Optional[str]" = None,
+ score: "Optional[numeric]" = None,
+) -> "Box3D":
+ """A 3D bounding box. The box is specified by its center, size and orientation.
+
+ Args:
+ center: The center point of the box as a length-3 ndarray.
+ size: The box's X, Y and Z dimensions as a length-3 ndarray.
+ orientation: The rotation transforming global XYZ coordinates
+ into the box's local XYZ coordinates, given as a length-4
+ ndarray [r, x, y, z] corresponding to the non-zero quaternion
+ r + xi + yj + zk.
+ color: The box's color as an (r, g, b) tuple with 0 <= r,g,b <= 1.
+ label: An optional label for the box.
+ score: An optional score for the box. Typically used to indicate
+ the confidence of a detection.
+
+ Returns:
+ A Box3D object.
+
+ Example:
+ The following example creates a point cloud with 60 boxes rotating
+ around the X, Y and Z axes.
+
+ ```python
+ import wandb
+
+ import math
+ import numpy as np
+ from scipy.spatial.transform import Rotation
+
+
+ with wandb.init() as run:
+ run.log(
+ {
+ "points": wandb.Object3D.from_point_cloud(
+ points=np.random.uniform(-5, 5, size=(100, 3)),
+ boxes=[
+ wandb.box3d(
+ center=(0.3 * t - 3, 0, 0),
+ size=(0.1, 0.1, 0.1),
+ orientation=Rotation.from_euler(
+ "xyz", [t * math.pi / 10, 0, 0]
+ ).as_quat(),
+ color=(0.5 + t / 40, 0.5, 0.5),
+ label=f"box {t}",
+ score=0.9,
+ )
+ for t in range(20)
+ ]
+ + [
+ wandb.box3d(
+ center=(0, 0.3 * t - 3, 0.3),
+ size=(0.1, 0.1, 0.1),
+ orientation=Rotation.from_euler(
+ "xyz", [0, t * math.pi / 10, 0]
+ ).as_quat(),
+ color=(0.5, 0.5 + t / 40, 0.5),
+ label=f"box {t}",
+ score=0.9,
+ )
+ for t in range(20)
+ ]
+ + [
+ wandb.box3d(
+ center=(0.3, 0.3, 0.3 * t - 3),
+ size=(0.1, 0.1, 0.1),
+ orientation=Rotation.from_euler(
+ "xyz", [0, 0, t * math.pi / 10]
+ ).as_quat(),
+ color=(0.5, 0.5, 0.5 + t / 40),
+ label=f"box {t}",
+ score=0.9,
+ )
+ for t in range(20)
+ ],
+ ),
+ }
+ )
+ ```
+ """
+ try:
+ import numpy as np
+ except ImportError as e:
+ raise _install_numpy_error() from e
+
+ center = np.asarray(center, dtype=np.float64)
+ size = np.asarray(size, dtype=np.float64)
+ orientation = np.asarray(orientation, dtype=np.float64)
+
+ assert center.shape == (3,)
+ assert size.shape == (3,)
+ assert orientation.shape == (4,)
+
+ # Precompute the rotation matrix.
+ rot = _quaternion_to_rotation(orientation)
+
+ # Scale, rotate and translate each corner of the unit box.
+ unit_corners = np.array(
+ list(itertools.product((-1, 1), (-1, 1), (-1, 1))),
+ dtype=np.float64,
+ )
+ corners = center + (0.5 * size * unit_corners) @ rot
+
+ return {
+ # Ignore the type because mypy can't infer that the list has length 8:
+ # https://github.com/python/mypy/issues/7509
+ "corners": tuple(tuple(pt) for pt in corners), # type: ignore
+ "color": color,
+ "label": label,
+ "score": score,
+ }
+
+
+class Object3D(BatchableMedia):
+ """W&B class for 3D point clouds."""
+
+ SUPPORTED_TYPES: ClassVar[Set[str]] = {
+ "obj",
+ "gltf",
+ "glb",
+ "babylon",
+ "stl",
+ "pts.json",
+ }
+ SUPPORTED_POINT_CLOUD_TYPES: ClassVar[Set[str]] = {"lidar/beta"}
+ _log_type: ClassVar[str] = "object3D-file"
+
+ def __init__(
+ self,
+ data_or_path: Union["np.ndarray", str, pathlib.Path, "TextIO", dict],
+ caption: Optional[str] = None,
+ **kwargs: Optional[Union[str, "FileFormat3D"]],
+ ) -> None:
+ """Creates a W&B Object3D object.
+
+ Args:
+ data_or_path: Object3D can be initialized from a file or a numpy array.
+ caption: Caption associated with the object for display.
+
+ Examples:
+ The shape of the numpy array must be one of either
+
+ ```text
+ [[x y z], ...] nx3
+ [[x y z c], ...] nx4 where c is a category with supported range [1, 14]
+ [[x y z r g b], ...] nx6 where is rgb is color
+ ```
+ """
+ super().__init__(caption=caption)
+
+ if hasattr(data_or_path, "name") and not isinstance(data_or_path, pathlib.Path):
+ # if the file has a path, we just detect the type and copy it from there.
+ # this does not work for pathlib.Path objects,
+ # where `.name` returns the last directory in the path.
+ data_or_path = data_or_path.name
+
+ if hasattr(data_or_path, "read"):
+ if hasattr(data_or_path, "seek"):
+ data_or_path.seek(0)
+ object_3d = data_or_path.read()
+
+ extension = kwargs.pop("file_type", None)
+ if extension is None:
+ raise ValueError(
+ "Must pass file type keyword argument when using io objects."
+ )
+ if extension not in Object3D.SUPPORTED_TYPES:
+ raise ValueError(
+ "Object 3D only supports numpy arrays or files of the type: "
+ + ", ".join(Object3D.SUPPORTED_TYPES)
+ )
+
+ extension = "." + extension
+
+ tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + extension)
+ with open(tmp_path, "w") as f:
+ f.write(object_3d)
+
+ self._set_file(tmp_path, is_tmp=True, extension=extension)
+ elif isinstance(data_or_path, (str, pathlib.Path)):
+ data_or_path = str(data_or_path)
+
+ path = data_or_path
+ extension = None
+ for supported_type in Object3D.SUPPORTED_TYPES:
+ if path.endswith(supported_type):
+ extension = "." + supported_type
+ break
+
+ if not extension:
+ raise ValueError(
+ "File '"
+ + path
+ + "' is not compatible with Object3D: supported types are: "
+ + ", ".join(Object3D.SUPPORTED_TYPES)
+ )
+
+ self._set_file(data_or_path, is_tmp=False, extension=extension)
+ # Supported different types and scene for 3D scenes
+ elif isinstance(data_or_path, dict) and "type" in data_or_path:
+ if data_or_path["type"] == "lidar/beta":
+ data = {
+ "type": data_or_path["type"],
+ "vectors": data_or_path["vectors"].tolist()
+ if "vectors" in data_or_path
+ else [],
+ "points": data_or_path["points"].tolist()
+ if "points" in data_or_path
+ else [],
+ "boxes": data_or_path["boxes"].tolist()
+ if "boxes" in data_or_path
+ else [],
+ }
+ else:
+ raise ValueError(
+ "Type not supported, only 'lidar/beta' is currently supported"
+ )
+
+ tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ".pts.json")
+ with codecs.open(tmp_path, "w", encoding="utf-8") as fp:
+ json.dump(
+ data,
+ fp,
+ separators=(",", ":"),
+ sort_keys=True,
+ indent=4,
+ )
+ self._set_file(tmp_path, is_tmp=True, extension=".pts.json")
+ elif util.is_numpy_array(data_or_path):
+ np_data = data_or_path
+
+ # The following assertion is required for numpy to trust that
+ # np_data is numpy array. The reason it is behind a False
+ # guard is to ensure that this line does not run at runtime,
+ # which would cause a runtime error if the user's machine did
+ # not have numpy installed.
+
+ if TYPE_CHECKING:
+ assert isinstance(np_data, np.ndarray)
+
+ if len(np_data.shape) != 2 or np_data.shape[1] not in {3, 4, 6}:
+ raise ValueError(
+ """
+ The shape of the numpy array must be one of either
+ [[x y z], ...] nx3
+ [x y z c], ...] nx4 where c is a category with supported range [1, 14]
+ [x y z r g b], ...] nx6 where rgb is color
+ """
+ )
+
+ list_data = np_data.tolist()
+ tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ".pts.json")
+ with codecs.open(tmp_path, "w", encoding="utf-8") as fp:
+ json.dump(
+ list_data,
+ fp,
+ separators=(",", ":"),
+ sort_keys=True,
+ indent=4,
+ )
+ self._set_file(tmp_path, is_tmp=True, extension=".pts.json")
+ else:
+ raise ValueError("data must be a numpy array, dict or a file object")
+
+ @classmethod
+ def from_file(
+ cls,
+ data_or_path: Union["TextIO", str],
+ file_type: Optional["FileFormat3D"] = None,
+ ) -> "Object3D":
+ """Initializes Object3D from a file or stream.
+
+ Args:
+ data_or_path (Union["TextIO", str]): A path to a file or a `TextIO` stream.
+ file_type (str): Specifies the data format passed to `data_or_path`. Required when `data_or_path` is a
+ `TextIO` stream. This parameter is ignored if a file path is provided. The type is taken from the file extension.
+
+
+ """
+ # if file_type is not None and file_type not in cls.SUPPORTED_TYPES:
+ # raise ValueError(
+ # f"Unsupported file type: {file_type}. Supported types are: {cls.SUPPORTED_TYPES}"
+ # )
+ return cls(data_or_path, file_type=file_type)
+
+ @classmethod
+ def from_numpy(cls, data: "np.ndarray") -> "Object3D":
+ """Initializes Object3D from a numpy array.
+
+ Args:
+ data (numpy array): Each entry in the array will
+ represent one point in the point cloud.
+
+
+ The shape of the numpy array must be one of either:
+
+ ```text
+ [[x y z], ...] # nx3.
+ [[x y z c], ...] # nx4 where c is a category with supported range [1, 14].
+ [[x y z r g b], ...] # nx6 where is rgb is color.
+ ```
+
+
+ """
+ if not util.is_numpy_array(data):
+ raise ValueError("`data` must be a numpy array")
+
+ if len(data.shape) != 2 or data.shape[1] not in {3, 4, 6}:
+ raise ValueError(
+ """
+ The shape of the numpy array must be one of either:
+ [[x y z], ...] nx3
+ [x y z c], ...] nx4 where c is a category with supported range [1, 14]
+ [x y z r g b], ...] nx6 where rgb is color
+ """
+ )
+
+ return cls(data)
+
+ @classmethod
+ def from_point_cloud(
+ cls,
+ points: Sequence["Point"],
+ boxes: Sequence["Box3D"],
+ vectors: Optional[Sequence["Vector3D"]] = None,
+ point_cloud_type: "PointCloudType" = "lidar/beta",
+ # camera: Optional[Camera] = None,
+ ) -> "Object3D":
+ """Initializes Object3D from a python object.
+
+ Args:
+ points (Sequence["Point"]): The points in the point cloud.
+ boxes (Sequence["Box3D"]): 3D bounding boxes for labeling the point cloud. Boxes
+ are displayed in point cloud visualizations.
+ vectors (Optional[Sequence["Vector3D"]]): Each vector is displayed in the point cloud
+ visualization. Can be used to indicate directionality of bounding boxes. Defaults to None.
+ point_cloud_type ("lidar/beta"): At this time, only the "lidar/beta" type is supported. Defaults to "lidar/beta".
+
+
+ """
+ if point_cloud_type not in cls.SUPPORTED_POINT_CLOUD_TYPES:
+ raise ValueError("Point cloud type not supported")
+
+ numpy = wandb.util.get_module(
+ "numpy",
+ required="wandb.Object3D.from_point_cloud requires numpy. Install with `pip install numpy`",
+ )
+
+ data = {
+ "type": point_cloud_type,
+ "points": numpy.array(points),
+ "boxes": numpy.array(boxes),
+ "vectors": numpy.array(vectors) if vectors is not None else numpy.array([]),
+ }
+
+ return cls(data)
+
+ @classmethod
+ def get_media_subdir(cls: Type["Object3D"]) -> str:
+ """Get media subdirectory.
+
+
+ """
+ return os.path.join("media", "object3D")
+
+ def to_json(self, run_or_artifact: Union["LocalRun", "Artifact"]) -> dict:
+ """Returns the JSON representation expected by the backend.
+
+
+ """
+ json_dict = super().to_json(run_or_artifact)
+ json_dict["_type"] = Object3D._log_type
+
+ if isinstance(run_or_artifact, wandb.Artifact):
+ if self._path is None or not self._path.endswith(".pts.json"):
+ raise ValueError(
+ "Non-point cloud 3D objects are not yet supported with Artifacts"
+ )
+
+ return json_dict
+
+ @classmethod
+ def seq_to_json(
+ cls: Type["Object3D"],
+ seq: Sequence["BatchableMedia"],
+ run: "LocalRun",
+ key: str,
+ step: Union[int, str],
+ ) -> dict:
+ """Convert a sequence of Audio objects to a JSON representation.
+
+
+ """
+ seq = list(seq)
+
+ jsons = [obj.to_json(run) for obj in seq]
+
+ for obj in jsons:
+ expected = LogicalPath(cls.get_media_subdir())
+ if not obj["path"].startswith(expected):
+ raise ValueError(
+ "Files in an array of Object3D's must be in the {} directory, not {}".format(
+ expected, obj["path"]
+ )
+ )
+
+ return {
+ "_type": "object3D",
+ "filenames": [
+ os.path.relpath(j["path"], cls.get_media_subdir()) for j in jsons
+ ],
+ "count": len(jsons),
+ "objects": jsons,
+ }
+
+
+class _Object3DFileType(_dtypes.Type):
+ name = "object3D-file"
+ types = [Object3D]
+
+
+_dtypes.TypeRegistry.add(_Object3DFileType)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/plotly.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/plotly.py
new file mode 100644
index 0000000000000000000000000000000000000000..b07ce7c72225bd26da53f9989a03d1d66209a090
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/plotly.py
@@ -0,0 +1,95 @@
+import codecs
+import os
+from typing import TYPE_CHECKING, Sequence, Type, Union
+
+from wandb import util
+from wandb.sdk.lib import runid
+
+from ._private import MEDIA_TMP
+from .base_types.media import Media, _numpy_arrays_to_lists
+from .base_types.wb_value import WBValue
+from .image import Image
+
+if TYPE_CHECKING: # pragma: no cover
+ import matplotlib # type: ignore
+ import pandas as pd
+ import plotly # type: ignore
+
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ from ..wandb_run import Run as LocalRun
+
+ ValToJsonType = Union[
+ dict,
+ "WBValue",
+ Sequence["WBValue"],
+ "plotly.Figure",
+ "matplotlib.artist.Artist",
+ "pd.DataFrame",
+ object,
+ ]
+
+
+class Plotly(Media):
+ """W&B class for Plotly plots."""
+
+ _log_type = "plotly-file"
+
+ @classmethod
+ def make_plot_media(
+ cls: Type["Plotly"], val: Union["plotly.Figure", "matplotlib.artist.Artist"]
+ ) -> Union[Image, "Plotly"]:
+ """Create a Plotly object from a Plotly figure or a matplotlib artist.
+
+
+ """
+ if util.is_matplotlib_typename(util.get_full_typename(val)):
+ if util.matplotlib_contains_images(val):
+ return Image(val)
+ val = util.matplotlib_to_plotly(val)
+ return cls(val)
+
+ def __init__(self, val: Union["plotly.Figure", "matplotlib.artist.Artist"]):
+ """Initialize a Plotly object.
+
+ Args:
+ val: Matplotlib or Plotly figure.
+ """
+ super().__init__()
+ # First, check to see if the incoming `val` object is a plotfly figure
+ if not util.is_plotly_figure_typename(util.get_full_typename(val)):
+ # If it is not, but it is a matplotlib figure, then attempt to convert it to plotly
+ if util.is_matplotlib_typename(util.get_full_typename(val)):
+ if util.matplotlib_contains_images(val):
+ raise ValueError(
+ "Plotly does not currently support converting matplotlib figures containing images. \
+ You can convert the plot to a static image with `wandb.Image(plt)` "
+ )
+ val = util.matplotlib_to_plotly(val)
+ else:
+ raise ValueError(
+ "Logged plots must be plotly figures, or matplotlib plots convertible to plotly via mpl_to_plotly"
+ )
+
+ tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ".plotly.json")
+ val = _numpy_arrays_to_lists(val.to_plotly_json())
+ with codecs.open(tmp_path, "w", encoding="utf-8") as fp:
+ util.json_dump_safer(val, fp)
+ self._set_file(tmp_path, is_tmp=True, extension=".plotly.json")
+
+ @classmethod
+ def get_media_subdir(cls: Type["Plotly"]) -> str:
+ """Returns the media subdirectory for Plotly plots.
+
+
+ """
+ return os.path.join("media", "plotly")
+
+ def to_json(self, run_or_artifact: Union["LocalRun", "Artifact"]) -> dict:
+ """Convert the Plotly object to a JSON representation.
+
+
+ """
+ json_dict = super().to_json(run_or_artifact)
+ json_dict["_type"] = self._log_type
+ return json_dict
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/saved_model.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/saved_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3f9c894c833c17029b25a82e46ec8b15d2c6f4a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/saved_model.py
@@ -0,0 +1,435 @@
+from __future__ import annotations
+
+import os
+import pathlib
+import shutil
+import sys
+from types import ModuleType
+from typing import TYPE_CHECKING, Any, ClassVar, Generic, TypeVar, cast
+
+import wandb
+from wandb import util
+from wandb.sdk.lib import runid
+from wandb.sdk.lib.hashutil import md5_file_hex
+from wandb.sdk.lib.paths import LogicalPath
+
+from ._private import MEDIA_TMP
+from .base_types.wb_value import WBValue
+
+if TYPE_CHECKING:
+ import sklearn # type: ignore
+ import tensorflow # type: ignore
+ import torch # type: ignore
+ from typing_extensions import Self
+
+ from wandb.sdk.artifacts.artifact import Artifact
+
+
+DEBUG_MODE = False
+
+
+def _add_deterministic_dir_to_artifact(
+ artifact: Artifact, dir_name: str, target_dir_root: str
+) -> str:
+ file_paths = []
+ for dirpath, _, filenames in os.walk(dir_name, topdown=True):
+ for fn in filenames:
+ file_paths.append(os.path.join(dirpath, fn))
+ dirname = md5_file_hex(*file_paths)[:20]
+ target_path = LogicalPath(os.path.join(target_dir_root, dirname))
+ artifact.add_dir(dir_name, target_path)
+ return target_path
+
+
+def _load_dir_from_artifact(source_artifact: Artifact, path: str) -> str:
+ dl_path = None
+
+ # Look through the entire manifest to find all of the files in the directory.
+ # Construct the directory path by inspecting the target download location.
+ for p, _ in source_artifact.manifest.entries.items():
+ if p.startswith(path):
+ example_path = source_artifact.get_entry(p).download()
+ if dl_path is None:
+ root = example_path[: -len(p)]
+ dl_path = os.path.join(root, path)
+
+ assert dl_path is not None, f"Could not find directory {path} in artifact"
+
+ return dl_path
+
+
+SavedModelObjType = TypeVar("SavedModelObjType")
+
+
+class _SavedModel(WBValue, Generic[SavedModelObjType]):
+ """Internal W&B Artifact model storage.
+
+ _model_type_id: (str) The id of the SavedModel subclass used to serialize the model.
+ """
+
+ _log_type: ClassVar[str]
+ _path_extension: ClassVar[str]
+
+ _model_obj: SavedModelObjType | None
+ _path: str | None
+ _input_obj_or_path: SavedModelObjType | str | pathlib.Path
+
+ # Public Methods
+ def __init__(
+ self, obj_or_path: SavedModelObjType | str | pathlib.Path, **kwargs: Any
+ ) -> None:
+ super().__init__()
+ if self.__class__ == _SavedModel:
+ raise TypeError(
+ "Cannot instantiate abstract SavedModel class - please use SavedModel.init(...) instead."
+ )
+ self._model_obj = None
+ self._path = None
+ self._input_obj_or_path = obj_or_path
+ input_is_path = isinstance(obj_or_path, (str, pathlib.Path)) and os.path.exists(
+ obj_or_path
+ )
+ if input_is_path:
+ obj_or_path = str(obj_or_path)
+ self._set_obj(self._deserialize(obj_or_path))
+ else:
+ self._set_obj(obj_or_path)
+
+ self._copy_to_disk()
+ # At this point, the model will be saved to a temp path,
+ # and self._path will be set to such temp path. If the model
+ # provided was a path, then both self._path and self._model_obj
+ # are copies of the user-provided data. However, if the input
+ # was a model object, then we want to clear the model object. The first
+ # accessing of the model object (via .model_obj()) will load the model
+ # from the temp path.
+
+ if not input_is_path:
+ self._unset_obj()
+
+ @staticmethod
+ def init(obj_or_path: Any, **kwargs: Any) -> _SavedModel:
+ maybe_instance = _SavedModel._maybe_init(obj_or_path, **kwargs)
+ if maybe_instance is None:
+ raise ValueError(
+ f"No suitable SavedModel subclass constructor found for obj_or_path: {obj_or_path}"
+ )
+ return maybe_instance
+
+ @classmethod
+ def from_json(
+ cls: type[_SavedModel], json_obj: dict, source_artifact: Artifact
+ ) -> _SavedModel:
+ path = json_obj["path"]
+
+ # First, if the entry is a file, the download it.
+ entry = source_artifact.manifest.entries.get(path)
+ if entry is not None:
+ dl_path = str(source_artifact.get_entry(path).download())
+ else:
+ # If not, assume it is directory.
+ # FUTURE: Add this functionality to the artifact loader
+ # (would be nice to parallelize)
+ dl_path = _load_dir_from_artifact(source_artifact, path)
+
+ # Return the SavedModel object instantiated with the downloaded path
+ # and specified adapter.
+ return cls(dl_path)
+
+ def to_json(self, run_or_artifact: wandb.Run | Artifact) -> dict:
+ # Unlike other data types, we do not allow adding to a Run directly. There is a
+ # bit of tech debt in the other data types which requires the input to `to_json`
+ # to accept a Run or Artifact. However, Run additions should be deprecated in the future.
+ # This check helps ensure we do not add to the debt.
+ if isinstance(run_or_artifact, wandb.Run):
+ raise TypeError("SavedModel cannot be added to run - must use artifact")
+
+ artifact = run_or_artifact
+ json_obj = {
+ "type": self._log_type,
+ }
+ assert self._path is not None, "Cannot add SavedModel to Artifact without path"
+ if os.path.isfile(self._path):
+ # If the path is a file, then we can just add it to the artifact,
+ # First checking to see if the artifact already has the file (use the cache)
+ # Else, add it directly, allowing the artifact adder to rename the file deterministically.
+ already_added_path = artifact.get_added_local_path_name(self._path)
+ if already_added_path is not None:
+ json_obj["path"] = already_added_path
+ else:
+ target_path = os.path.join(
+ ".wb_data", "saved_models", os.path.basename(self._path)
+ )
+ json_obj["path"] = artifact.add_file(self._path, target_path, True).path
+ elif os.path.isdir(self._path):
+ # If the path is a directory, then we need to add all of the files
+ # The directory must be named deterministically based on the contents of the directory,
+ # but the files themselves need to have their name preserved.
+ # FUTURE: Add this functionality to the artifact adder itself
+ json_obj["path"] = _add_deterministic_dir_to_artifact(
+ artifact, self._path, os.path.join(".wb_data", "saved_models")
+ )
+ else:
+ raise ValueError(
+ f"Expected a path to a file or directory, got {self._path}"
+ )
+
+ return json_obj
+
+ def model_obj(self) -> SavedModelObjType:
+ """Return the model object."""
+ if self._model_obj is None:
+ assert self._path is not None, "Cannot load model object without path"
+ self._set_obj(self._deserialize(self._path))
+
+ assert self._model_obj is not None, "Model object is None"
+ return self._model_obj
+
+ # Methods to be implemented by subclasses
+ @staticmethod
+ def _deserialize(path: str) -> SavedModelObjType:
+ """Return the model object from a path. Allowed to throw errors."""
+ raise NotImplementedError
+
+ @staticmethod
+ def _validate_obj(obj: Any) -> bool:
+ """Validate the model object. Allowed to throw errors."""
+ raise NotImplementedError
+
+ @staticmethod
+ def _serialize(obj: SavedModelObjType, dir_or_file_path: str) -> None:
+ """Save the model to disk.
+
+ The method will receive a directory path which all files needed for
+ deserialization should be saved. A directory will always be passed if
+ _path_extension is an empty string, else a single file will be passed. Allowed
+ to throw errors.
+ """
+ raise NotImplementedError
+
+ # Private Class Methods
+ @classmethod
+ def _maybe_init(
+ cls: type[_SavedModel], obj_or_path: Any, **kwargs: Any
+ ) -> _SavedModel | None:
+ # _maybe_init is an exception-safe method that will return an instance of this class
+ # (or any subclass of this class - recursively) OR None if no subclass constructor is found.
+ # We first try the current class, then recursively call this method on children classes. This pattern
+ # conforms to the new "Weave-type" pattern developed by Shawn. This way, we can for example have a
+ # pytorch subclass that can itself have two subclasses: one for a TorchScript model, and one for a PyTorch model.
+ # The children subclasses will know how to serialize/deserialize their respective payloads, but the pytorch
+ # parent class can know how to execute inference on the model - regardless of serialization strategy.
+ try:
+ return cls(obj_or_path, **kwargs)
+ except Exception as e:
+ if DEBUG_MODE:
+ print(f"{cls}._maybe_init({obj_or_path}) failed: {e}") # noqa: T201
+
+ for child_cls in cls.__subclasses__():
+ maybe_instance = child_cls._maybe_init(obj_or_path, **kwargs)
+ if maybe_instance is not None:
+ return maybe_instance
+
+ return None
+
+ @classmethod
+ def _tmp_path(cls: type[_SavedModel]) -> str:
+ # Generates a tmp path under our MEDIA_TMP directory which confirms to the file
+ # or folder preferences of the class.
+ assert isinstance(cls._path_extension, str), "_path_extension must be a string"
+ tmp_path = os.path.abspath(os.path.join(MEDIA_TMP.name, runid.generate_id()))
+ if cls._path_extension != "":
+ tmp_path += "." + cls._path_extension
+ return tmp_path
+
+ # Private Instance Methods
+ def _copy_to_disk(self) -> None:
+ # Creates a temporary path and writes a fresh copy of the
+ # model to disk - updating the _path appropriately.
+ tmp_path = self._tmp_path()
+ self._dump(tmp_path)
+ self._path = tmp_path
+
+ def _unset_obj(self) -> None:
+ assert self._path is not None, "Cannot unset object if path is None"
+ self._model_obj = None
+
+ def _set_obj(self, model_obj: Any) -> None:
+ assert model_obj is not None and self._validate_obj(model_obj), (
+ f"Invalid model object {model_obj}"
+ )
+ self._model_obj = model_obj
+
+ def _dump(self, target_path: str) -> None:
+ assert self._model_obj is not None, "Cannot dump if model object is None"
+ self._serialize(self._model_obj, target_path)
+
+
+def _get_cloudpickle() -> ModuleType:
+ return cast(
+ ModuleType,
+ util.get_module("cloudpickle", "ModelAdapter requires `cloudpickle`"),
+ )
+
+
+# TODO: Add pip deps
+# TODO: potentially move this up to the saved model class
+PicklingSavedModelObjType = TypeVar("PicklingSavedModelObjType")
+
+
+class _PicklingSavedModel(_SavedModel[SavedModelObjType]):
+ _dep_py_files: list[str] | None = None
+ _dep_py_files_path: str | None = None
+
+ def __init__(
+ self,
+ obj_or_path: SavedModelObjType | str | pathlib.Path,
+ dep_py_files: list[str] | None = None,
+ ):
+ super().__init__(obj_or_path)
+ if self.__class__ == _PicklingSavedModel:
+ raise TypeError(
+ "Cannot instantiate abstract _PicklingSavedModel class - please use SavedModel.init(...) instead."
+ )
+ if dep_py_files is not None and len(dep_py_files) > 0:
+ self._dep_py_files = dep_py_files
+ self._dep_py_files_path = os.path.abspath(
+ os.path.join(MEDIA_TMP.name, runid.generate_id())
+ )
+ os.makedirs(self._dep_py_files_path, exist_ok=True)
+ for extra_file in self._dep_py_files:
+ if os.path.isfile(extra_file):
+ shutil.copy(extra_file, self._dep_py_files_path)
+ elif os.path.isdir(extra_file):
+ shutil.copytree(
+ extra_file,
+ os.path.join(
+ self._dep_py_files_path, os.path.basename(extra_file)
+ ),
+ )
+ else:
+ raise ValueError(f"Invalid dependency file: {extra_file}")
+
+ @classmethod
+ def from_json(cls, json_obj: dict, source_artifact: Artifact) -> Self:
+ backup_path = [p for p in sys.path]
+ if (
+ "dep_py_files_path" in json_obj
+ and json_obj["dep_py_files_path"] is not None
+ ):
+ dl_path = _load_dir_from_artifact(
+ source_artifact, json_obj["dep_py_files_path"]
+ )
+ assert dl_path is not None
+ sys.path.append(dl_path)
+ inst = super().from_json(json_obj, source_artifact) # type: ignore
+ sys.path = backup_path
+
+ return inst # type: ignore
+
+ def to_json(self, run_or_artifact: wandb.Run | Artifact) -> dict:
+ json_obj = super().to_json(run_or_artifact)
+ assert isinstance(run_or_artifact, wandb.Artifact)
+ if self._dep_py_files_path is not None:
+ json_obj["dep_py_files_path"] = _add_deterministic_dir_to_artifact(
+ run_or_artifact,
+ self._dep_py_files_path,
+ os.path.join(".wb_data", "extra_files"),
+ )
+ return json_obj
+
+
+def _get_torch() -> ModuleType:
+ return cast(
+ ModuleType,
+ util.get_module("torch", "ModelAdapter requires `torch`"),
+ )
+
+
+class _PytorchSavedModel(_PicklingSavedModel["torch.nn.Module"]):
+ _log_type = "pytorch-model-file"
+ _path_extension = "pt"
+
+ @staticmethod
+ def _deserialize(dir_or_file_path: str) -> torch.nn.Module:
+ return _get_torch().load(dir_or_file_path, weights_only=False)
+
+ @staticmethod
+ def _validate_obj(obj: Any) -> bool:
+ return isinstance(obj, _get_torch().nn.Module)
+
+ @staticmethod
+ def _serialize(model_obj: torch.nn.Module, dir_or_file_path: str) -> None:
+ _get_torch().save(
+ model_obj,
+ dir_or_file_path,
+ pickle_module=_get_cloudpickle(),
+ )
+
+
+def _get_sklearn() -> ModuleType:
+ return cast(
+ ModuleType,
+ util.get_module("sklearn", "ModelAdapter requires `sklearn`"),
+ )
+
+
+class _SklearnSavedModel(_PicklingSavedModel["sklearn.base.BaseEstimator"]):
+ _log_type = "sklearn-model-file"
+ _path_extension = "pkl"
+
+ @staticmethod
+ def _deserialize(
+ dir_or_file_path: str,
+ ) -> sklearn.base.BaseEstimator:
+ with open(dir_or_file_path, "rb") as file:
+ model = _get_cloudpickle().load(file)
+ return model
+
+ @staticmethod
+ def _validate_obj(obj: Any) -> bool:
+ dynamic_sklearn = _get_sklearn()
+ return cast(
+ bool,
+ (
+ dynamic_sklearn.base.is_classifier(obj)
+ or dynamic_sklearn.base.is_outlier_detector(obj)
+ or dynamic_sklearn.base.is_regressor(obj)
+ ),
+ )
+
+ @staticmethod
+ def _serialize(
+ model_obj: sklearn.base.BaseEstimator, dir_or_file_path: str
+ ) -> None:
+ dynamic_cloudpickle = _get_cloudpickle()
+ with open(dir_or_file_path, "wb") as file:
+ dynamic_cloudpickle.dump(model_obj, file)
+
+
+def _get_tf_keras() -> ModuleType:
+ return cast(
+ ModuleType,
+ util.get_module("tensorflow", "ModelAdapter requires `tensorflow`"),
+ ).keras
+
+
+class _TensorflowKerasSavedModel(_SavedModel["tensorflow.keras.Model"]):
+ _log_type = "tfkeras-model-file"
+ _path_extension = ""
+
+ @staticmethod
+ def _deserialize(
+ dir_or_file_path: str,
+ ) -> tensorflow.keras.Model:
+ return _get_tf_keras().models.load_model(dir_or_file_path)
+
+ @staticmethod
+ def _validate_obj(obj: Any) -> bool:
+ return isinstance(obj, _get_tf_keras().models.Model)
+
+ @staticmethod
+ def _serialize(model_obj: tensorflow.keras.Model, dir_or_file_path: str) -> None:
+ _get_tf_keras().models.save_model(
+ model_obj, dir_or_file_path, include_optimizer=True
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/table.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/table.py
new file mode 100644
index 0000000000000000000000000000000000000000..d2d39e49e667d3f8db4c92d3691d67fc260dc2f1
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/table.py
@@ -0,0 +1,1468 @@
+import base64
+import binascii
+import codecs
+import datetime
+import json
+import logging
+import os
+from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Set, Tuple
+
+import wandb
+from wandb import util
+from wandb.sdk.lib import runid
+
+from . import _dtypes
+from ._private import MEDIA_TMP
+from .base_types.media import Media, _numpy_arrays_to_lists
+from .base_types.wb_value import WBValue
+from .table_decorators import (
+ allow_incremental_logging_after_append,
+ allow_relogging_after_mutation,
+ ensure_not_incremental,
+)
+from .utils import _json_helper
+
+if TYPE_CHECKING:
+ from wandb.sdk.artifacts import artifact
+
+ from ...wandb_run import Run as LocalRun
+
+
+class _TableLinkMixin:
+ def set_table(self, table):
+ self._table = table
+
+
+class _TableKey(str, _TableLinkMixin):
+ def set_table(self, table, col_name):
+ assert col_name in table.columns
+ self._table = table
+ self._col_name = col_name
+
+
+class _TableIndex(int, _TableLinkMixin):
+ def get_row(self):
+ row = {}
+ if self._table:
+ row = {
+ c: self._table.data[self][i] for i, c in enumerate(self._table.columns)
+ }
+
+ return row
+
+
+class _PrimaryKeyType(_dtypes.Type):
+ name = "primaryKey"
+ legacy_names = ["wandb.TablePrimaryKey"]
+
+ def assign_type(self, wb_type=None):
+ if isinstance(wb_type, _dtypes.StringType) or isinstance(
+ wb_type, _PrimaryKeyType
+ ):
+ return self
+ return _dtypes.InvalidType()
+
+ @classmethod
+ def from_obj(cls, py_obj):
+ if not isinstance(py_obj, _TableKey):
+ raise TypeError("py_obj must be a wandb.Table")
+ else:
+ return cls()
+
+
+class _ForeignKeyType(_dtypes.Type):
+ name = "foreignKey"
+ legacy_names = ["wandb.TableForeignKey"]
+ types = [_TableKey]
+
+ def __init__(self, table, col_name):
+ assert isinstance(table, Table)
+ assert isinstance(col_name, str)
+ assert col_name in table.columns
+ self.params.update({"table": table, "col_name": col_name})
+
+ def assign_type(self, wb_type=None):
+ if isinstance(wb_type, _dtypes.StringType):
+ return self
+ elif (
+ isinstance(wb_type, _ForeignKeyType)
+ and id(self.params["table"]) == id(wb_type.params["table"])
+ and self.params["col_name"] == wb_type.params["col_name"]
+ ):
+ return self
+
+ return _dtypes.InvalidType()
+
+ @classmethod
+ def from_obj(cls, py_obj):
+ if not isinstance(py_obj, _TableKey):
+ raise TypeError("py_obj must be a _TableKey")
+ else:
+ return cls(py_obj._table, py_obj._col_name)
+
+ def to_json(self, artifact=None):
+ res = super().to_json(artifact)
+ if artifact is not None:
+ table_name = f"media/tables/t_{runid.generate_id()}"
+ entry = artifact.add(self.params["table"], table_name)
+ res["params"]["table"] = entry.path
+ else:
+ raise AssertionError(
+ "_ForeignKeyType does not support serialization without an artifact"
+ )
+ return res
+
+ @classmethod
+ def from_json(
+ cls,
+ json_dict,
+ artifact,
+ ):
+ table = None
+ col_name = None
+ if artifact is None:
+ raise AssertionError(
+ "_ForeignKeyType does not support deserialization without an artifact"
+ )
+ else:
+ table = artifact.get(json_dict["params"]["table"])
+ col_name = json_dict["params"]["col_name"]
+
+ if table is None:
+ raise AssertionError("Unable to deserialize referenced table")
+
+ return cls(table, col_name)
+
+
+class _ForeignIndexType(_dtypes.Type):
+ name = "foreignIndex"
+ legacy_names = ["wandb.TableForeignIndex"]
+ types = [_TableIndex]
+
+ def __init__(self, table):
+ assert isinstance(table, Table)
+ self.params.update({"table": table})
+
+ def assign_type(self, wb_type=None):
+ if isinstance(wb_type, _dtypes.NumberType):
+ return self
+ elif isinstance(wb_type, _ForeignIndexType) and id(self.params["table"]) == id(
+ wb_type.params["table"]
+ ):
+ return self
+
+ return _dtypes.InvalidType()
+
+ @classmethod
+ def from_obj(cls, py_obj):
+ if not isinstance(py_obj, _TableIndex):
+ raise TypeError("py_obj must be a _TableIndex")
+ else:
+ return cls(py_obj._table)
+
+ def to_json(self, artifact=None):
+ res = super().to_json(artifact)
+ if artifact is not None:
+ table_name = f"media/tables/t_{runid.generate_id()}"
+ entry = artifact.add(self.params["table"], table_name)
+ res["params"]["table"] = entry.path
+ else:
+ raise AssertionError(
+ "_ForeignIndexType does not support serialization without an artifact"
+ )
+ return res
+
+ @classmethod
+ def from_json(
+ cls,
+ json_dict,
+ artifact,
+ ):
+ table = None
+ if artifact is None:
+ raise AssertionError(
+ "_ForeignIndexType does not support deserialization without an artifact"
+ )
+ else:
+ table = artifact.get(json_dict["params"]["table"])
+
+ if table is None:
+ raise AssertionError("Unable to deserialize referenced table")
+
+ return cls(table)
+
+
+_SUPPORTED_LOGGING_MODES = ["IMMUTABLE", "MUTABLE", "INCREMENTAL"]
+
+
+class Table(Media):
+ """The Table class used to display and analyze tabular data.
+
+ Unlike traditional spreadsheets, Tables support numerous types of data:
+ scalar values, strings, numpy arrays, and most subclasses of `wandb.data_types.Media`.
+ This means you can embed `Images`, `Video`, `Audio`, and other sorts of rich, annotated media
+ directly in Tables, alongside other traditional scalar values.
+
+ This class is the primary class used to generate W&B Tables
+ https://docs.wandb.ai/guides/models/tables/.
+ """
+
+ MAX_ROWS = 10000
+ MAX_ARTIFACT_ROWS = 200000
+ _MAX_EMBEDDING_DIMENSIONS = 150
+ _log_type = "table"
+
+ def __init__(
+ self,
+ columns=None,
+ data=None,
+ rows=None,
+ dataframe=None,
+ dtype=None,
+ optional=True,
+ allow_mixed_types=False,
+ log_mode: Optional[
+ Literal["IMMUTABLE", "MUTABLE", "INCREMENTAL"]
+ ] = "IMMUTABLE",
+ ):
+ """Initializes a Table object.
+
+ The rows is available for legacy reasons and should not be used.
+ The Table class uses data to mimic the Pandas API.
+
+ Args:
+ columns: (List[str]) Names of the columns in the table.
+ Defaults to ["Input", "Output", "Expected"].
+ data: (List[List[any]]) 2D row-oriented array of values.
+ dataframe: (pandas.DataFrame) DataFrame object used to create the table.
+ When set, `data` and `columns` arguments are ignored.
+ rows: (List[List[any]]) 2D row-oriented array of values.
+ optional: (Union[bool,List[bool]]) Determines if `None` values are allowed. Default to True
+ - If a singular bool value, then the optionality is enforced for all
+ columns specified at construction time
+ - If a list of bool values, then the optionality is applied to each
+ column - should be the same length as `columns`
+ applies to all columns. A list of bool values applies to each respective column.
+ allow_mixed_types: (bool) Determines if columns are allowed to have mixed types
+ (disables type validation). Defaults to False
+ log_mode: Optional[str] Controls how the Table is logged when mutations occur.
+ Options:
+ - "IMMUTABLE" (default): Table can only be logged once; subsequent
+ logging attempts after the table has been mutated will be no-ops.
+ - "MUTABLE": Table can be re-logged after mutations, creating
+ a new artifact version each time it's logged.
+ - "INCREMENTAL": Table data is logged incrementally, with each log creating
+ a new artifact entry containing the new data since the last log.
+ """
+ super().__init__()
+ self._validate_log_mode(log_mode)
+ self.log_mode = log_mode
+ if self.log_mode == "INCREMENTAL":
+ self._increment_num: int | None = None
+ self._last_logged_idx: int | None = None
+ self._previous_increments_paths: list[str] | None = None
+ self._run_target_for_increments: LocalRun | None = None
+ self._pk_col = None
+ self._fk_cols: set[str] = set()
+ if allow_mixed_types:
+ dtype = _dtypes.AnyType
+
+ # This is kept for legacy reasons (tss: personally, I think we should remove this)
+ if columns is None:
+ columns = ["Input", "Output", "Expected"]
+
+ # Explicit dataframe option
+ if dataframe is not None:
+ self._init_from_dataframe(dataframe, columns, optional, dtype)
+ else:
+ # Expected pattern
+ if data is not None:
+ if util.is_numpy_array(data):
+ self._init_from_ndarray(data, columns, optional, dtype)
+ elif util.is_pandas_data_frame(data):
+ self._init_from_dataframe(data, columns, optional, dtype)
+ else:
+ self._init_from_list(data, columns, optional, dtype)
+
+ # legacy
+ elif rows is not None:
+ self._init_from_list(rows, columns, optional, dtype)
+
+ # Default empty case
+ else:
+ self._init_from_list([], columns, optional, dtype)
+
+ def _validate_log_mode(self, log_mode):
+ assert log_mode in _SUPPORTED_LOGGING_MODES, (
+ f"Invalid log_mode: {log_mode}. Must be one of {_SUPPORTED_LOGGING_MODES}"
+ )
+
+ @staticmethod
+ def _assert_valid_columns(columns):
+ valid_col_types = [str, int]
+ assert isinstance(columns, list), "columns argument expects a `list` object"
+ assert len(columns) == 0 or all(
+ [type(col) in valid_col_types for col in columns]
+ ), "columns argument expects list of strings or ints"
+
+ def _init_from_list(self, data, columns, optional=True, dtype=None):
+ assert isinstance(data, list), "data argument expects a `list` object"
+ self.data = []
+ self._assert_valid_columns(columns)
+ self.columns = columns
+ self._make_column_types(dtype, optional)
+ for row in data:
+ self.add_data(*row)
+
+ def _init_from_ndarray(self, ndarray, columns, optional=True, dtype=None):
+ assert util.is_numpy_array(ndarray), (
+ "ndarray argument expects a `numpy.ndarray` object"
+ )
+ self.data = []
+ self._assert_valid_columns(columns)
+ self.columns = columns
+ self._make_column_types(dtype, optional)
+ for row in ndarray:
+ self.add_data(*row)
+
+ def _init_from_dataframe(self, dataframe, columns, optional=True, dtype=None):
+ assert util.is_pandas_data_frame(dataframe), (
+ "dataframe argument expects a `pandas.core.frame.DataFrame` object"
+ )
+ self.data = []
+ columns = list(dataframe.columns)
+ self._assert_valid_columns(columns)
+ self.columns = columns
+ self._make_column_types(dtype, optional)
+ for row in range(len(dataframe)):
+ self.add_data(*tuple(dataframe[col].values[row] for col in self.columns))
+
+ def _make_column_types(self, dtype=None, optional=True):
+ if dtype is None:
+ dtype = _dtypes.UnknownType()
+
+ if optional.__class__ is not list:
+ optional = [optional for _ in range(len(self.columns))]
+
+ if dtype.__class__ is not list:
+ dtype = [dtype for _ in range(len(self.columns))]
+
+ self._column_types = _dtypes.TypedDictType({})
+ for col_name, opt, dt in zip(self.columns, optional, dtype):
+ self.cast(col_name, dt, opt)
+
+ def _load_incremental_table_state_from_resumed_run(self, run: "LocalRun", key: str):
+ """Handle updating incremental table state for resumed runs.
+
+ This method is called when a run is resumed and there are previous
+ increments of this table that need to be preserved. It updates the
+ table's internal state to track previous increments and the current
+ increment number.
+ """
+ if (
+ self._previous_increments_paths is not None
+ or self._increment_num is not None
+ ):
+ raise AssertionError(
+ "The table has been initialized for a resumed run already"
+ )
+
+ self._set_incremental_table_run_target(run)
+
+ summary_from_key = run.summary.get(key)
+
+ if (
+ summary_from_key is None
+ or not isinstance(summary_from_key, dict)
+ or summary_from_key.get("_type") != "incremental-table-file"
+ ):
+ # The key was never logged to the run or its last logged
+ # value was not an incrementally logged table.
+ return
+
+ previous_increments_paths = summary_from_key.get(
+ "previous_increments_paths", []
+ )
+
+ # add the artifact path of the last logged increment
+ last_artifact_path = summary_from_key.get("artifact_path")
+
+ if last_artifact_path:
+ previous_increments_paths.append(last_artifact_path)
+
+ # add 1 because a new increment is being logged
+ last_increment_num = summary_from_key.get("increment_num", 0)
+
+ self._increment_num = last_increment_num + 1
+ self._previous_increments_paths = previous_increments_paths
+
+ def _set_incremental_table_run_target(self, run: "LocalRun") -> None:
+ """Associate a Run object with this incremental Table.
+
+ A Table object in incremental mode can only be logged to a single Run.
+ Raises an error if the table is already associated to a different run.
+ """
+ if self._run_target_for_increments is None:
+ self._run_target_for_increments = run
+ elif self._run_target_for_increments is not run:
+ raise AssertionError("An incremental Table can only be logged to one Run.")
+
+ @allow_relogging_after_mutation
+ def cast(self, col_name, dtype, optional=False):
+ """Casts a column to a specific data type.
+
+ This can be one of the normal python classes, an internal W&B type,
+ or an example object, like an instance of wandb.Image or
+ wandb.Classes.
+
+ Args:
+ col_name (str): The name of the column to cast.
+ dtype (class, wandb.wandb_sdk.interface._dtypes.Type, any): The
+ target dtype.
+ optional (bool): If the column should allow Nones.
+ """
+ assert col_name in self.columns
+
+ wbtype = _dtypes.TypeRegistry.type_from_dtype(dtype)
+
+ if optional:
+ wbtype = _dtypes.OptionalType(wbtype)
+
+ # Cast each value in the row, raising an error if there are invalid entries.
+ col_ndx = self.columns.index(col_name)
+ for row in self.data:
+ result_type = wbtype.assign(row[col_ndx])
+ if isinstance(result_type, _dtypes.InvalidType):
+ raise TypeError(
+ f"Existing data {row[col_ndx]}, of type {_dtypes.TypeRegistry.type_of(row[col_ndx])} cannot be cast to {wbtype}"
+ )
+ wbtype = result_type
+
+ # Assert valid options
+ is_pk = isinstance(wbtype, _PrimaryKeyType)
+ is_fk = isinstance(wbtype, _ForeignKeyType)
+ is_fi = isinstance(wbtype, _ForeignIndexType)
+ if is_pk or is_fk or is_fi:
+ assert not optional, (
+ "Primary keys, foreign keys, and foreign indexes cannot be optional."
+ )
+
+ if (is_fk or is_fk) and id(wbtype.params["table"]) == id(self):
+ raise AssertionError("Cannot set a foreign table reference to same table.")
+
+ if is_pk:
+ assert self._pk_col is None, (
+ f"Cannot have multiple primary keys - {self._pk_col} is already set as the primary key."
+ )
+
+ # Update the column type
+ self._column_types.params["type_map"][col_name] = wbtype
+
+ # Wrap the data if needed
+ self._update_keys()
+ return wbtype
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+ def _eq_debug(self, other, should_assert=False):
+ eq = isinstance(other, Table)
+ assert not should_assert or eq, (
+ f"Found type {other.__class__}, expected {Table}"
+ )
+ eq = eq and len(self.data) == len(other.data)
+ assert not should_assert or eq, (
+ f"Found {len(other.data)} rows, expected {len(self.data)}"
+ )
+ eq = eq and self.columns == other.columns
+ assert not should_assert or eq, (
+ f"Found columns {other.columns}, expected {self.columns}"
+ )
+ eq = eq and self._column_types == other._column_types
+ assert not should_assert or eq, (
+ f"Found column type {other._column_types}, expected column type {self._column_types}"
+ )
+ if eq:
+ for row_ndx in range(len(self.data)):
+ for col_ndx in range(len(self.data[row_ndx])):
+ _eq = self.data[row_ndx][col_ndx] == other.data[row_ndx][col_ndx]
+ # equal if all are equal
+ if util.is_numpy_array(_eq):
+ _eq = ((_eq * -1) + 1).sum() == 0
+ eq = eq and _eq
+ assert not should_assert or eq, (
+ f"Unequal data at row_ndx {row_ndx} col_ndx {col_ndx}: found {other.data[row_ndx][col_ndx]}, expected {self.data[row_ndx][col_ndx]}"
+ )
+ if not eq:
+ return eq
+ return eq
+
+ def __eq__(self, other):
+ return self._eq_debug(other)
+
+ @allow_relogging_after_mutation
+ def add_row(self, *row):
+ """Deprecated. Use `Table.add_data` method instead."""
+ logging.warning("add_row is deprecated, use add_data")
+ self.add_data(*row)
+
+ @allow_relogging_after_mutation
+ @allow_incremental_logging_after_append
+ def add_data(self, *data):
+ """Adds a new row of data to the table.
+
+ The maximum amount ofrows in a table is determined by
+ `wandb.Table.MAX_ARTIFACT_ROWS`.
+
+ The length of the data should match the length of the table column.
+ """
+ if len(data) != len(self.columns):
+ raise ValueError(
+ f"This table expects {len(self.columns)} columns: {self.columns}, found {len(data)}"
+ )
+
+ # Special case to pre-emptively cast a column as a key.
+ # Needed as String.assign(Key) is invalid
+ for ndx, item in enumerate(data):
+ if isinstance(item, _TableLinkMixin):
+ self.cast(
+ self.columns[ndx],
+ _dtypes.TypeRegistry.type_of(item),
+ optional=False,
+ )
+
+ # Update the table's column types
+ result_type = self._get_updated_result_type(data)
+ self._column_types = result_type
+
+ # rows need to be mutable
+ if isinstance(data, tuple):
+ data = list(data)
+ # Add the new data
+ self.data.append(data)
+
+ # Update the wrapper values if needed
+ self._update_keys(force_last=True)
+
+ def _get_updated_result_type(self, row):
+ """Returns the updated result type based on the inputted row.
+
+ Raises:
+ TypeError: if the assignment is invalid.
+ """
+ incoming_row_dict = {
+ col_key: row[ndx] for ndx, col_key in enumerate(self.columns)
+ }
+ current_type = self._column_types
+ result_type = current_type.assign(incoming_row_dict)
+ if isinstance(result_type, _dtypes.InvalidType):
+ raise TypeError(
+ f"Data row contained incompatible types:\n{current_type.explain(incoming_row_dict)}"
+ )
+ return result_type
+
+ def _to_table_json(self, max_rows=None, warn=True):
+ # separate this method for easier testing
+ if max_rows is None:
+ max_rows = Table.MAX_ROWS
+ n_rows = len(self.data)
+ if n_rows > max_rows and warn:
+ # NOTE: Never raises for reinit="create_new" runs.
+ # Since this is called by bind_to_run(), this can be fixed by
+ # propagating the run. It cannot be fixed for to_json() calls
+ # that are given an artifact, other than by deferring to singleton
+ # settings.
+ if wandb.run and (
+ wandb.run.settings.table_raise_on_max_row_limit_exceeded
+ or wandb.run.settings.strict
+ ):
+ raise ValueError(
+ f"Table row limit exceeded: table has {n_rows} rows, limit is {max_rows}. "
+ f"To increase the maximum number of allowed rows in a wandb.Table, override "
+ f"the limit with `wandb.Table.MAX_ARTIFACT_ROWS = X` and try again. Note: "
+ f"this may cause slower queries in the W&B UI."
+ )
+ logging.warning(f"Truncating wandb.Table object to {max_rows} rows.")
+
+ if self.log_mode == "INCREMENTAL" and self._last_logged_idx is not None:
+ return {
+ "columns": self.columns,
+ "data": self.data[
+ self._last_logged_idx + 1 : self._last_logged_idx + 1 + max_rows
+ ],
+ }
+ else:
+ return {"columns": self.columns, "data": self.data[:max_rows]}
+
+ def bind_to_run(self, *args, **kwargs):
+ """Bind this object to a run.
+
+
+ """
+ # We set `warn=False` since Tables will now always be logged to both
+ # files and artifacts. The file limit will never practically matter and
+ # this code path will be ultimately removed. The 10k limit warning confuses
+ # users given that we publicly say 200k is the limit.
+ data = self._to_table_json(warn=False)
+ tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ".table.json")
+ data = _numpy_arrays_to_lists(data)
+ with codecs.open(tmp_path, "w", encoding="utf-8") as fp:
+ util.json_dump_safer(data, fp)
+ self._set_file(tmp_path, is_tmp=True, extension=".table.json")
+ super().bind_to_run(*args, **kwargs)
+
+ @classmethod
+ def get_media_subdir(cls):
+ """Get media subdirectory.
+
+
+ """
+ return os.path.join("media", "table")
+
+ @classmethod
+ def from_json(cls, json_obj, source_artifact: "artifact.Artifact"):
+ """Deserialize JSON object into it's class representation.
+
+
+ """
+ data = []
+ column_types = None
+ np_deserialized_columns = {}
+ timestamp_column_indices = set()
+ log_mode = json_obj.get("log_mode", "IMMUTABLE")
+ if json_obj.get("column_types") is not None:
+ column_types = _dtypes.TypeRegistry.type_from_dict(
+ json_obj["column_types"], source_artifact
+ )
+ for col_name in column_types.params["type_map"]:
+ col_type = column_types.params["type_map"][col_name]
+ ndarray_type = None
+ if isinstance(col_type, _dtypes.NDArrayType):
+ ndarray_type = col_type
+ elif isinstance(col_type, _dtypes.UnionType):
+ for t in col_type.params["allowed_types"]:
+ if isinstance(t, _dtypes.NDArrayType):
+ ndarray_type = t
+ elif isinstance(t, _dtypes.TimestampType):
+ timestamp_column_indices.add(
+ json_obj["columns"].index(col_name)
+ )
+
+ elif isinstance(col_type, _dtypes.TimestampType):
+ timestamp_column_indices.add(json_obj["columns"].index(col_name))
+
+ if (
+ ndarray_type is not None
+ and ndarray_type._get_serialization_path() is not None
+ ):
+ serialization_path = ndarray_type._get_serialization_path()
+
+ if serialization_path is None:
+ continue
+
+ np = util.get_module(
+ "numpy",
+ required="Deserializing NumPy columns requires NumPy to be installed.",
+ )
+ deserialized = np.load(
+ source_artifact.get_entry(serialization_path["path"]).download()
+ )
+ np_deserialized_columns[json_obj["columns"].index(col_name)] = (
+ deserialized[serialization_path["key"]]
+ )
+ ndarray_type._clear_serialization_path()
+
+ if log_mode == "INCREMENTAL":
+ unprocessed_table_data = _get_data_from_increments(
+ json_obj, source_artifact
+ )
+ else:
+ unprocessed_table_data = json_obj["data"]
+
+ for r_ndx, row in enumerate(unprocessed_table_data):
+ data.append(
+ _process_table_row(
+ row,
+ timestamp_column_indices,
+ np_deserialized_columns,
+ source_artifact,
+ r_ndx,
+ )
+ )
+
+ # construct Table with dtypes for each column if type information exists
+ dtypes = None
+ if column_types is not None:
+ dtypes = [
+ column_types.params["type_map"][str(col)] for col in json_obj["columns"]
+ ]
+
+ new_obj = cls(
+ columns=json_obj["columns"], data=data, dtype=dtypes, log_mode=log_mode
+ )
+
+ if column_types is not None:
+ new_obj._column_types = column_types
+
+ new_obj._update_keys()
+ return new_obj
+
+ def to_json(self, run_or_artifact):
+ """Returns the JSON representation expected by the backend.
+
+
+ """
+ json_dict = super().to_json(run_or_artifact)
+
+ if self.log_mode == "INCREMENTAL":
+ if self._previous_increments_paths is None:
+ self._previous_increments_paths = []
+ if self._increment_num is None:
+ self._increment_num = 0
+
+ json_dict.update(
+ {
+ "increment_num": self._increment_num,
+ "previous_increments_paths": self._previous_increments_paths,
+ }
+ )
+
+ if isinstance(run_or_artifact, wandb.Run):
+ if self.log_mode == "INCREMENTAL":
+ wbvalue_type = "incremental-table-file"
+ else:
+ wbvalue_type = "table-file"
+
+ json_dict.update(
+ {
+ "_type": wbvalue_type,
+ "ncols": len(self.columns),
+ "nrows": len(self.data),
+ "log_mode": self.log_mode,
+ }
+ )
+
+ elif isinstance(run_or_artifact, wandb.Artifact):
+ artifact = run_or_artifact
+ mapped_data = []
+ data = self._to_table_json(Table.MAX_ARTIFACT_ROWS)["data"]
+
+ ndarray_col_ndxs = set()
+ for col_ndx, col_name in enumerate(self.columns):
+ col_type = self._column_types.params["type_map"][col_name]
+ ndarray_type = None
+ if isinstance(col_type, _dtypes.NDArrayType):
+ ndarray_type = col_type
+ elif isinstance(col_type, _dtypes.UnionType):
+ for t in col_type.params["allowed_types"]:
+ if isinstance(t, _dtypes.NDArrayType):
+ ndarray_type = t
+
+ # Do not serialize 1d arrays - these are likely embeddings and
+ # will not have the same cost as higher dimensional arrays
+ is_1d_array = (
+ ndarray_type is not None
+ and "shape" in ndarray_type._params
+ and isinstance(ndarray_type._params["shape"], list)
+ and len(ndarray_type._params["shape"]) == 1
+ and ndarray_type._params["shape"][0]
+ <= self._MAX_EMBEDDING_DIMENSIONS
+ )
+ if is_1d_array:
+ self._column_types.params["type_map"][col_name] = _dtypes.ListType(
+ _dtypes.NumberType, ndarray_type._params["shape"][0]
+ )
+ elif ndarray_type is not None:
+ np = util.get_module(
+ "numpy",
+ required="Serializing NumPy requires NumPy to be installed.",
+ )
+ file_name = f"{str(col_name)}_{runid.generate_id()}.npz"
+ npz_file_name = os.path.join(MEDIA_TMP.name, file_name)
+ np.savez_compressed(
+ npz_file_name,
+ **{
+ str(col_name): self.get_column(col_name, convert_to="numpy")
+ },
+ )
+ entry = artifact.add_file(
+ npz_file_name, "media/serialized_data/" + file_name, is_tmp=True
+ )
+ ndarray_type._set_serialization_path(entry.path, str(col_name))
+ ndarray_col_ndxs.add(col_ndx)
+
+ for row in data:
+ mapped_row = []
+ for ndx, v in enumerate(row):
+ if ndx in ndarray_col_ndxs:
+ mapped_row.append(None)
+ else:
+ mapped_row.append(_json_helper(v, artifact))
+ mapped_data.append(mapped_row)
+
+ json_dict.update(
+ {
+ "_type": Table._log_type,
+ "columns": self.columns,
+ "data": mapped_data,
+ "ncols": len(self.columns),
+ "nrows": len(mapped_data),
+ "column_types": self._column_types.to_json(artifact),
+ "log_mode": self.log_mode,
+ }
+ )
+ else:
+ raise TypeError("to_json accepts wandb_run.Run or wandb_artifact.Artifact")
+
+ return json_dict
+
+ def iterrows(self):
+ """Returns the table data by row, showing the index of the row and the relevant data.
+
+ Yields:
+ ------
+ index: The index of the row. Using this value in other W&B tables
+ will automatically build a relationship between the tables
+ row: The data of the row.
+
+
+ """
+ for ndx in range(len(self.data)):
+ index = _TableIndex(ndx)
+ index.set_table(self)
+ yield index, self.data[ndx]
+
+ @allow_relogging_after_mutation
+ def set_pk(self, col_name):
+ """Set primary key type for Table object.
+
+
+ """
+ # TODO: Docs
+ assert col_name in self.columns
+ self.cast(col_name, _PrimaryKeyType())
+
+ @allow_relogging_after_mutation
+ def set_fk(self, col_name, table, table_col):
+ """Set foreign key type for Table object.
+
+
+ """
+ # TODO: Docs
+ assert col_name in self.columns
+ assert col_name != self._pk_col
+ self.cast(col_name, _ForeignKeyType(table, table_col))
+
+ def _update_keys(self, force_last=False):
+ """Updates the known key-like columns based on current column types.
+
+ If the state has been updated since the last update, wraps the data
+ appropriately in the Key classes.
+
+ Args:
+ force_last: (bool) Wraps the last column of data even if there
+ are no key updates.
+ """
+ _pk_col = None
+ _fk_cols = set()
+
+ # Buildup the known keys from column types
+ c_types = self._column_types.params["type_map"]
+ for t in c_types:
+ if isinstance(c_types[t], _PrimaryKeyType):
+ _pk_col = t
+ elif isinstance(c_types[t], _ForeignKeyType) or isinstance(
+ c_types[t], _ForeignIndexType
+ ):
+ _fk_cols.add(t)
+
+ # If there are updates to perform, safely update them
+ has_update = _pk_col != self._pk_col or _fk_cols != self._fk_cols
+ if has_update:
+ # If we removed the PK
+ if _pk_col is None and self._pk_col is not None:
+ raise AssertionError(
+ f"Cannot unset primary key (column {self._pk_col})"
+ )
+ # If there is a removed FK
+ if len(self._fk_cols - _fk_cols) > 0:
+ raise AssertionError(
+ f"Cannot unset foreign key. Attempted to unset ({self._fk_cols - _fk_cols})"
+ )
+
+ self._pk_col = _pk_col
+ self._fk_cols = _fk_cols
+
+ # Apply updates to data only if there are update or the caller
+ # requested the final row to be updated
+ if has_update or force_last:
+ self._apply_key_updates(not has_update)
+
+ def _apply_key_updates(self, only_last=False):
+ """Appropriately wraps the underlying data in special Key classes.
+
+ Args:
+ only_last: only apply the updates to the last row (used for performance when
+ the caller knows that the only new data is the last row and no updates were
+ applied to the column types)
+ """
+ c_types = self._column_types.params["type_map"]
+
+ # Define a helper function which will wrap the data of a single row
+ # in the appropriate class wrapper.
+ def update_row(row_ndx):
+ for fk_col in self._fk_cols:
+ col_ndx = self.columns.index(fk_col)
+
+ # Wrap the Foreign Keys
+ if isinstance(c_types[fk_col], _ForeignKeyType) and not isinstance(
+ self.data[row_ndx][col_ndx], _TableKey
+ ):
+ self.data[row_ndx][col_ndx] = _TableKey(self.data[row_ndx][col_ndx])
+ self.data[row_ndx][col_ndx].set_table(
+ c_types[fk_col].params["table"],
+ c_types[fk_col].params["col_name"],
+ )
+
+ # Wrap the Foreign Indexes
+ elif isinstance(c_types[fk_col], _ForeignIndexType) and not isinstance(
+ self.data[row_ndx][col_ndx], _TableIndex
+ ):
+ self.data[row_ndx][col_ndx] = _TableIndex(
+ self.data[row_ndx][col_ndx]
+ )
+ self.data[row_ndx][col_ndx].set_table(
+ c_types[fk_col].params["table"]
+ )
+
+ # Wrap the Primary Key
+ if self._pk_col is not None:
+ col_ndx = self.columns.index(self._pk_col)
+ self.data[row_ndx][col_ndx] = _TableKey(self.data[row_ndx][col_ndx])
+ self.data[row_ndx][col_ndx].set_table(self, self._pk_col)
+
+ if only_last:
+ update_row(len(self.data) - 1)
+ else:
+ for row_ndx in range(len(self.data)):
+ update_row(row_ndx)
+
+ @ensure_not_incremental
+ @allow_relogging_after_mutation
+ def add_column(self, name, data, optional=False):
+ """Adds a column of data to the table.
+
+ Args:
+ name: (str) - the unique name of the column
+ data: (list | np.array) - a column of homogeneous data
+ optional: (bool) - if null-like values are permitted
+ """
+ assert isinstance(name, str) and name not in self.columns
+ is_np = util.is_numpy_array(data)
+ assert isinstance(data, list) or is_np
+ assert isinstance(optional, bool)
+ is_first_col = len(self.columns) == 0
+ assert is_first_col or len(data) == len(self.data), (
+ f"Expected length {len(self.data)}, found {len(data)}"
+ )
+
+ # Add the new data
+ for ndx in range(max(len(data), len(self.data))):
+ if is_first_col:
+ self.data.append([])
+ if is_np:
+ self.data[ndx].append(data[ndx])
+ else:
+ self.data[ndx].append(data[ndx])
+ # add the column
+ self.columns.append(name)
+
+ try:
+ self.cast(name, _dtypes.UnknownType(), optional=optional)
+ except TypeError:
+ # Undo the changes
+ if is_first_col:
+ self.data = []
+ self.columns = []
+ else:
+ for ndx in range(len(self.data)):
+ self.data[ndx] = self.data[ndx][:-1]
+ self.columns = self.columns[:-1]
+ raise
+
+ def get_column(self, name, convert_to=None):
+ """Retrieves a column from the table and optionally converts it to a NumPy object.
+
+ Args:
+ name: (str) - the name of the column
+ convert_to: (str, optional)
+ - "numpy": will convert the underlying data to numpy object
+ """
+ assert name in self.columns
+ assert convert_to is None or convert_to == "numpy"
+ if convert_to == "numpy":
+ np = util.get_module(
+ "numpy", required="Converting to NumPy requires installing NumPy"
+ )
+ col = []
+ col_ndx = self.columns.index(name)
+ for row in self.data:
+ item = row[col_ndx]
+ if convert_to is not None and isinstance(item, WBValue):
+ item = item.to_data_array()
+ col.append(item)
+ if convert_to == "numpy":
+ col = np.array(col)
+ return col
+
+ def get_index(self):
+ """Returns an array of row indexes for use in other tables to create links."""
+ ndxs = []
+ for ndx in range(len(self.data)):
+ index = _TableIndex(ndx)
+ index.set_table(self)
+ ndxs.append(index)
+ return ndxs
+
+ def get_dataframe(self):
+ """Returns a `pandas.DataFrame` of the table."""
+ pd = util.get_module(
+ "pandas",
+ required="Converting to pandas.DataFrame requires installing pandas",
+ )
+ return pd.DataFrame.from_records(self.data, columns=self.columns)
+
+ def index_ref(self, index):
+ """Gets a reference of the index of a row in the table.
+
+
+ """
+ assert index < len(self.data)
+ _index = _TableIndex(index)
+ _index.set_table(self)
+ return _index
+
+ @ensure_not_incremental
+ @allow_relogging_after_mutation
+ def add_computed_columns(self, fn):
+ """Adds one or more computed columns based on existing data.
+
+ Args:
+ fn: A function which accepts one or two parameters, ndx (int) and
+ row (dict), which is expected to return a dict representing
+ new columns for that row, keyed by the new column names.
+ - `ndx` is an integer representing the index of the row. Only included if `include_ndx`
+ is set to `True`.
+ - `row` is a dictionary keyed by existing columns
+ """
+ new_columns = {}
+ for ndx, row in self.iterrows():
+ row_dict = {self.columns[i]: row[i] for i in range(len(self.columns))}
+ new_row_dict = fn(ndx, row_dict)
+ assert isinstance(new_row_dict, dict)
+ for key in new_row_dict:
+ new_columns[key] = new_columns.get(key, [])
+ new_columns[key].append(new_row_dict[key])
+ for new_col_name in new_columns:
+ self.add_column(new_col_name, new_columns[new_col_name])
+
+
+class _PartitionTablePartEntry:
+ """Helper class for PartitionTable to track its parts."""
+
+ def __init__(self, entry, source_artifact):
+ self.entry = entry
+ self.source_artifact = source_artifact
+ self._part = None
+
+ def get_part(self):
+ if self._part is None:
+ self._part = self.source_artifact.get(self.entry.path)
+ return self._part
+
+ def free(self):
+ self._part = None
+
+
+class PartitionedTable(Media):
+ """A table which is composed of multiple sub-tables.
+
+ Currently, PartitionedTable is designed to point to a directory within an
+ artifact.
+ """
+
+ _log_type = "partitioned-table"
+
+ def __init__(self, parts_path):
+ """Initialize a PartitionedTable.
+
+ Args:
+ parts_path (str): path to a directory of tables in the artifact.
+ """
+ super().__init__()
+ self.parts_path = parts_path
+ self._loaded_part_entries = {}
+
+ def to_json(self, artifact_or_run):
+ json_obj = {
+ "_type": PartitionedTable._log_type,
+ }
+ if isinstance(artifact_or_run, wandb.Run):
+ artifact_entry_url = self._get_artifact_entry_ref_url()
+ if artifact_entry_url is None:
+ raise ValueError(
+ "PartitionedTables must first be added to an Artifact before logging to a Run"
+ )
+ json_obj["artifact_path"] = artifact_entry_url
+ else:
+ json_obj["parts_path"] = self.parts_path
+ return json_obj
+
+ @classmethod
+ def from_json(cls, json_obj, source_artifact):
+ instance = cls(json_obj["parts_path"])
+ entries = source_artifact.manifest.get_entries_in_directory(
+ json_obj["parts_path"]
+ )
+ for entry in entries:
+ instance._add_part_entry(entry, source_artifact)
+ return instance
+
+ def iterrows(self):
+ """Iterate over rows as (ndx, row).
+
+ Args:
+ index (int): The index of the row.
+ row (List[any]): The data of the row.
+ """
+ columns = None
+ ndx = 0
+ for entry_path in self._loaded_part_entries:
+ part = self._loaded_part_entries[entry_path].get_part()
+ if columns is None:
+ columns = part.columns
+ elif columns != part.columns:
+ raise ValueError(
+ f"Table parts have non-matching columns. {columns} != {part.columns}"
+ )
+ for _, row in part.iterrows():
+ yield ndx, row
+ ndx += 1
+
+ self._loaded_part_entries[entry_path].free()
+
+ def _add_part_entry(self, entry, source_artifact):
+ self._loaded_part_entries[entry.path] = _PartitionTablePartEntry(
+ entry, source_artifact
+ )
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+ def __eq__(self, other):
+ return isinstance(other, self.__class__) and self.parts_path == other.parts_path
+
+ def bind_to_run(self, *args, **kwargs):
+ raise ValueError("PartitionedTables cannot be bound to runs")
+
+
+class JoinedTable(Media):
+ """Join two tables for visualization in the Artifact UI.
+
+ Args:
+ table1 (str, wandb.Table, ArtifactManifestEntry):
+ the path to a wandb.Table in an artifact, the table object, or ArtifactManifestEntry
+ table2 (str, wandb.Table):
+ the path to a wandb.Table in an artifact, the table object, or ArtifactManifestEntry
+ join_key (str, [str, str]):
+ key or keys to perform the join
+ """
+
+ _log_type = "joined-table"
+
+ def __init__(self, table1, table2, join_key):
+ super().__init__()
+
+ if not isinstance(join_key, str) and (
+ not isinstance(join_key, list) or len(join_key) != 2
+ ):
+ raise ValueError(
+ "JoinedTable join_key should be a string or a list of two strings"
+ )
+
+ if not self._validate_table_input(table1):
+ raise ValueError(
+ "JoinedTable table1 should be an artifact path to a table or wandb.Table object"
+ )
+
+ if not self._validate_table_input(table2):
+ raise ValueError(
+ "JoinedTable table2 should be an artifact path to a table or wandb.Table object"
+ )
+
+ self._table1 = table1
+ self._table2 = table2
+ self._join_key = join_key
+
+ @classmethod
+ def from_json(cls, json_obj, source_artifact):
+ t1 = source_artifact.get(json_obj["table1"])
+ if t1 is None:
+ t1 = json_obj["table1"]
+
+ t2 = source_artifact.get(json_obj["table2"])
+ if t2 is None:
+ t2 = json_obj["table2"]
+
+ return cls(
+ t1,
+ t2,
+ json_obj["join_key"],
+ )
+
+ @staticmethod
+ def _validate_table_input(table):
+ """Helper method to validate that the table input is one of the 3 supported types."""
+ return (
+ (isinstance(table, str) and table.endswith(".table.json"))
+ or isinstance(table, Table)
+ or isinstance(table, PartitionedTable)
+ or (hasattr(table, "ref_url") and table.ref_url().endswith(".table.json"))
+ )
+
+ def _ensure_table_in_artifact(self, table, artifact, table_ndx):
+ """Helper method to add the table to the incoming artifact. Returns the path."""
+ if isinstance(table, Table) or isinstance(table, PartitionedTable):
+ table_name = f"t{table_ndx}_{str(id(self))}"
+ if (
+ table._artifact_source is not None
+ and table._artifact_source.name is not None
+ ):
+ table_name = os.path.basename(table._artifact_source.name)
+ entry = artifact.add(table, table_name)
+ table = entry.path
+ # Check if this is an ArtifactManifestEntry
+ elif hasattr(table, "ref_url"):
+ # Give the new object a unique, yet deterministic name
+ name = binascii.hexlify(base64.standard_b64decode(table.digest)).decode(
+ "ascii"
+ )[:20]
+ entry = artifact.add_reference(
+ table.ref_url(), "{}.{}.json".format(name, table.name.split(".")[-2])
+ )[0]
+ table = entry.path
+
+ err_str = "JoinedTable table:{} not found in artifact. Add a table to the artifact using Artifact#add(
, {}) before adding this JoinedTable"
+ if table not in artifact._manifest.entries:
+ raise ValueError(err_str.format(table, table))
+
+ return table
+
+ def to_json(self, artifact_or_run):
+ json_obj = {
+ "_type": JoinedTable._log_type,
+ }
+ if isinstance(artifact_or_run, wandb.Run):
+ artifact_entry_url = self._get_artifact_entry_ref_url()
+ if artifact_entry_url is None:
+ raise ValueError(
+ "JoinedTables must first be added to an Artifact before logging to a Run"
+ )
+ json_obj["artifact_path"] = artifact_entry_url
+ else:
+ table1 = self._ensure_table_in_artifact(self._table1, artifact_or_run, 1)
+ table2 = self._ensure_table_in_artifact(self._table2, artifact_or_run, 2)
+ json_obj.update(
+ {
+ "table1": table1,
+ "table2": table2,
+ "join_key": self._join_key,
+ }
+ )
+ return json_obj
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+ def _eq_debug(self, other, should_assert=False):
+ eq = isinstance(other, JoinedTable)
+ assert not should_assert or eq, (
+ f"Found type {other.__class__}, expected {JoinedTable}"
+ )
+ eq = eq and self._join_key == other._join_key
+ assert not should_assert or eq, (
+ f"Found {other._join_key} join key, expected {self._join_key}"
+ )
+ eq = eq and self._table1._eq_debug(other._table1, should_assert)
+ eq = eq and self._table2._eq_debug(other._table2, should_assert)
+ return eq
+
+ def __eq__(self, other):
+ return self._eq_debug(other, False)
+
+ def bind_to_run(self, *args, **kwargs):
+ raise ValueError("JoinedTables cannot be bound to runs")
+
+
+class _TableType(_dtypes.Type):
+ name = "table"
+ legacy_names = ["wandb.Table"]
+ types = [Table]
+
+ def __init__(self, column_types=None):
+ if column_types is None:
+ column_types = _dtypes.UnknownType()
+ if isinstance(column_types, dict):
+ column_types = _dtypes.TypedDictType(column_types)
+ elif not (
+ isinstance(column_types, _dtypes.TypedDictType)
+ or isinstance(column_types, _dtypes.UnknownType)
+ ):
+ raise TypeError("column_types must be a dict or TypedDictType")
+
+ self.params.update({"column_types": column_types})
+
+ def assign_type(self, wb_type=None):
+ if isinstance(wb_type, _TableType):
+ column_types = self.params["column_types"].assign_type(
+ wb_type.params["column_types"]
+ )
+ if not isinstance(column_types, _dtypes.InvalidType):
+ return _TableType(column_types)
+
+ return _dtypes.InvalidType()
+
+ @classmethod
+ def from_obj(cls, py_obj):
+ if not isinstance(py_obj, Table):
+ raise TypeError("py_obj must be a wandb.Table")
+ else:
+ return cls(py_obj._column_types)
+
+
+class _JoinedTableType(_dtypes.Type):
+ name = "joined-table"
+ types = [JoinedTable]
+
+
+class _PartitionedTableType(_dtypes.Type):
+ name = "partitioned-table"
+ types = [PartitionedTable]
+
+
+_dtypes.TypeRegistry.add(_TableType)
+_dtypes.TypeRegistry.add(_JoinedTableType)
+_dtypes.TypeRegistry.add(_PartitionedTableType)
+_dtypes.TypeRegistry.add(_ForeignKeyType)
+_dtypes.TypeRegistry.add(_PrimaryKeyType)
+_dtypes.TypeRegistry.add(_ForeignIndexType)
+
+
+def _get_data_from_increments(
+ json_obj: Dict[str, Any], source_artifact: "artifact.Artifact"
+) -> List[Any]:
+ """Get data from incremental table artifacts.
+
+ Args:
+ json_obj: The JSON object containing table metadata.
+ source_artifact: The source artifact containing the table data.
+
+ Returns:
+ List of table rows from all increments.
+ """
+ if "latest" not in source_artifact.aliases:
+ wandb.termwarn(
+ (
+ "It is recommended to use the latest version of the "
+ "incremental table artifact for ordering guarantees."
+ ),
+ repeat=False,
+ )
+ data: List[Any] = []
+ increment_num = json_obj.get("increment_num", None)
+ if increment_num is None:
+ return data
+
+ # Sort by increment number first, then by timestamp if present
+ # Format of name is: "{incr_num}-{timestamp_ms}.{key}.table.json"
+ def get_sort_key(key: str) -> Tuple[int, int]:
+ try:
+ parts = key.split(".")
+ increment_parts = parts[0].split("-")
+ increment_num = int(increment_parts[0])
+ # If there's a timestamp part, use it for secondary sorting
+ timestamp = int(increment_parts[1]) if len(increment_parts) > 1 else 0
+ except (ValueError, IndexError):
+ wandb.termwarn(
+ (
+ f"Could not parse artifact entry for increment {key}."
+ " The entry name does not follow the naming convention"
+ " -..table.json"
+ " The data in the table will be out of order."
+ ),
+ repeat=False,
+ )
+ return (0, 0)
+
+ return (increment_num, timestamp)
+
+ sorted_increment_keys = []
+ for entry_key in source_artifact.manifest.entries:
+ if entry_key.endswith(".table.json"):
+ sorted_increment_keys.append(entry_key)
+
+ sorted_increment_keys.sort(key=get_sort_key)
+
+ for entry_key in sorted_increment_keys:
+ try:
+ with open(source_artifact.manifest.entries[entry_key].download()) as f:
+ table_data = json.load(f)
+ data.extend(table_data["data"])
+ except (json.JSONDecodeError, KeyError) as e:
+ raise wandb.Error(f"Invalid table file {entry_key}") from e
+ return data
+
+
+def _process_table_row(
+ row: List[Any],
+ timestamp_column_indices: Set[_dtypes.TimestampType],
+ np_deserialized_columns: Dict[int, Any],
+ source_artifact: "artifact.Artifact",
+ row_idx: int,
+) -> List[Any]:
+ """Convert special columns in a table row to Python types.
+
+ Processes a single row of table data by converting timestamp values to
+ datetime objects, replacing np typed cells with numpy array data,
+ and initializing media objects from their json value.
+
+
+ Args:
+ row: The row data to process.
+ timestamp_column_indices: Set of column indices containing timestamps.
+ np_deserialized_columns: Dictionary mapping column indices to numpy arrays.
+ source_artifact: The source artifact containing the table data.
+ row_idx: The index of the current row.
+
+ Returns:
+ Processed row data.
+ """
+ row_data = []
+ for c_ndx, item in enumerate(row):
+ cell: Any
+ if c_ndx in timestamp_column_indices and isinstance(item, (int, float)):
+ cell = datetime.datetime.fromtimestamp(
+ item / 1000, tz=datetime.timezone.utc
+ )
+ elif c_ndx in np_deserialized_columns:
+ cell = np_deserialized_columns[c_ndx][row_idx]
+ elif (
+ isinstance(item, dict)
+ and "_type" in item
+ and (obj := WBValue.init_from_json(item, source_artifact))
+ ):
+ cell = obj
+ else:
+ cell = item
+ row_data.append(cell)
+ return row_data
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/table_decorators.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/table_decorators.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c4ead3462d8745ef21c319321c9773667a2ee4d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/table_decorators.py
@@ -0,0 +1,108 @@
+"""Decorators for W&B Table operations."""
+
+from __future__ import annotations
+
+from functools import wraps
+from typing import Any, Callable, TypeVar
+
+from typing_extensions import Concatenate, ParamSpec
+
+import wandb
+
+_P = ParamSpec("_P")
+_T = TypeVar("_T")
+
+
+def allow_relogging_after_mutation(
+ method: Callable[Concatenate[wandb.Table, _P], _T],
+) -> Callable[Concatenate[wandb.Table, _P], _T]:
+ """Decorator that handles table state after mutations based on log_mode.
+
+ For MUTABLE tables, resets the run and artifact target to allow re-logging.
+ For IMMUTABLE tables, warns if attempting to mutate after logging.
+ """
+
+ @wraps(method)
+ def wrapper(self: wandb.Table, *args: Any, **kwargs: Any) -> _T:
+ has_been_logged = self._run is not None or self._artifact_target is not None
+
+ if self.log_mode == "MUTABLE":
+ self._run = None
+ self._artifact_target = None
+ self._path = None
+ self._sha256 = None
+ elif self.log_mode == "IMMUTABLE" and has_been_logged:
+ wandb.termwarn(
+ "You are mutating a Table with log_mode='IMMUTABLE' that has been "
+ "logged already. Subsequent log() calls will have no effect. "
+ "Set log_mode='MUTABLE' to enable re-logging after mutations",
+ repeat=False,
+ )
+
+ return method(self, *args, **kwargs)
+
+ return wrapper
+
+
+def allow_incremental_logging_after_append(
+ method: Callable[Concatenate[wandb.Table, _P], _T],
+) -> Callable[Concatenate[wandb.Table, _P], _T]:
+ """Decorator that handles incremental logging state after append operations.
+
+ For INCREMENTAL tables, manages artifact references and increments counters
+ to support partial data logging.
+ """
+
+ @wraps(method)
+ def wrapper(self: wandb.Table, *args: Any, **kwargs: Any) -> _T:
+ res = method(self, *args, **kwargs)
+
+ if self.log_mode != "INCREMENTAL" or self._artifact_target is None:
+ return res
+
+ art_entry_url = self._get_artifact_entry_ref_url()
+ if art_entry_url is not None:
+ if self._previous_increments_paths is None:
+ raise ValueError(
+ "_previous_increments_paths must be set if incremental"
+ " table has been logged already"
+ )
+ self._previous_increments_paths.append(art_entry_url)
+ self._run = None
+ self._artifact_target = None
+ self._path = None
+ self._sha256 = None
+
+ if self._increment_num is None:
+ raise ValueError(
+ "_increment_num must be set if incremental table has been"
+ " logged already"
+ )
+
+ self._increment_num += 1
+ if self._increment_num > 99:
+ wandb.termwarn(
+ "You have exceeded 100 increments for this table. "
+ "Only the latest 100 increments will be visualized in the run workspace.",
+ repeat=False,
+ )
+ return res
+
+ return wrapper
+
+
+def ensure_not_incremental(
+ method: Callable[Concatenate[wandb.Table, _P], _T],
+) -> Callable[Concatenate[wandb.Table, _P], _T]:
+ """Decorator that checks if log mode is incremental to disallow methods from being called."""
+
+ @wraps(method)
+ def wrapper(self: wandb.Table, *args: Any, **kwargs: Any) -> _T:
+ if self.log_mode == "INCREMENTAL":
+ raise wandb.Error(
+ f"Operation '{method.__name__}' is not supported for tables with "
+ "log_mode='INCREMENTAL'. Use a different log mode like 'MUTABLE' or 'IMMUTABLE'."
+ )
+ return method(self, *args, **kwargs)
+
+ return wrapper
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/trace_tree.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/trace_tree.py
new file mode 100644
index 0000000000000000000000000000000000000000..d42d407c8a4ad9397306be9e3ea5a37383496a6e
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/trace_tree.py
@@ -0,0 +1,440 @@
+"""This module contains the `WBTraceTree` media type, and the supporting dataclasses.
+
+A `WBTraceTree` is a media object containing a root span and an
+arbitrary model dump as a serializable dictionary. Logging such media type will
+result in a W&B Trace Debugger panel being created in the workspace UI.
+"""
+
+import dataclasses
+import hashlib
+import json
+import typing
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
+
+import wandb
+from wandb.sdk.data_types import _dtypes
+from wandb.sdk.data_types.base_types.media import Media
+from wandb.sdk.data_types.utils import _json_helper
+
+if TYPE_CHECKING: # pragma: no cover
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ from ..wandb_run import Run as LocalRun
+
+
+class StatusCode(str, Enum):
+ SUCCESS = "SUCCESS"
+ ERROR = "ERROR"
+
+ def __str__(self) -> str:
+ return str(self.value)
+
+
+class SpanKind(str, Enum):
+ LLM = "LLM"
+ CHAIN = "CHAIN"
+ AGENT = "AGENT"
+ TOOL = "TOOL"
+
+ def __str__(self) -> str:
+ return str(self.value)
+
+
+@dataclass()
+class Result:
+ inputs: Optional[Dict[str, Any]] = field(default=None)
+ outputs: Optional[Dict[str, Any]] = field(default=None)
+
+
+@dataclass()
+class Span:
+ span_id: Optional[str] = field(default=None)
+ name: Optional[str] = field(default=None)
+ start_time_ms: Optional[int] = field(default=None)
+ end_time_ms: Optional[int] = field(default=None)
+ status_code: Optional[StatusCode] = field(default=None)
+ status_message: Optional[str] = field(default=None)
+ attributes: Optional[Dict[str, Any]] = field(default=None)
+ results: Optional[List[Result]] = field(default=None)
+ child_spans: Optional[List["Span"]] = field(default=None)
+ span_kind: Optional[SpanKind] = field(default=None)
+
+ def add_attribute(self, key: str, value: Any) -> None:
+ if self.attributes is None:
+ self.attributes = {}
+ self.attributes[key] = value
+
+ def add_named_result(self, inputs: Dict[str, Any], outputs: Dict[str, Any]) -> None:
+ if self.results is None:
+ self.results = []
+ self.results.append(Result(inputs, outputs))
+
+ def add_child_span(self, span: "Span") -> None:
+ if self.child_spans is None:
+ self.child_spans = []
+ self.child_spans.append(span)
+
+
+class WBTraceTree(Media):
+ """Media object for trace tree data.
+
+ Args:
+ root_span (Span): The root span of the trace tree.
+ model_dict (dict, optional): A dictionary containing the model dump.
+ NOTE: model_dict is a completely-user-defined dict. The UI will render
+ a JSON viewer for this dict, giving special treatment to dictionaries
+ with a `_kind` key. This is because model vendors have such different
+ serialization formats that we need to be flexible here.
+ """
+
+ _log_type = "wb_trace_tree"
+
+ def __init__(
+ self,
+ root_span: Span,
+ model_dict: typing.Optional[dict] = None,
+ ):
+ super().__init__()
+ self._root_span = root_span
+ self._model_dict = model_dict
+
+ @classmethod
+ def get_media_subdir(cls) -> str:
+ return "media/wb_trace_tree"
+
+ def to_json(self, run: Optional[Union["LocalRun", "Artifact"]]) -> dict:
+ res = {"_type": self._log_type}
+ # Here we use `dumps` to put things into string format. This is because
+ # the complex data structures create problems for gorilla history to parquet.
+ if self._model_dict is not None:
+ model_dump_str = _safe_serialize(self._model_dict)
+ res["model_hash"] = _hash_id(model_dump_str)
+ res["model_dict_dumps"] = model_dump_str
+ res["root_span_dumps"] = _safe_serialize(dataclasses.asdict(self._root_span))
+ return res
+
+ def is_bound(self) -> bool:
+ return True
+
+
+class _WBTraceTreeFileType(_dtypes.Type):
+ name = "wb_trace_tree"
+ types = [WBTraceTree]
+
+
+_dtypes.TypeRegistry.add(_WBTraceTreeFileType)
+
+
+# generate a deterministic 16 character id based on input string
+def _hash_id(s: str) -> str:
+ return hashlib.md5(s.encode("utf-8")).hexdigest()[:16]
+
+
+def _fallback_serialize(obj: Any) -> str:
+ try:
+ return f"<>"
+ except Exception:
+ return "<>"
+
+
+def _safe_serialize(obj: dict) -> str:
+ try:
+ return json.dumps(
+ _json_helper(obj, None),
+ skipkeys=True,
+ default=_fallback_serialize,
+ )
+ except Exception:
+ return "{}"
+
+
+class TraceAttribute:
+ """Descriptor for accessing and setting attributes of the `Trace` class."""
+
+ def __set_name__(self, owner: type, name: str) -> None:
+ self.name = name
+
+ def __get__(self, instance: "Trace", owner: type) -> Any:
+ return getattr(instance._span, self.name)
+
+ def __set__(self, instance: "Trace", value: Any) -> None:
+ setattr(instance._span, self.name, value)
+
+
+class Trace:
+ """A simplification of WBTraceTree and Span to manage a trace - a collection of spans, their metadata and hierarchy.
+
+ Args:
+ name: (str) The name of the root span.
+ kind: (str, optional) The kind of the root span.
+ status_code: (str, optional) The status of the root span, either "error" or "success".
+ status_message: (str, optional) Any status message associated with the root span.
+ metadata: (dict, optional) Any additional metadata for the root span.
+ start_time_ms: (int, optional) The start time of the root span in milliseconds.
+ end_time_ms: (int, optional) The end time of the root span in milliseconds.
+ inputs: (dict, optional) The named inputs of the root span.
+ outputs: (dict, optional) The named outputs of the root span.
+ model_dict: (dict, optional) A json serializable dictionary containing the model architecture details.
+
+ Example:
+ .. code-block:: python
+ ```
+ trace = Trace(
+ name="My awesome Model",
+ kind="LLM",
+ status_code= "SUCCESS",
+ metadata={"attr_1": 1, "attr_2": 2,},
+ start_time_ms=int(round(time.time() * 1000)),
+ end_time_ms=int(round(time.time() * 1000))+1000,
+ inputs={"user": "How old is google?"},
+ outputs={"assistant": "25 years old"},
+ model_dict={"_kind": "openai", "api_type": "azure"}
+ )
+ run = wandb.init(project=,)
+ trace.log("my_trace")
+ wandb.finish()
+ ```
+ """
+
+ name = TraceAttribute()
+ status_code = TraceAttribute()
+ status_message = TraceAttribute()
+ start_time_ms = TraceAttribute()
+ end_time_ms = TraceAttribute()
+
+ def __init__(
+ self,
+ name: str,
+ kind: Optional[str] = None,
+ status_code: Optional[str] = None,
+ status_message: Optional[str] = None,
+ metadata: Optional[dict] = None,
+ start_time_ms: Optional[int] = None,
+ end_time_ms: Optional[int] = None,
+ inputs: Optional[dict] = None,
+ outputs: Optional[dict] = None,
+ model_dict: Optional[dict] = None,
+ ):
+ self._span = self._assert_and_create_span(
+ name=name,
+ kind=kind,
+ status_code=status_code,
+ status_message=status_message,
+ metadata=metadata,
+ start_time_ms=start_time_ms,
+ end_time_ms=end_time_ms,
+ inputs=inputs,
+ outputs=outputs,
+ )
+ if model_dict is not None:
+ assert isinstance(model_dict, dict), "Model dict must be a dictionary"
+ self._model_dict = model_dict
+
+ def _assert_and_create_span(
+ self,
+ name: str,
+ kind: Optional[str] = None,
+ status_code: Optional[str] = None,
+ status_message: Optional[str] = None,
+ metadata: Optional[dict] = None,
+ start_time_ms: Optional[int] = None,
+ end_time_ms: Optional[int] = None,
+ inputs: Optional[dict] = None,
+ outputs: Optional[dict] = None,
+ ) -> Span:
+ """Utility to assert the validity of the span parameters and create a span object.
+
+ Args:
+ name: The name of the span.
+ kind: The kind of the span.
+ status_code: The status code of the span.
+ status_message: The status message of the span.
+ metadata: Dictionary of metadata to be logged with the span.
+ start_time_ms: Start time of the span in milliseconds.
+ end_time_ms: End time of the span in milliseconds.
+ inputs: Dictionary of inputs to be logged with the span.
+ outputs: Dictionary of outputs to be logged with the span.
+
+ Returns:
+ A Span object.
+ """
+ if kind is not None:
+ assert kind.upper() in SpanKind.__members__, (
+ "Invalid span kind, can be one of 'LLM', 'AGENT', 'CHAIN', 'TOOL'"
+ )
+ kind = SpanKind(kind.upper())
+ if status_code is not None:
+ assert status_code.upper() in StatusCode.__members__, (
+ "Invalid status code, can be one of 'SUCCESS' or 'ERROR'"
+ )
+ status_code = StatusCode(status_code.upper())
+ if inputs is not None:
+ assert isinstance(inputs, dict), "Inputs must be a dictionary"
+ if outputs is not None:
+ assert isinstance(outputs, dict), "Outputs must be a dictionary"
+ if inputs or outputs:
+ result = Result(inputs=inputs, outputs=outputs)
+ else:
+ result = None
+
+ if metadata is not None:
+ assert isinstance(metadata, dict), "Metadata must be a dictionary"
+
+ return Span(
+ name=name,
+ span_kind=kind,
+ status_code=status_code,
+ status_message=status_message,
+ attributes=metadata,
+ start_time_ms=start_time_ms,
+ end_time_ms=end_time_ms,
+ results=[result] if result else None,
+ )
+
+ def add_child(
+ self,
+ child: "Trace",
+ ) -> "Trace":
+ """Utility to add a child span to the current span of the trace.
+
+ Args:
+ child: The child span to be added to the current span of the trace.
+
+ Returns:
+ The current trace object with the child span added to it.
+ """
+ self._span.add_child_span(child._span)
+ if self._model_dict is not None and child._model_dict is not None:
+ self._model_dict.update({child._span.name: child._model_dict})
+ return self
+
+ def add_inputs_and_outputs(self, inputs: dict, outputs: dict) -> "Trace":
+ """Add a result to the span of the current trace.
+
+ Args:
+ inputs: Dictionary of inputs to be logged with the span.
+ outputs: Dictionary of outputs to be logged with the span.
+
+ Returns:
+ The current trace object with the result added to it.
+ """
+ if self._span.results is None:
+ result = Result(inputs=inputs, outputs=outputs)
+ self._span.results = [result]
+ else:
+ result = Result(inputs=inputs, outputs=outputs)
+ self._span.results.append(result)
+ return self
+
+ def add_metadata(self, metadata: dict) -> "Trace":
+ """Add metadata to the span of the current trace."""
+ if self._span.attributes is None:
+ self._span.attributes = metadata
+ else:
+ self._span.attributes.update(metadata)
+ return self
+
+ @property
+ def metadata(self) -> Optional[Dict[str, str]]:
+ """Get the metadata of the trace.
+
+ Returns:
+ Dictionary of metadata.
+ """
+ return self._span.attributes
+
+ @metadata.setter
+ def metadata(self, value: Dict[str, str]) -> None:
+ """Set the metadata of the trace.
+
+ Args:
+ value: Dictionary of metadata to be set.
+ """
+ if self._span.attributes is None:
+ self._span.attributes = value
+ else:
+ self._span.attributes.update(value)
+
+ @property
+ def inputs(self) -> Optional[Dict[str, str]]:
+ """Get the inputs of the trace.
+
+ Returns:
+ Dictionary of inputs.
+ """
+ return self._span.results[-1].inputs if self._span.results else None
+
+ @inputs.setter
+ def inputs(self, value: Dict[str, str]) -> None:
+ """Set the inputs of the trace.
+
+ Args:
+ value: Dictionary of inputs to be set.
+ """
+ if self._span.results is None:
+ result = Result(inputs=value, outputs={})
+ self._span.results = [result]
+ else:
+ result = Result(inputs=value, outputs=self._span.results[-1].outputs)
+ self._span.results.append(result)
+
+ @property
+ def outputs(self) -> Optional[Dict[str, str]]:
+ """Get the outputs of the trace.
+
+ Returns:
+ Dictionary of outputs.
+ """
+ return self._span.results[-1].outputs if self._span.results else None
+
+ @outputs.setter
+ def outputs(self, value: Dict[str, str]) -> None:
+ """Set the outputs of the trace.
+
+ Args:
+ value: Dictionary of outputs to be set.
+ """
+ if self._span.results is None:
+ result = Result(inputs={}, outputs=value)
+ self._span.results = [result]
+ else:
+ result = Result(inputs=self._span.results[-1].inputs, outputs=value)
+ self._span.results.append(result)
+
+ @property
+ def kind(self) -> Optional[str]:
+ """Get the kind of the trace.
+
+ Returns:
+ The kind of the trace.
+ """
+ return self._span.span_kind.value if self._span.span_kind else None
+
+ @kind.setter
+ def kind(self, value: str) -> None:
+ """Set the kind of the trace.
+
+ Args:
+ value: The kind of the trace to be set.
+ """
+ assert value.upper() in SpanKind.__members__, (
+ "Invalid span kind, can be one of 'LLM', 'AGENT', 'CHAIN', 'TOOL'"
+ )
+ self._span.span_kind = SpanKind(value.upper())
+
+ def log(self, name: str) -> None:
+ """Log the trace to a wandb run.
+
+ Args:
+ name: The name of the trace to be logged
+ """
+ trace_tree = WBTraceTree(self._span, self._model_dict)
+ # NOTE: Does not work for reinit="create_new" runs.
+ # This method should be deprecated and users should call run.log().
+ assert wandb.run is not None, (
+ "You must call wandb.init() before logging a trace"
+ )
+ assert len(name.strip()) > 0, "You must provide a valid name to log the trace"
+ wandb.run.log({name: trace_tree})
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/utils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a7515446782ddce590f814f9546aea8e2887c4e
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/utils.py
@@ -0,0 +1,260 @@
+import datetime
+import logging
+import os
+from decimal import Decimal
+from typing import TYPE_CHECKING, Optional, Sequence, Union, cast
+
+import wandb
+from wandb import util
+
+from ..internal import incremental_table_util
+from .base_types.media import BatchableMedia, Media
+from .base_types.wb_value import WBValue
+from .image import _server_accepts_image_filenames
+from .plotly import Plotly
+
+if TYPE_CHECKING: # pragma: no cover
+ import matplotlib # type: ignore
+ import pandas as pd
+ import plotly # type: ignore
+
+ from ..wandb_run import Run as LocalRun
+
+ ValToJsonType = Union[
+ dict,
+ "WBValue",
+ Sequence["WBValue"],
+ "plotly.Figure",
+ "matplotlib.artist.Artist",
+ "pd.DataFrame",
+ object,
+ ]
+
+
+def history_dict_to_json(
+ run: Optional["LocalRun"],
+ payload: dict,
+ step: Optional[int] = None,
+ ignore_copy_err: Optional[bool] = None,
+) -> dict:
+ # Converts a History row dict's elements so they're friendly for JSON serialization.
+
+ if step is None:
+ # We should be at the top level of the History row; assume this key is set.
+ step = payload["_step"]
+
+ # We use list here because we were still seeing cases of RuntimeError dict changed size
+ for key in list(payload):
+ val = payload[key]
+ if isinstance(val, dict):
+ payload[key] = history_dict_to_json(
+ run, val, step=step, ignore_copy_err=ignore_copy_err
+ )
+ else:
+ payload[key] = val_to_json(
+ run, key, val, namespace=step, ignore_copy_err=ignore_copy_err
+ )
+
+ return payload
+
+
+# TODO: refine this
+def val_to_json(
+ run: Optional["LocalRun"],
+ key: str,
+ val: "ValToJsonType",
+ namespace: Optional[Union[str, int]] = None,
+ ignore_copy_err: Optional[bool] = None,
+) -> Union[Sequence, dict]:
+ # Converts a wandb datatype to its JSON representation.
+ if namespace is None:
+ raise ValueError(
+ "val_to_json must be called with a namespace(a step number, or 'summary') argument"
+ )
+
+ converted = val
+
+ if isinstance(val, (int, float, str, bool)):
+ # These are already JSON-serializable,
+ # no need to do the expensive checks below.
+ return converted # type: ignore[return-value]
+
+ typename = util.get_full_typename(val)
+
+ if util.is_pandas_data_frame(val):
+ val = wandb.Table(dataframe=val)
+
+ elif util.is_matplotlib_typename(typename) or util.is_plotly_typename(typename):
+ val = Plotly.make_plot_media(val)
+ elif isinstance(val, (list, tuple, range)) and all(
+ isinstance(v, WBValue) for v in val
+ ):
+ assert run
+ # This check will break down if Image/Audio/... have child classes.
+ if (
+ len(val)
+ and isinstance(val[0], BatchableMedia)
+ and all(isinstance(v, type(val[0])) for v in val)
+ ):
+ if TYPE_CHECKING:
+ val = cast(Sequence["BatchableMedia"], val)
+
+ items = _prune_max_seq(val)
+
+ if _server_accepts_image_filenames(run):
+ for item in items:
+ item.bind_to_run(
+ run=run,
+ key=key,
+ step=namespace,
+ ignore_copy_err=ignore_copy_err,
+ )
+ else:
+ for i, item in enumerate(items):
+ item.bind_to_run(
+ run=run,
+ key=key,
+ step=namespace,
+ id_=i,
+ ignore_copy_err=ignore_copy_err,
+ )
+ if run._attach_id and run._init_pid != os.getpid():
+ wandb.termwarn(
+ f"Attempting to log a sequence of {items[0].__class__.__name__} objects from multiple processes might result in data loss. Please upgrade your wandb server",
+ repeat=False,
+ )
+
+ return items[0].seq_to_json(items, run, key, namespace)
+ else:
+ # TODO(adrian): Good idea to pass on the same key here? Maybe include
+ # the array index?
+ # There is a bug here: if this array contains two arrays of the same type of
+ # anonymous media objects, their eventual names will collide.
+ # This used to happen. The frontend doesn't handle heterogeneous arrays
+ # raise ValueError(
+ # "Mixed media types in the same list aren't supported")
+ return [
+ val_to_json(
+ run, key, v, namespace=namespace, ignore_copy_err=ignore_copy_err
+ )
+ for v in val
+ ]
+
+ if isinstance(val, WBValue):
+ assert run
+ if isinstance(val, Media) and not val.is_bound():
+ if hasattr(val, "_log_type") and val._log_type in [
+ "table",
+ "partitioned-table",
+ "joined-table",
+ ]:
+ _log_table_artifact(val, key, run)
+
+ # Partitioned tables and joined tables do not support being bound to runs.
+ if not (
+ hasattr(val, "_log_type")
+ and val._log_type in ["partitioned-table", "joined-table"]
+ ):
+ val.bind_to_run(run, key, namespace)
+
+ res = val.to_json(run)
+
+ if isinstance(val, wandb.Table) and val.log_mode == "INCREMENTAL":
+ # Set the _last_logged_idx AFTER the Table has been logged and
+ # bound to the run.
+ val._last_logged_idx = len(val.data) - 1
+ return res
+
+ return converted # type: ignore
+
+
+def _log_table_artifact(val: "Media", key: str, run: "LocalRun") -> None:
+ """Log a table to the run based on the table type and logging mode.
+
+ Creates and logs a `run_table` type for Table, PartitionedTable, and
+ JoinedTable values. For tables with log_mode="INCREMENTAL", creates and
+ logs an incremental artifact of type `wandb-run-incremental-table.`
+
+ Args:
+ val: A wbvalue with log_type "table", "partitioned-table",
+ or "joined-table."
+ key: The key used to log val.
+ run: The LocalRun used to log val.
+ """
+ from wandb.sdk.artifacts._internal_artifact import InternalArtifact
+
+ if isinstance(val, wandb.Table) and val.log_mode == "INCREMENTAL":
+ if (
+ run.resumed
+ and val._previous_increments_paths is None
+ and val._increment_num is None
+ ):
+ val._load_incremental_table_state_from_resumed_run(run, key)
+ else:
+ val._set_incremental_table_run_target(run)
+ art = incremental_table_util.init_artifact(run, key)
+ entry_name = incremental_table_util.get_entry_name(val, key)
+ else:
+ art = InternalArtifact(f"run-{run.id}-{key}", "run_table")
+ entry_name = key
+
+ art.add(val, entry_name)
+ run.log_artifact(art)
+
+
+def _prune_max_seq(seq: Sequence["BatchableMedia"]) -> Sequence["BatchableMedia"]:
+ # If media type has a max respect it
+ items = seq
+ if hasattr(seq[0], "MAX_ITEMS") and seq[0].MAX_ITEMS < len(seq):
+ logging.warning(
+ f"Only {seq[0].MAX_ITEMS} {seq[0].__class__.__name__} will be uploaded."
+ )
+ items = seq[: seq[0].MAX_ITEMS]
+ return items
+
+
+def _json_helper(val, artifact):
+ if isinstance(val, WBValue):
+ return val.to_json(artifact)
+ elif val.__class__ is dict:
+ res = {}
+ for key in val:
+ res[key] = _json_helper(val[key], artifact)
+ return res
+
+ if hasattr(val, "tolist"):
+ py_val = val.tolist()
+ if val.__class__.__name__ == "datetime64" and isinstance(py_val, int):
+ # when numpy datetime64 .tolist() returns an int, it is nanoseconds.
+ # need to convert to milliseconds
+ return _json_helper(py_val / int(1e6), artifact)
+ return _json_helper(py_val, artifact)
+ elif hasattr(val, "item"):
+ return _json_helper(val.item(), artifact)
+
+ if isinstance(val, datetime.datetime):
+ if val.tzinfo is None:
+ val = datetime.datetime(
+ val.year,
+ val.month,
+ val.day,
+ val.hour,
+ val.minute,
+ val.second,
+ val.microsecond,
+ tzinfo=datetime.timezone.utc,
+ )
+ return int(val.timestamp() * 1000)
+ elif isinstance(val, datetime.date):
+ return int(
+ datetime.datetime(
+ val.year, val.month, val.day, tzinfo=datetime.timezone.utc
+ ).timestamp()
+ * 1000
+ )
+ elif isinstance(val, (list, tuple)):
+ return [_json_helper(i, artifact) for i in val]
+ elif isinstance(val, Decimal):
+ return float(val)
+ else:
+ return util.json_friendly(val)[0]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/video.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/video.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e554927ca71a4705ad0f85d0389c8cecf20c883
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/data_types/video.py
@@ -0,0 +1,303 @@
+import functools
+import logging
+import os
+import pathlib
+from io import BytesIO
+from typing import TYPE_CHECKING, Any, Literal, Optional, Sequence, Type, Union
+
+import wandb
+from wandb import env, util
+from wandb.sdk import wandb_setup
+from wandb.sdk.lib import filesystem, printer, printer_asyncio, runid
+
+from . import _dtypes
+from ._private import MEDIA_TMP
+from .base_types.media import BatchableMedia
+
+if TYPE_CHECKING: # pragma: no cover
+ from typing import TextIO
+
+ import numpy as np
+
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ from ..wandb_run import Run as LocalRun
+
+
+def _should_print_spinner() -> bool:
+ settings = wandb_setup.singleton().settings_if_loaded
+ if settings and (settings.quiet or settings.silent):
+ return False
+
+ return not env.is_quiet() and not env.is_silent()
+
+
+# This helper function is a workaround for the issue discussed here:
+# https://github.com/wandb/wandb/issues/3472
+#
+# Essentially, the issue is that moviepy's write_gif function fails to close
+# the open write / file descriptor returned from `imageio.save`. The following
+# function is a simplified copy of the function in the moviepy source code.
+# See https://github.com/Zulko/moviepy/blob/7e3e8bb1b739eb6d1c0784b0cb2594b587b93b39/moviepy/video/io/gif_writers.py#L428
+#
+# Except, we close the writer!
+def write_gif_with_image_io(
+ clip: Any, filename: str, fps: Optional[int] = None
+) -> None:
+ from packaging.version import parse
+
+ imageio = util.get_module(
+ "imageio",
+ required='wandb.Video requires imageio when passing raw data. Install with "pip install wandb[media]"',
+ )
+
+ if parse(imageio.__version__) < parse("2.28.1"):
+ raise ValueError(
+ "imageio version 2.28.1 or higher is required to encode gifs. "
+ "Please upgrade imageio with `pip install imageio>=2.28.1`"
+ )
+
+ writer = imageio.save(
+ filename,
+ quantizer=0,
+ palettesize=256,
+ loop=0,
+ duration=1000 / clip.fps,
+ )
+
+ for frame in clip.iter_frames(fps=fps, dtype="uint8"):
+ writer.append_data(frame)
+
+ writer.close()
+
+
+class Video(BatchableMedia):
+ """A class for logging videos to W&B."""
+
+ _log_type = "video-file"
+ EXTS = ("gif", "mp4", "webm", "ogg")
+ _width: Optional[int]
+ _height: Optional[int]
+
+ def __init__(
+ self,
+ data_or_path: Union[str, pathlib.Path, "np.ndarray", "TextIO", "BytesIO"],
+ caption: Optional[str] = None,
+ fps: Optional[int] = None,
+ format: Optional[Literal["gif", "mp4", "webm", "ogg"]] = None,
+ ):
+ """Initialize a W&B Video object.
+
+ Args:
+ data_or_path: Video can be initialized with a path to a file or an io object.
+ Video can be initialized with a numpy tensor. The numpy tensor
+ must be either 4 dimensional or 5 dimensional.
+ The dimensions should be (number of frames, channel, height, width) or
+ (batch, number of frames, channel, height, width)
+ The format parameter must be specified with the format argument
+ when initializing with a numpy array
+ or io object.
+ caption: Caption associated with the video for display.
+ fps: The frame rate to use when encoding raw video frames.
+ Default value is 4.
+ This parameter has no effect when data_or_path is a string, or bytes.
+ format: Format of video, necessary if initializing with a numpy array
+ or io object. This parameter will be used to determine the format
+ to use when encoding the video data. Accepted values are "gif",
+ "mp4", "webm", or "ogg".
+ If no value is provided, the default format will be "gif".
+
+ Examples:
+ Log a numpy array as a video
+
+ ```python
+ import numpy as np
+ import wandb
+
+ with wandb.init() as run:
+ # axes are (number of frames, channel, height, width)
+ frames = np.random.randint(
+ low=0, high=256, size=(10, 3, 100, 100), dtype=np.uint8
+ )
+ run.log({"video": wandb.Video(frames, format="mp4", fps=4)})
+ ```
+ """
+ super().__init__(caption=caption)
+
+ if format is None:
+ wandb.termwarn(
+ "`format` argument was not provided, defaulting to `gif`. "
+ "This parameter will be required in v0.20.0, "
+ "please specify the format explicitly."
+ )
+ self._format = format or "gif"
+ self._width = None
+ self._height = None
+ self._channels = None
+ if self._format not in Video.EXTS:
+ raise ValueError(
+ "wandb.Video accepts {} formats".format(", ".join(Video.EXTS))
+ )
+
+ if isinstance(data_or_path, (BytesIO, str)) and fps:
+ msg = (
+ "`fps` argument does not affect the frame rate of the video "
+ "when providing a file path or raw bytes."
+ )
+ wandb.termwarn(msg)
+
+ if isinstance(data_or_path, BytesIO):
+ filename = os.path.join(
+ MEDIA_TMP.name, runid.generate_id() + "." + self._format
+ )
+ with open(filename, "wb") as f:
+ f.write(data_or_path.read())
+ self._set_file(filename, is_tmp=True)
+ elif isinstance(data_or_path, (str, pathlib.Path)):
+ data_or_path = str(data_or_path)
+
+ _, ext = os.path.splitext(data_or_path)
+ ext = ext[1:].lower()
+ if ext not in Video.EXTS:
+ raise ValueError(
+ "wandb.Video accepts {} formats".format(", ".join(Video.EXTS))
+ )
+ self._set_file(data_or_path, is_tmp=False)
+ # ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=p=0 data_or_path
+ else:
+ if hasattr(data_or_path, "numpy"): # TF data eager tensors
+ self.data = data_or_path.numpy()
+ elif util.is_numpy_array(data_or_path):
+ self.data = data_or_path
+ else:
+ raise ValueError(
+ "wandb.Video accepts a file path or numpy like data as input"
+ )
+ fps = fps or 4
+
+ if _should_print_spinner():
+ printer_asyncio.run_async_with_spinner(
+ printer.new_printer(),
+ "Encoding video...",
+ functools.partial(self.encode, fps=fps),
+ )
+ else:
+ self.encode(fps=fps)
+
+ def encode(self, fps: int = 4) -> None:
+ """Encode the video data to a file.
+
+
+ """
+ # import ImageSequenceClip from the appropriate MoviePy module
+ mpy = util.get_module(
+ "moviepy.video.io.ImageSequenceClip",
+ required='wandb.Video requires moviepy when passing raw data. Install with "pip install wandb[media]"',
+ )
+
+ tensor = self._prepare_video(self.data)
+ _, self._height, self._width, self._channels = tensor.shape # type: ignore
+
+ # encode sequence of images into gif string
+ clip = mpy.ImageSequenceClip(list(tensor), fps=fps)
+
+ filename = os.path.join(
+ MEDIA_TMP.name, runid.generate_id() + "." + self._format
+ )
+
+ if self._format == "gif":
+ write_gif_with_image_io(clip, filename)
+ else:
+ clip.write_videofile(filename, logger=None)
+
+ self._set_file(filename, is_tmp=True)
+
+ @classmethod
+ def get_media_subdir(cls: Type["Video"]) -> str:
+ """Get media subdirectory for video files.
+
+
+ """
+ return os.path.join("media", "videos")
+
+ def to_json(self, run_or_artifact: Union["LocalRun", "Artifact"]) -> dict:
+ """Returns the JSON representation expected by the backend.
+
+
+ """
+ json_dict = super().to_json(run_or_artifact)
+ json_dict["_type"] = self._log_type
+
+ if self._width is not None:
+ json_dict["width"] = self._width
+ if self._height is not None:
+ json_dict["height"] = self._height
+
+ return json_dict
+
+ def _prepare_video(self, video: "np.ndarray") -> "np.ndarray":
+ """This logic was mostly taken from tensorboardX."""
+ np = util.get_module(
+ "numpy",
+ required='wandb.Video requires numpy when passing raw data. To get it, run "pip install numpy".',
+ )
+ if video.ndim < 4:
+ raise ValueError(
+ "Video must be at least 4 dimensions: time, channels, height, width"
+ )
+ if video.ndim == 4:
+ video = video.reshape(1, *video.shape)
+ b, t, c, h, w = video.shape
+
+ if video.dtype != np.uint8:
+ logging.warning("Converting video data to uint8")
+ video = video.astype(np.uint8)
+
+ def is_power2(num: int) -> bool:
+ return num != 0 and ((num & (num - 1)) == 0)
+
+ # pad to nearest power of 2, all at once
+ if not is_power2(video.shape[0]):
+ len_addition = int(2 ** video.shape[0].bit_length() - video.shape[0])
+ video = np.concatenate(
+ (video, np.zeros(shape=(len_addition, t, c, h, w))), axis=0
+ )
+
+ n_rows = 2 ** ((b.bit_length() - 1) // 2)
+ n_cols = video.shape[0] // n_rows
+
+ video = video.reshape(n_rows, n_cols, t, c, h, w)
+ video = np.transpose(video, axes=(2, 0, 4, 1, 5, 3))
+ video = video.reshape(t, n_rows * h, n_cols * w, c)
+ return video
+
+ @classmethod
+ def seq_to_json(
+ cls: Type["Video"],
+ seq: Sequence["BatchableMedia"],
+ run: "LocalRun",
+ key: str,
+ step: Union[int, str],
+ ) -> dict:
+ """Convert a sequence of Video objects to a JSON representation.
+
+
+ """
+ base_path = os.path.join(run.dir, cls.get_media_subdir())
+ filesystem.mkdir_exists_ok(base_path)
+
+ meta = {
+ "_type": "videos",
+ "count": len(seq),
+ "videos": [v.to_json(run) for v in seq],
+ "captions": Video.captions(seq),
+ }
+ return meta
+
+
+class _VideoFileType(_dtypes.Type):
+ name = "video-file"
+ types = [Video]
+
+
+_dtypes.TypeRegistry.add(_VideoFileType)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/integration_utils/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/integration_utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/integration_utils/auto_logging.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/integration_utils/auto_logging.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c3d36b9ce29299fdf2cc3d72b8878ab2e4db9ba
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/integration_utils/auto_logging.py
@@ -0,0 +1,232 @@
+import asyncio
+import functools
+import inspect
+import logging
+from typing import Any, Dict, Optional, Protocol, Sequence, TypeVar
+
+import wandb.sdk
+import wandb.util
+from wandb.sdk.lib import telemetry as wb_telemetry
+from wandb.sdk.lib.timer import Timer
+
+logger = logging.getLogger(__name__)
+
+
+AutologInitArgs = Optional[Dict[str, Any]]
+
+
+K = TypeVar("K", bound=str)
+V = TypeVar("V")
+
+
+class Response(Protocol[K, V]):
+ def __getitem__(self, key: K) -> V: ... # pragma: no cover
+
+ def get(
+ self, key: K, default: Optional[V] = None
+ ) -> Optional[V]: ... # pragma: no cover
+
+
+class ArgumentResponseResolver(Protocol):
+ def __call__(
+ self,
+ args: Sequence[Any],
+ kwargs: Dict[str, Any],
+ response: Response,
+ start_time: float,
+ time_elapsed: float,
+ ) -> Optional[Dict[str, Any]]: ... # pragma: no cover
+
+
+class PatchAPI:
+ def __init__(
+ self,
+ name: str,
+ symbols: Sequence[str],
+ resolver: ArgumentResponseResolver,
+ ) -> None:
+ """Patches the API to log wandb Media or metrics."""
+ # name of the LLM provider, e.g. "Cohere" or "OpenAI" or package name like "Transformers"
+ self.name = name
+ # api library name, e.g. "cohere" or "openai" or "transformers"
+ self._api = None
+ # dictionary of original methods
+ self.original_methods: Dict[str, Any] = {}
+ # list of symbols to patch, e.g. ["Client.generate", "Edit.create"] or ["Pipeline.__call__"]
+ self.symbols = symbols
+ # resolver callable to convert args/response into a dictionary of wandb media objects or metrics
+ self.resolver = resolver
+
+ @property
+ def set_api(self) -> Any:
+ """Returns the API module."""
+ lib_name = self.name.lower()
+ if self._api is None:
+ self._api = wandb.util.get_module(
+ name=lib_name,
+ required=f"To use the W&B {self.name} Autolog, "
+ f"you need to have the `{lib_name}` python "
+ f"package installed. Please install it with `pip install {lib_name}`.",
+ lazy=False,
+ )
+ return self._api
+
+ def patch(self, run: "wandb.Run") -> None:
+ """Patches the API to log media or metrics to W&B."""
+ for symbol in self.symbols:
+ # split on dots, e.g. "Client.generate" -> ["Client", "generate"]
+ symbol_parts = symbol.split(".")
+ # and get the attribute from the module
+ original = functools.reduce(getattr, symbol_parts, self.set_api)
+
+ def method_factory(original_method: Any):
+ async def async_method(*args, **kwargs):
+ future = asyncio.Future()
+
+ async def callback(coro):
+ try:
+ result = await coro
+ loggable_dict = self.resolver(
+ args, kwargs, result, timer.start_time, timer.elapsed
+ )
+ if loggable_dict is not None:
+ run.log(loggable_dict)
+ future.set_result(result)
+ except Exception as e:
+ logger.warning(e)
+
+ with Timer() as timer:
+ coro = original_method(*args, **kwargs)
+ asyncio.ensure_future(callback(coro))
+
+ return await future
+
+ def sync_method(*args, **kwargs):
+ with Timer() as timer:
+ result = original_method(*args, **kwargs)
+ try:
+ loggable_dict = self.resolver(
+ args, kwargs, result, timer.start_time, timer.elapsed
+ )
+ if loggable_dict is not None:
+ run.log(loggable_dict)
+ except Exception as e:
+ logger.warning(e)
+ return result
+
+ if inspect.iscoroutinefunction(original_method):
+ return functools.wraps(original_method)(async_method)
+ else:
+ return functools.wraps(original_method)(sync_method)
+
+ # save original method
+ self.original_methods[symbol] = original
+ # monkey patch the method
+ if len(symbol_parts) == 1:
+ setattr(self.set_api, symbol_parts[0], method_factory(original))
+ else:
+ setattr(
+ functools.reduce(getattr, symbol_parts[:-1], self.set_api),
+ symbol_parts[-1],
+ method_factory(original),
+ )
+
+ def unpatch(self) -> None:
+ """Unpatches the API."""
+ for symbol, original in self.original_methods.items():
+ # split on dots, e.g. "Client.generate" -> ["Client", "generate"]
+ symbol_parts = symbol.split(".")
+ # unpatch the method
+ if len(symbol_parts) == 1:
+ setattr(self.set_api, symbol_parts[0], original)
+ else:
+ setattr(
+ functools.reduce(getattr, symbol_parts[:-1], self.set_api),
+ symbol_parts[-1],
+ original,
+ )
+
+
+class AutologAPI:
+ def __init__(
+ self,
+ name: str,
+ symbols: Sequence[str],
+ resolver: ArgumentResponseResolver,
+ telemetry_feature: Optional[str] = None,
+ ) -> None:
+ """Autolog API calls to W&B."""
+ self._telemetry_feature = telemetry_feature
+ self._patch_api = PatchAPI(
+ name=name,
+ symbols=symbols,
+ resolver=resolver,
+ )
+ self._name = self._patch_api.name
+ self._run: Optional[wandb.Run] = None
+ self.__run_created_by_autolog: bool = False
+
+ @property
+ def _is_enabled(self) -> bool:
+ """Returns whether autologging is enabled."""
+ return self._run is not None
+
+ def __call__(self, init: AutologInitArgs = None) -> None:
+ """Enable autologging."""
+ self.enable(init=init)
+
+ def _run_init(self, init: AutologInitArgs = None) -> None:
+ """Handle wandb run initialization."""
+ # - autolog(init: dict = {...}) calls wandb.init(**{...})
+ # regardless of whether there is a wandb.run or not,
+ # we only track if the run was created by autolog
+ # - todo: autolog(init: dict | run = run) would use the user-provided run
+ # - autolog() uses the wandb.run if there is one, otherwise it calls wandb.init()
+ if init:
+ _wandb_run = wandb.run
+ # we delegate dealing with the init dict to wandb.init()
+ self._run = wandb.init(**init)
+ if _wandb_run != self._run:
+ self.__run_created_by_autolog = True
+ elif wandb.run is None:
+ self._run = wandb.init()
+ self.__run_created_by_autolog = True
+ else:
+ self._run = wandb.run
+
+ def enable(self, init: AutologInitArgs = None) -> None:
+ """Enable autologging.
+
+ Args:
+ init: Optional dictionary of arguments to pass to wandb.init().
+
+ """
+ if self._is_enabled:
+ logger.info(
+ f"{self._name} autologging is already enabled, disabling and re-enabling."
+ )
+ self.disable()
+
+ logger.info(f"Enabling {self._name} autologging.")
+ self._run_init(init=init)
+
+ self._patch_api.patch(self._run)
+
+ if self._telemetry_feature:
+ with wb_telemetry.context(self._run) as tel:
+ setattr(tel.feature, self._telemetry_feature, True)
+
+ def disable(self) -> None:
+ """Disable autologging."""
+ if self._run is None:
+ return
+
+ logger.info(f"Disabling {self._name} autologging.")
+
+ if self.__run_created_by_autolog:
+ self._run.finish()
+ self.__run_created_by_autolog = False
+
+ self._run = None
+
+ self._patch_api.unpatch()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/integration_utils/data_logging.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/integration_utils/data_logging.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0b971cc17211228132698f4279b7b7db1a81bed
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/integration_utils/data_logging.py
@@ -0,0 +1,475 @@
+# wandb.integrations.data_logging.py
+#
+# Contains common utility functions that enable
+# logging datasets and predictions to wandb.
+import sys
+from collections.abc import Sequence
+from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
+
+import wandb
+
+if TYPE_CHECKING:
+ from wandb.data_types import _TableIndex
+
+CAN_INFER_IMAGE_AND_VIDEO = sys.version_info.major == 3 and sys.version_info.minor >= 5
+
+
+class ValidationDataLogger:
+ """Logs validation data as a wandb.Table.
+
+ ValidationDataLogger is intended to be used inside of library integrations
+ in order to facilitate the process of optionally building a validation dataset
+ and logging periodic predictions against such validation data using WandB best
+ practices.
+ """
+
+ validation_inputs: Union[Sequence, Dict[str, Sequence]]
+ validation_targets: Optional[Union[Sequence, Dict[str, Sequence]]]
+ validation_indexes: List["_TableIndex"]
+ prediction_row_processor: Optional[Callable]
+ class_labels_table: Optional["wandb.Table"]
+ infer_missing_processors: bool
+
+ def __init__(
+ self,
+ inputs: Union[Sequence, Dict[str, Sequence]],
+ targets: Optional[Union[Sequence, Dict[str, Sequence]]] = None,
+ indexes: Optional[List["_TableIndex"]] = None,
+ validation_row_processor: Optional[Callable] = None,
+ prediction_row_processor: Optional[Callable] = None,
+ input_col_name: str = "input",
+ target_col_name: str = "target",
+ table_name: str = "wb_validation_data",
+ artifact_type: str = "validation_dataset",
+ class_labels: Optional[List[str]] = None,
+ infer_missing_processors: bool = True,
+ ) -> None:
+ """Initialize a new ValidationDataLogger.
+
+ Args:
+ inputs: A list of input vectors or dictionary of lists of input vectors
+ (used if the model has multiple named inputs)
+ targets: A list of target vectors or dictionary of lists of target vectors
+ (used if the model has multiple named targets/putputs). Defaults to `None`.
+ `targets` and `indexes` cannot both be `None`.
+ indexes: An ordered list of `wandb.data_types._TableIndex` mapping the
+ input items to their source table. This is most commonly retrieved by using
+ `indexes = my_data_table.get_index()`. Defaults to `None`. `targets`
+ and `indexes` cannot both be `None`.
+ validation_row_processor: A function to apply to the validation data,
+ commonly used to visualize the data. The function will receive an `ndx` (`int`)
+ and a `row` (`dict`). If `inputs` is a list, then `row["input"]` will be the input
+ data for the row. Else, it will be keyed based on the name of the input slot
+ (corresponding to `inputs`). If `targets` is a list, then
+ `row["target"]` will be the target data for the row. Else, it will
+ be keyed based on `targets`. For example, if your input data is a
+ single ndarray, but you wish to visualize the data as an image,
+ then you can provide `lambda ndx, row: {"img": wandb.Image(row["input"])}`
+ as the processor. If `None`, we will try to guess the appropriate processor.
+ Ignored if `log_evaluation` is `False` or `val_keys` are present. Defaults to `None`.
+ prediction_row_processor: Same as validation_row_processor, but applied to the
+ model's output. `row["output"]` will contain the results of the model output.
+ Defaults to `None`.
+ input_col_name: The name to use for the input column.
+ Defaults to `"input"`.
+ target_col_name: The name to use for the target column.
+ Defaults to `"target"`.
+ table_name: The name to use for the validation table.
+ Defaults to `"wb_validation_data"`.
+ artifact_type: The artifact type to use for the validation data.
+ Defaults to `"validation_dataset"`.
+ class_labels: Optional list of labels to use in the inferred
+ processors. If the model's `target` or `output` is inferred to be a class,
+ we will attempt to map the class to these labels. Defaults to `None`.
+ infer_missing_processors: Determines if processors are inferred if
+ they are missing. Defaults to True.
+ """
+ class_labels_table: Optional[wandb.Table]
+ if isinstance(class_labels, list) and len(class_labels) > 0:
+ class_labels_table = wandb.Table(
+ columns=["label"], data=[[label] for label in class_labels]
+ )
+ else:
+ class_labels_table = None
+
+ if indexes is None:
+ assert targets is not None
+ local_validation_table = wandb.Table(columns=[], data=[])
+
+ if isinstance(targets, dict):
+ for col_name in targets:
+ local_validation_table.add_column(col_name, targets[col_name])
+ else:
+ local_validation_table.add_column(target_col_name, targets)
+
+ if isinstance(inputs, dict):
+ for col_name in inputs:
+ local_validation_table.add_column(col_name, inputs[col_name])
+ else:
+ local_validation_table.add_column(input_col_name, inputs)
+
+ if validation_row_processor is None and infer_missing_processors:
+ example_input = _make_example(inputs)
+ example_target = _make_example(targets)
+ if example_input is not None and example_target is not None:
+ validation_row_processor = _infer_validation_row_processor(
+ example_input,
+ example_target,
+ class_labels_table,
+ input_col_name,
+ target_col_name,
+ )
+
+ if validation_row_processor is not None:
+ local_validation_table.add_computed_columns(validation_row_processor)
+
+ local_validation_artifact = wandb.Artifact(table_name, artifact_type)
+ local_validation_artifact.add(local_validation_table, "validation_data")
+ if wandb.run:
+ wandb.run.use_artifact(local_validation_artifact)
+ indexes = local_validation_table.get_index()
+ else:
+ local_validation_artifact = None
+
+ self.class_labels_table = class_labels_table
+ self.validation_inputs = inputs
+ self.validation_targets = targets
+ self.validation_indexes = indexes
+ self.prediction_row_processor = prediction_row_processor
+ self.infer_missing_processors = infer_missing_processors
+ self.local_validation_artifact = local_validation_artifact
+ self.input_col_name = input_col_name
+
+ def make_predictions(
+ self, predict_fn: Callable
+ ) -> Union[Sequence, Dict[str, Sequence]]:
+ """Produce predictions by passing `validation_inputs` to `predict_fn`.
+
+ Args:
+ predict_fn (Callable): Any function which can accept `validation_inputs` and produce
+ a list of vectors or dictionary of lists of vectors
+
+ Returns:
+ (Sequence | Dict[str, Sequence]): The returned value of predict_fn
+ """
+ return predict_fn(self.validation_inputs)
+
+ def log_predictions(
+ self,
+ predictions: Union[Sequence, Dict[str, Sequence]],
+ prediction_col_name: str = "output",
+ val_ndx_col_name: str = "val_row",
+ table_name: str = "validation_predictions",
+ commit: bool = True,
+ ) -> wandb.data_types.Table:
+ """Log a set of predictions.
+
+ Intended usage:
+
+ vl.log_predictions(vl.make_predictions(self.model.predict))
+
+ Args:
+ predictions (Sequence | Dict[str, Sequence]): A list of prediction vectors or dictionary
+ of lists of prediction vectors
+ prediction_col_name (str, optional): the name of the prediction column. Defaults to "output".
+ val_ndx_col_name (str, optional): The name of the column linking prediction table
+ to the validation ata table. Defaults to "val_row".
+ table_name (str, optional): name of the prediction table. Defaults to "validation_predictions".
+ commit (bool, optional): determines if commit should be called on the logged data. Defaults to False.
+ """
+ pred_table = wandb.Table(columns=[], data=[])
+ if isinstance(predictions, dict):
+ for col_name in predictions:
+ pred_table.add_column(col_name, predictions[col_name])
+ else:
+ pred_table.add_column(prediction_col_name, predictions)
+ pred_table.add_column(val_ndx_col_name, self.validation_indexes)
+
+ if self.prediction_row_processor is None and self.infer_missing_processors:
+ example_prediction = _make_example(predictions)
+ example_input = _make_example(self.validation_inputs)
+ if example_prediction is not None and example_input is not None:
+ self.prediction_row_processor = _infer_prediction_row_processor(
+ example_prediction,
+ example_input,
+ self.class_labels_table,
+ self.input_col_name,
+ prediction_col_name,
+ )
+
+ if self.prediction_row_processor is not None:
+ pred_table.add_computed_columns(self.prediction_row_processor)
+
+ wandb.log({table_name: pred_table}, commit=commit)
+ return pred_table
+
+
+def _make_example(data: Any) -> Optional[Union[Dict, Sequence, Any]]:
+ """Used to make an example input, target, or output."""
+ example: Optional[Union[Dict, Sequence, Any]]
+
+ if isinstance(data, dict):
+ example = {}
+ for key in data:
+ example[key] = data[key][0]
+ elif hasattr(data, "__len__"):
+ example = data[0]
+ else:
+ example = None
+
+ return example
+
+
+def _get_example_shape(example: Union[Sequence, Any]):
+ """Get the shape of an object if applicable."""
+ shape = []
+ if not isinstance(example, str) and hasattr(example, "__len__"):
+ length = len(example)
+ shape = [length]
+ if length > 0:
+ shape += _get_example_shape(example[0])
+ return shape
+
+
+def _bind(lambda_fn: Callable, **closure_kwargs: Any) -> Callable:
+ """Create a closure around a lambda function by binding `closure_kwargs` to the function."""
+
+ def closure(*args: Any, **kwargs: Any) -> Any:
+ _k = {}
+ _k.update(kwargs)
+ _k.update(closure_kwargs)
+ return lambda_fn(*args, **_k)
+
+ return closure
+
+
+def _infer_single_example_keyed_processor(
+ example: Union[Sequence, Any],
+ class_labels_table: Optional["wandb.Table"] = None,
+ possible_base_example: Optional[Union[Sequence, Any]] = None,
+) -> Dict[str, Callable]:
+ """Infers a processor from a single example.
+
+ Infers a processor from a single example with optional class_labels_table
+ and base_example. Base example is useful for cases such as segmentation masks
+ """
+ shape = _get_example_shape(example)
+ processors: Dict[str, Callable] = {}
+ if (
+ class_labels_table is not None
+ and len(shape) == 1
+ and shape[0] == len(class_labels_table.data)
+ ):
+ np = wandb.util.get_module(
+ "numpy",
+ required="Inferring processors require numpy",
+ )
+ # Assume these are logits
+ class_names = class_labels_table.get_column("label")
+
+ processors["max_class"] = lambda n, d, p: class_labels_table.index_ref( # type: ignore
+ np.argmax(d)
+ )
+ # TODO: Consider adding back if users ask
+ # processors["min_class"] = lambda n, d, p: class_labels_table.index_ref( # type: ignore
+ # np.argmin(d)
+ # )
+
+ values = np.unique(example)
+ is_one_hot = len(values) == 2 and set(values) == {0, 1}
+ if not is_one_hot:
+ processors["score"] = lambda n, d, p: {
+ class_names[i]: d[i] for i in range(shape[0])
+ }
+ elif (
+ len(shape) == 1
+ and shape[0] == 1
+ and (
+ isinstance(example[0], int)
+ or (hasattr(example, "tolist") and isinstance(example.tolist()[0], int)) # type: ignore
+ )
+ ):
+ # assume this is a class
+ if class_labels_table is not None:
+ processors["class"] = (
+ lambda n, d, p: class_labels_table.index_ref(d[0])
+ if d[0] < len(class_labels_table.data)
+ else d[0]
+ ) # type: ignore
+ else:
+ processors["val"] = lambda n, d, p: d[0]
+ elif len(shape) == 1:
+ np = wandb.util.get_module(
+ "numpy",
+ required="Inferring processors require numpy",
+ )
+ # This could be anything
+ if shape[0] <= 10:
+ # if less than 10, fan out the results
+ # processors["node"] = lambda n, d, p: {i: d[i] for i in range(shape[0])}
+ processors["node"] = lambda n, d, p: [
+ d[i].tolist() if hasattr(d[i], "tolist") else d[i]
+ for i in range(shape[0])
+ ]
+ # just report the argmax and argmin
+ processors["argmax"] = lambda n, d, p: np.argmax(d)
+
+ values = np.unique(example)
+ is_one_hot = len(values) == 2 and set(values) == {0, 1}
+ if not is_one_hot:
+ processors["argmin"] = lambda n, d, p: np.argmin(d)
+ elif len(shape) == 2 and CAN_INFER_IMAGE_AND_VIDEO:
+ if (
+ class_labels_table is not None
+ and possible_base_example is not None
+ and shape == _get_example_shape(possible_base_example)
+ ):
+ # consider this a segmentation mask
+ processors["image"] = lambda n, d, p: wandb.Image(
+ p,
+ masks={
+ "masks": {
+ "mask_data": d,
+ "class_labels": class_labels_table.get_column("label"), # type: ignore
+ }
+ },
+ )
+ else:
+ # consider this a 2d image
+ processors["image"] = lambda n, d, p: wandb.Image(d)
+ elif len(shape) == 3 and CAN_INFER_IMAGE_AND_VIDEO:
+ # consider this an image
+ processors["image"] = lambda n, d, p: wandb.Image(d)
+ elif len(shape) == 4 and CAN_INFER_IMAGE_AND_VIDEO:
+ # consider this a video
+ processors["video"] = lambda n, d, p: wandb.Video(d)
+
+ return processors
+
+
+def _infer_validation_row_processor(
+ example_input: Union[Dict, Sequence],
+ example_target: Union[Dict, Sequence, Any],
+ class_labels_table: Optional["wandb.Table"] = None,
+ input_col_name: str = "input",
+ target_col_name: str = "target",
+) -> Callable:
+ """Infers the composite processor for the validation data."""
+ single_processors = {}
+ if isinstance(example_input, dict):
+ for key in example_input:
+ key_processors = _infer_single_example_keyed_processor(example_input[key])
+ for p_key in key_processors:
+ single_processors[f"{key}:{p_key}"] = _bind(
+ lambda ndx, row, key_processor, key: key_processor(
+ ndx,
+ row[key],
+ None,
+ ),
+ key_processor=key_processors[p_key],
+ key=key,
+ )
+ else:
+ key = input_col_name
+ key_processors = _infer_single_example_keyed_processor(example_input)
+ for p_key in key_processors:
+ single_processors[f"{key}:{p_key}"] = _bind(
+ lambda ndx, row, key_processor, key: key_processor(
+ ndx,
+ row[key],
+ None,
+ ),
+ key_processor=key_processors[p_key],
+ key=key,
+ )
+
+ if isinstance(example_target, dict):
+ for key in example_target:
+ key_processors = _infer_single_example_keyed_processor(
+ example_target[key], class_labels_table
+ )
+ for p_key in key_processors:
+ single_processors[f"{key}:{p_key}"] = _bind(
+ lambda ndx, row, key_processor, key: key_processor(
+ ndx,
+ row[key],
+ None,
+ ),
+ key_processor=key_processors[p_key],
+ key=key,
+ )
+ else:
+ key = target_col_name
+ key_processors = _infer_single_example_keyed_processor(
+ example_target,
+ class_labels_table,
+ example_input if not isinstance(example_input, dict) else None,
+ )
+ for p_key in key_processors:
+ single_processors[f"{key}:{p_key}"] = _bind(
+ lambda ndx, row, key_processor, key: key_processor(
+ ndx,
+ row[key],
+ row[input_col_name]
+ if not isinstance(example_input, dict)
+ else None,
+ ),
+ key_processor=key_processors[p_key],
+ key=key,
+ )
+
+ def processor(ndx, row):
+ return {key: single_processors[key](ndx, row) for key in single_processors}
+
+ return processor
+
+
+def _infer_prediction_row_processor(
+ example_prediction: Union[Dict, Sequence],
+ example_input: Union[Dict, Sequence],
+ class_labels_table: Optional["wandb.Table"] = None,
+ input_col_name: str = "input",
+ output_col_name: str = "output",
+) -> Callable:
+ """Infers the composite processor for the prediction output data."""
+ single_processors = {}
+
+ if isinstance(example_prediction, dict):
+ for key in example_prediction:
+ key_processors = _infer_single_example_keyed_processor(
+ example_prediction[key], class_labels_table
+ )
+ for p_key in key_processors:
+ single_processors[f"{key}:{p_key}"] = _bind(
+ lambda ndx, row, key_processor, key: key_processor(
+ ndx,
+ row[key],
+ None,
+ ),
+ key_processor=key_processors[p_key],
+ key=key,
+ )
+ else:
+ key = output_col_name
+ key_processors = _infer_single_example_keyed_processor(
+ example_prediction,
+ class_labels_table,
+ example_input if not isinstance(example_input, dict) else None,
+ )
+ for p_key in key_processors:
+ single_processors[f"{key}:{p_key}"] = _bind(
+ lambda ndx, row, key_processor, key: key_processor(
+ ndx,
+ row[key],
+ ndx.get_row().get("val_row").get_row().get(input_col_name)
+ if not isinstance(example_input, dict)
+ else None,
+ ),
+ key_processor=key_processors[p_key],
+ key=key,
+ )
+
+ def processor(ndx, row):
+ return {key: single_processors[key](ndx, row) for key in single_processors}
+
+ return processor
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/interface/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/interface/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/interface/constants.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/interface/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..09fe1e26f0ce72e23df8b627ff15e332f6ebc4e6
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/interface/constants.py
@@ -0,0 +1,4 @@
+#
+NOTIFY_PROCESS = 1
+NOTIFY_SHUTDOWN = 2
+NOTIFY_REQUEST = 3
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/interface/interface.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/interface/interface.py
new file mode 100644
index 0000000000000000000000000000000000000000..37bd050a0097a94a5847bcb1b0df9d10ca54ef07
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/interface/interface.py
@@ -0,0 +1,1093 @@
+"""Interface base class - Used to send messages to the internal process.
+
+InterfaceBase: The abstract class
+InterfaceShared: Common routines for socket and queue based implementations
+InterfaceQueue: Use multiprocessing queues to send and receive messages
+InterfaceSock: Use socket to send and receive messages
+"""
+
+import gzip
+import logging
+import time
+from abc import abstractmethod
+from pathlib import Path
+from secrets import token_hex
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Dict,
+ Iterable,
+ List,
+ Literal,
+ NewType,
+ Optional,
+ Tuple,
+ TypedDict,
+ Union,
+)
+
+from wandb import termwarn
+from wandb.proto import wandb_internal_pb2 as pb
+from wandb.proto import wandb_telemetry_pb2 as tpb
+from wandb.sdk.artifacts.artifact import Artifact
+from wandb.sdk.artifacts.artifact_manifest import ArtifactManifest
+from wandb.sdk.artifacts.staging import get_staging_dir
+from wandb.sdk.lib import json_util as json
+from wandb.sdk.mailbox import HandleAbandonedError, MailboxHandle
+from wandb.util import (
+ WandBJSONEncoderOld,
+ get_h5_typename,
+ json_dumps_safer,
+ json_dumps_safer_history,
+ json_friendly,
+ json_friendly_val,
+ maybe_compress_summary,
+)
+
+from ..data_types.utils import history_dict_to_json, val_to_json
+from . import summary_record as sr
+
+MANIFEST_FILE_SIZE_THRESHOLD = 100_000
+
+GlobStr = NewType("GlobStr", str)
+
+
+PolicyName = Literal["now", "live", "end"]
+
+
+class FilesDict(TypedDict):
+ files: Iterable[Tuple[GlobStr, PolicyName]]
+
+
+if TYPE_CHECKING:
+ from ..wandb_run import Run
+
+
+logger = logging.getLogger("wandb")
+
+
+def file_policy_to_enum(policy: "PolicyName") -> "pb.FilesItem.PolicyType.V":
+ if policy == "now":
+ enum = pb.FilesItem.PolicyType.NOW
+ elif policy == "end":
+ enum = pb.FilesItem.PolicyType.END
+ elif policy == "live":
+ enum = pb.FilesItem.PolicyType.LIVE
+ return enum
+
+
+def file_enum_to_policy(enum: "pb.FilesItem.PolicyType.V") -> "PolicyName":
+ if enum == pb.FilesItem.PolicyType.NOW:
+ policy: PolicyName = "now"
+ elif enum == pb.FilesItem.PolicyType.END:
+ policy = "end"
+ elif enum == pb.FilesItem.PolicyType.LIVE:
+ policy = "live"
+ return policy
+
+
+class InterfaceBase:
+ """Methods for sending different types of Records to the service.
+
+ None of the methods may be called from an asyncio context other than
+ deliver_async().
+ """
+
+ _drop: bool
+
+ def __init__(self) -> None:
+ self._drop = False
+
+ @abstractmethod
+ async def deliver_async(
+ self,
+ record: pb.Record,
+ ) -> MailboxHandle[pb.Result]:
+ """Send a record and create a handle to wait for the response.
+
+ The synchronous publish and deliver methods on this class cannot be
+ called in the asyncio thread because they block. Instead of having
+ an async copy of every method, this is a general method for sending
+ any kind of record in the asyncio thread.
+
+ Args:
+ record: The record to send. This method takes ownership of the
+ record and it must not be used afterward.
+
+ Returns:
+ A handle to wait for a response to the record.
+ """
+ raise NotImplementedError
+
+ def publish_header(self) -> None:
+ header = pb.HeaderRecord()
+ self._publish_header(header)
+
+ @abstractmethod
+ def _publish_header(self, header: pb.HeaderRecord) -> None:
+ raise NotImplementedError
+
+ def deliver_status(self) -> MailboxHandle[pb.Result]:
+ return self._deliver_status(pb.StatusRequest())
+
+ @abstractmethod
+ def _deliver_status(
+ self,
+ status: pb.StatusRequest,
+ ) -> MailboxHandle[pb.Result]:
+ raise NotImplementedError
+
+ def _make_config(
+ self,
+ data: Optional[dict] = None,
+ key: Optional[Union[Tuple[str, ...], str]] = None,
+ val: Optional[Any] = None,
+ obj: Optional[pb.ConfigRecord] = None,
+ ) -> pb.ConfigRecord:
+ config = obj or pb.ConfigRecord()
+ if data:
+ for k, v in data.items():
+ update = config.update.add()
+ update.key = k
+ update.value_json = json_dumps_safer(json_friendly(v)[0])
+ if key:
+ update = config.update.add()
+ if isinstance(key, tuple):
+ for k in key:
+ update.nested_key.append(k)
+ else:
+ update.key = key
+ update.value_json = json_dumps_safer(json_friendly(val)[0])
+ return config
+
+ def _make_run(self, run: "Run") -> pb.RunRecord: # noqa: C901
+ proto_run = pb.RunRecord()
+ if run._settings.entity is not None:
+ proto_run.entity = run._settings.entity
+ if run._settings.project is not None:
+ proto_run.project = run._settings.project
+ if run._settings.run_group is not None:
+ proto_run.run_group = run._settings.run_group
+ if run._settings.run_job_type is not None:
+ proto_run.job_type = run._settings.run_job_type
+ if run._settings.run_id is not None:
+ proto_run.run_id = run._settings.run_id
+ if run._settings.run_name is not None:
+ proto_run.display_name = run._settings.run_name
+ if run._settings.run_notes is not None:
+ proto_run.notes = run._settings.run_notes
+ if run._settings.run_tags is not None:
+ proto_run.tags.extend(run._settings.run_tags)
+ if run._start_time is not None:
+ proto_run.start_time.FromMicroseconds(int(run._start_time * 1e6))
+ if run._starting_step is not None:
+ proto_run.starting_step = run._starting_step
+ if run._settings.git_remote_url is not None:
+ proto_run.git.remote_url = run._settings.git_remote_url
+ if run._settings.git_commit is not None:
+ proto_run.git.commit = run._settings.git_commit
+ if run._settings.sweep_id is not None:
+ proto_run.sweep_id = run._settings.sweep_id
+ if run._settings.host:
+ proto_run.host = run._settings.host
+ if run._settings.resumed:
+ proto_run.resumed = run._settings.resumed
+ if run._settings.fork_from:
+ run_moment = run._settings.fork_from
+ proto_run.branch_point.run = run_moment.run
+ proto_run.branch_point.metric = run_moment.metric
+ proto_run.branch_point.value = run_moment.value
+ if run._settings.resume_from:
+ run_moment = run._settings.resume_from
+ proto_run.branch_point.run = run_moment.run
+ proto_run.branch_point.metric = run_moment.metric
+ proto_run.branch_point.value = run_moment.value
+ if run._forked:
+ proto_run.forked = run._forked
+ if run._config is not None:
+ config_dict = run._config._as_dict() # type: ignore
+ self._make_config(data=config_dict, obj=proto_run.config)
+ if run._telemetry_obj:
+ proto_run.telemetry.MergeFrom(run._telemetry_obj)
+ if run._start_runtime:
+ proto_run.runtime = run._start_runtime
+ return proto_run
+
+ def publish_run(self, run: "Run") -> None:
+ run_record = self._make_run(run)
+ self._publish_run(run_record)
+
+ @abstractmethod
+ def _publish_run(self, run: pb.RunRecord) -> None:
+ raise NotImplementedError
+
+ def publish_cancel(self, cancel_slot: str) -> None:
+ cancel = pb.CancelRequest(cancel_slot=cancel_slot)
+ self._publish_cancel(cancel)
+
+ @abstractmethod
+ def _publish_cancel(self, cancel: pb.CancelRequest) -> None:
+ raise NotImplementedError
+
+ def publish_config(
+ self,
+ data: Optional[dict] = None,
+ key: Optional[Union[Tuple[str, ...], str]] = None,
+ val: Optional[Any] = None,
+ ) -> None:
+ cfg = self._make_config(data=data, key=key, val=val)
+
+ self._publish_config(cfg)
+
+ @abstractmethod
+ def _publish_config(self, cfg: pb.ConfigRecord) -> None:
+ raise NotImplementedError
+
+ @abstractmethod
+ def _publish_metric(self, metric: pb.MetricRecord) -> None:
+ raise NotImplementedError
+
+ def _make_summary_from_dict(self, summary_dict: dict) -> pb.SummaryRecord:
+ summary = pb.SummaryRecord()
+ for k, v in summary_dict.items():
+ update = summary.update.add()
+ update.key = k
+ update.value_json = json.dumps(v)
+ return summary
+
+ def _summary_encode(
+ self,
+ value: Any,
+ path_from_root: str,
+ run: "Run",
+ ) -> dict:
+ """Normalize, compress, and encode sub-objects for backend storage.
+
+ value: Object to encode.
+ path_from_root: `str` dot separated string from the top-level summary to the
+ current `value`.
+
+ Returns:
+ A new tree of dict's with large objects replaced with dictionaries
+ with "_type" entries that say which type the original data was.
+ """
+ # Constructs a new `dict` tree in `json_value` that discards and/or
+ # encodes objects that aren't JSON serializable.
+
+ if isinstance(value, dict):
+ json_value = {}
+ for key, value in value.items(): # noqa: B020
+ json_value[key] = self._summary_encode(
+ value,
+ path_from_root + "." + key,
+ run=run,
+ )
+ return json_value
+ else:
+ friendly_value, converted = json_friendly(
+ val_to_json(run, path_from_root, value, namespace="summary")
+ )
+ json_value, compressed = maybe_compress_summary(
+ friendly_value, get_h5_typename(value)
+ )
+ if compressed:
+ # TODO(jhr): impleement me
+ pass
+ # self.write_h5(path_from_root, friendly_value)
+
+ return json_value
+
+ def _make_summary(
+ self,
+ summary_record: sr.SummaryRecord,
+ run: "Run",
+ ) -> pb.SummaryRecord:
+ pb_summary_record = pb.SummaryRecord()
+
+ for item in summary_record.update:
+ pb_summary_item = pb_summary_record.update.add()
+ key_length = len(item.key)
+
+ assert key_length > 0
+
+ if key_length > 1:
+ pb_summary_item.nested_key.extend(item.key)
+ else:
+ pb_summary_item.key = item.key[0]
+
+ path_from_root = ".".join(item.key)
+ json_value = self._summary_encode(
+ item.value,
+ path_from_root,
+ run=run,
+ )
+ json_value, _ = json_friendly(json_value) # type: ignore
+
+ pb_summary_item.value_json = json.dumps(
+ json_value,
+ cls=WandBJSONEncoderOld,
+ )
+
+ for item in summary_record.remove:
+ pb_summary_item = pb_summary_record.remove.add()
+ key_length = len(item.key)
+
+ assert key_length > 0
+
+ if key_length > 1:
+ pb_summary_item.nested_key.extend(item.key)
+ else:
+ pb_summary_item.key = item.key[0]
+
+ return pb_summary_record
+
+ def publish_summary(
+ self,
+ run: "Run",
+ summary_record: sr.SummaryRecord,
+ ) -> None:
+ pb_summary_record = self._make_summary(summary_record, run=run)
+ self._publish_summary(pb_summary_record)
+
+ @abstractmethod
+ def _publish_summary(self, summary: pb.SummaryRecord) -> None:
+ raise NotImplementedError
+
+ def _make_files(self, files_dict: "FilesDict") -> pb.FilesRecord:
+ files = pb.FilesRecord()
+ for path, policy in files_dict["files"]:
+ f = files.files.add()
+ f.path = path
+ f.policy = file_policy_to_enum(policy)
+ return files
+
+ def publish_files(self, files_dict: "FilesDict") -> None:
+ files = self._make_files(files_dict)
+ self._publish_files(files)
+
+ @abstractmethod
+ def _publish_files(self, files: pb.FilesRecord) -> None:
+ raise NotImplementedError
+
+ def publish_python_packages(self, working_set) -> None:
+ python_packages = pb.PythonPackagesRequest()
+ for pkg in working_set:
+ python_packages.package.add(name=pkg.key, version=pkg.version)
+ self._publish_python_packages(python_packages)
+
+ @abstractmethod
+ def _publish_python_packages(
+ self, python_packages: pb.PythonPackagesRequest
+ ) -> None:
+ raise NotImplementedError
+
+ def _make_artifact(self, artifact: "Artifact") -> pb.ArtifactRecord:
+ proto_artifact = pb.ArtifactRecord()
+ proto_artifact.type = artifact.type
+ proto_artifact.name = artifact.name
+ proto_artifact.client_id = artifact._client_id
+ proto_artifact.sequence_client_id = artifact._sequence_client_id
+ proto_artifact.digest = artifact.digest
+ if artifact.distributed_id:
+ proto_artifact.distributed_id = artifact.distributed_id
+ if artifact.description:
+ proto_artifact.description = artifact.description
+ if artifact.metadata:
+ proto_artifact.metadata = json.dumps(json_friendly_val(artifact.metadata))
+ if artifact._base_id:
+ proto_artifact.base_id = artifact._base_id
+
+ ttl_duration_input = artifact._ttl_duration_seconds_to_gql()
+ if ttl_duration_input:
+ proto_artifact.ttl_duration_seconds = ttl_duration_input
+ proto_artifact.incremental_beta1 = artifact.incremental
+ self._make_artifact_manifest(artifact.manifest, obj=proto_artifact.manifest)
+ return proto_artifact
+
+ def _make_artifact_manifest(
+ self,
+ artifact_manifest: ArtifactManifest,
+ obj: Optional[pb.ArtifactManifest] = None,
+ ) -> pb.ArtifactManifest:
+ proto_manifest = obj or pb.ArtifactManifest()
+ proto_manifest.version = artifact_manifest.version()
+ proto_manifest.storage_policy = artifact_manifest.storage_policy.name()
+
+ # Very large manifests need to be written to file to avoid protobuf size limits.
+ if len(artifact_manifest) > MANIFEST_FILE_SIZE_THRESHOLD:
+ path = self._write_artifact_manifest_file(artifact_manifest)
+ proto_manifest.manifest_file_path = path
+ return proto_manifest
+
+ # Set storage policy on storageLayout (always V2) and storageRegion, only allow coreweave-us on wandb.ai for now.
+ # NOTE: the decode logic is NewManifestFromProto in core/pkg/artifacts/manifest.go
+ # The creation logic is in artifacts/_factories.py make_storage_policy
+ for k, v in artifact_manifest.storage_policy.config().items() or {}.items():
+ cfg = proto_manifest.storage_policy_config.add()
+ cfg.key = k
+ # TODO: Why json.dumps when existing values are plain string? We want to send complex structure without defining the proto?
+ cfg.value_json = json.dumps(v)
+
+ for entry in sorted(artifact_manifest.entries.values(), key=lambda k: k.path):
+ proto_entry = proto_manifest.contents.add()
+ proto_entry.path = entry.path
+ proto_entry.digest = entry.digest
+ if entry.size:
+ proto_entry.size = entry.size
+ if entry.birth_artifact_id:
+ proto_entry.birth_artifact_id = entry.birth_artifact_id
+ if entry.ref:
+ proto_entry.ref = entry.ref
+ if entry.local_path:
+ proto_entry.local_path = entry.local_path
+ proto_entry.skip_cache = entry.skip_cache
+ for k, v in entry.extra.items():
+ proto_extra = proto_entry.extra.add()
+ proto_extra.key = k
+ proto_extra.value_json = json.dumps(v)
+ return proto_manifest
+
+ def _write_artifact_manifest_file(self, manifest: ArtifactManifest) -> str:
+ manifest_dir = Path(get_staging_dir()) / "artifact_manifests"
+ manifest_dir.mkdir(parents=True, exist_ok=True)
+ # It would be simpler to use `manifest.to_json()`, but that gets very slow for
+ # large manifests since it encodes the whole thing as a single JSON object.
+ filename = f"{time.time()}_{token_hex(8)}.manifest_contents.jl.gz"
+ manifest_file_path = manifest_dir / filename
+ with gzip.open(manifest_file_path, mode="wt", compresslevel=1) as f:
+ for entry in manifest.entries.values():
+ f.write(f"{json.dumps(entry.to_json())}\n")
+ return str(manifest_file_path)
+
+ def deliver_link_artifact(
+ self,
+ artifact: "Artifact",
+ portfolio_name: str,
+ aliases: Iterable[str],
+ entity: Optional[str] = None,
+ project: Optional[str] = None,
+ organization: Optional[str] = None,
+ ) -> MailboxHandle[pb.Result]:
+ link_artifact = pb.LinkArtifactRequest()
+ if artifact.is_draft():
+ link_artifact.client_id = artifact._client_id
+ else:
+ link_artifact.server_id = artifact.id if artifact.id else ""
+ link_artifact.portfolio_name = portfolio_name
+ link_artifact.portfolio_entity = entity or ""
+ link_artifact.portfolio_organization = organization or ""
+ link_artifact.portfolio_project = project or ""
+ link_artifact.portfolio_aliases.extend(aliases)
+
+ return self._deliver_link_artifact(link_artifact)
+
+ @abstractmethod
+ def _deliver_link_artifact(
+ self, link_artifact: pb.LinkArtifactRequest
+ ) -> MailboxHandle[pb.Result]:
+ raise NotImplementedError
+
+ @staticmethod
+ def _make_partial_source_str(
+ source: Any, job_info: Dict[str, Any], metadata: Dict[str, Any]
+ ) -> str:
+ """Construct use_artifact.partial.source_info.source as str."""
+ source_type = job_info.get("source_type", "").strip()
+ if source_type == "artifact":
+ info_source = job_info.get("source", {})
+ source.artifact.artifact = info_source.get("artifact", "")
+ source.artifact.entrypoint.extend(info_source.get("entrypoint", []))
+ source.artifact.notebook = info_source.get("notebook", False)
+ build_context = info_source.get("build_context")
+ if build_context:
+ source.artifact.build_context = build_context
+ dockerfile = info_source.get("dockerfile")
+ if dockerfile:
+ source.artifact.dockerfile = dockerfile
+ elif source_type == "repo":
+ source.git.git_info.remote = metadata.get("git", {}).get("remote", "")
+ source.git.git_info.commit = metadata.get("git", {}).get("commit", "")
+ source.git.entrypoint.extend(metadata.get("entrypoint", []))
+ source.git.notebook = metadata.get("notebook", False)
+ build_context = metadata.get("build_context")
+ if build_context:
+ source.git.build_context = build_context
+ dockerfile = metadata.get("dockerfile")
+ if dockerfile:
+ source.git.dockerfile = dockerfile
+ elif source_type == "image":
+ source.image.image = metadata.get("docker", "")
+ else:
+ raise ValueError("Invalid source type")
+
+ source_str: str = source.SerializeToString()
+ return source_str
+
+ def _make_proto_use_artifact(
+ self,
+ use_artifact: pb.UseArtifactRecord,
+ job_name: str,
+ job_info: Dict[str, Any],
+ metadata: Dict[str, Any],
+ ) -> pb.UseArtifactRecord:
+ use_artifact.partial.job_name = job_name
+ use_artifact.partial.source_info._version = job_info.get("_version", "")
+ use_artifact.partial.source_info.source_type = job_info.get("source_type", "")
+ use_artifact.partial.source_info.runtime = job_info.get("runtime", "")
+
+ src_str = self._make_partial_source_str(
+ source=use_artifact.partial.source_info.source,
+ job_info=job_info,
+ metadata=metadata,
+ )
+ use_artifact.partial.source_info.source.ParseFromString(src_str) # type: ignore[arg-type]
+
+ return use_artifact
+
+ def publish_use_artifact(
+ self,
+ artifact: "Artifact",
+ ) -> None:
+ assert artifact.id is not None, "Artifact must have an id"
+
+ use_artifact = pb.UseArtifactRecord(
+ id=artifact.id,
+ type=artifact.type,
+ name=artifact.name,
+ )
+
+ # TODO(gst): move to internal process
+ if "_partial" in artifact.metadata:
+ # Download source info from logged partial job artifact
+ job_info = {}
+ try:
+ path = artifact.get_entry("wandb-job.json").download()
+ with open(path) as f:
+ job_info = json.load(f)
+
+ except Exception as e:
+ logger.warning(
+ f"Failed to download partial job info from artifact {artifact}, : {e}"
+ )
+ termwarn(
+ f"Failed to download partial job info from artifact {artifact}, : {e}"
+ )
+ return
+
+ try:
+ use_artifact = self._make_proto_use_artifact(
+ use_artifact=use_artifact,
+ job_name=artifact.name,
+ job_info=job_info,
+ metadata=artifact.metadata,
+ )
+ except Exception as e:
+ logger.warning(f"Failed to construct use artifact proto: {e}")
+ termwarn(f"Failed to construct use artifact proto: {e}")
+ return
+
+ self._publish_use_artifact(use_artifact)
+
+ @abstractmethod
+ def _publish_use_artifact(self, proto_artifact: pb.UseArtifactRecord) -> None:
+ raise NotImplementedError
+
+ def deliver_artifact(
+ self,
+ run: "Run",
+ artifact: "Artifact",
+ aliases: Iterable[str],
+ tags: Optional[Iterable[str]] = None,
+ history_step: Optional[int] = None,
+ is_user_created: bool = False,
+ use_after_commit: bool = False,
+ finalize: bool = True,
+ ) -> MailboxHandle[pb.Result]:
+ proto_run = self._make_run(run)
+ proto_artifact = self._make_artifact(artifact)
+ proto_artifact.run_id = proto_run.run_id
+ proto_artifact.project = proto_run.project
+ proto_artifact.entity = proto_run.entity
+ proto_artifact.user_created = is_user_created
+ proto_artifact.use_after_commit = use_after_commit
+ proto_artifact.finalize = finalize
+
+ proto_artifact.aliases.extend(aliases or [])
+ proto_artifact.tags.extend(tags or [])
+
+ log_artifact = pb.LogArtifactRequest()
+ log_artifact.artifact.CopyFrom(proto_artifact)
+ if history_step is not None:
+ log_artifact.history_step = history_step
+ log_artifact.staging_dir = get_staging_dir()
+ resp = self._deliver_artifact(log_artifact)
+ return resp
+
+ @abstractmethod
+ def _deliver_artifact(
+ self,
+ log_artifact: pb.LogArtifactRequest,
+ ) -> MailboxHandle[pb.Result]:
+ raise NotImplementedError
+
+ def deliver_download_artifact(
+ self,
+ artifact_id: str,
+ download_root: str,
+ allow_missing_references: bool,
+ skip_cache: bool,
+ path_prefix: Optional[str],
+ ) -> MailboxHandle[pb.Result]:
+ download_artifact = pb.DownloadArtifactRequest()
+ download_artifact.artifact_id = artifact_id
+ download_artifact.download_root = download_root
+ download_artifact.allow_missing_references = allow_missing_references
+ download_artifact.skip_cache = skip_cache
+ download_artifact.path_prefix = path_prefix or ""
+ resp = self._deliver_download_artifact(download_artifact)
+ return resp
+
+ @abstractmethod
+ def _deliver_download_artifact(
+ self, download_artifact: pb.DownloadArtifactRequest
+ ) -> MailboxHandle[pb.Result]:
+ raise NotImplementedError
+
+ def publish_artifact(
+ self,
+ run: "Run",
+ artifact: "Artifact",
+ aliases: Iterable[str],
+ tags: Optional[Iterable[str]] = None,
+ is_user_created: bool = False,
+ use_after_commit: bool = False,
+ finalize: bool = True,
+ ) -> None:
+ proto_run = self._make_run(run)
+ proto_artifact = self._make_artifact(artifact)
+ proto_artifact.run_id = proto_run.run_id
+ proto_artifact.project = proto_run.project
+ proto_artifact.entity = proto_run.entity
+ proto_artifact.user_created = is_user_created
+ proto_artifact.use_after_commit = use_after_commit
+ proto_artifact.finalize = finalize
+ proto_artifact.aliases.extend(aliases or [])
+ proto_artifact.tags.extend(tags or [])
+ self._publish_artifact(proto_artifact)
+
+ @abstractmethod
+ def _publish_artifact(self, proto_artifact: pb.ArtifactRecord) -> None:
+ raise NotImplementedError
+
+ def publish_tbdata(self, log_dir: str, save: bool, root_logdir: str = "") -> None:
+ tbrecord = pb.TBRecord()
+ tbrecord.log_dir = log_dir
+ tbrecord.save = save
+ tbrecord.root_dir = root_logdir
+ self._publish_tbdata(tbrecord)
+
+ @abstractmethod
+ def _publish_tbdata(self, tbrecord: pb.TBRecord) -> None:
+ raise NotImplementedError
+
+ @abstractmethod
+ def _publish_telemetry(self, telem: tpb.TelemetryRecord) -> None:
+ raise NotImplementedError
+
+ def publish_environment(self, environment: pb.EnvironmentRecord) -> None:
+ self._publish_environment(environment)
+
+ @abstractmethod
+ def _publish_environment(self, environment: pb.EnvironmentRecord) -> None:
+ raise NotImplementedError
+
+ def publish_partial_history(
+ self,
+ run: "Run",
+ data: dict,
+ user_step: int,
+ step: Optional[int] = None,
+ flush: Optional[bool] = None,
+ publish_step: bool = True,
+ ) -> None:
+ data = history_dict_to_json(run, data, step=user_step, ignore_copy_err=True)
+ data.pop("_step", None)
+
+ # add timestamp to the history request, if not already present
+ # the timestamp might come from the tensorboard log logic
+ if "_timestamp" not in data:
+ data["_timestamp"] = time.time()
+
+ partial_history = pb.PartialHistoryRequest()
+ for k, v in data.items():
+ item = partial_history.item.add()
+ item.key = k
+ item.value_json = json_dumps_safer_history(v)
+
+ if publish_step and step is not None:
+ partial_history.step.num = step
+ if flush is not None:
+ partial_history.action.flush = flush
+ self._publish_partial_history(partial_history)
+
+ @abstractmethod
+ def _publish_partial_history(self, history: pb.PartialHistoryRequest) -> None:
+ raise NotImplementedError
+
+ def publish_history(
+ self,
+ run: "Run",
+ data: dict,
+ step: Optional[int] = None,
+ publish_step: bool = True,
+ ) -> None:
+ data = history_dict_to_json(run, data, step=step)
+ history = pb.HistoryRecord()
+ if publish_step:
+ assert step is not None
+ history.step.num = step
+ data.pop("_step", None)
+ for k, v in data.items():
+ item = history.item.add()
+ item.key = k
+ item.value_json = json_dumps_safer_history(v)
+ self._publish_history(history)
+
+ @abstractmethod
+ def _publish_history(self, history: pb.HistoryRecord) -> None:
+ raise NotImplementedError
+
+ def publish_preempting(self) -> None:
+ preempt_rec = pb.RunPreemptingRecord()
+ self._publish_preempting(preempt_rec)
+
+ @abstractmethod
+ def _publish_preempting(self, preempt_rec: pb.RunPreemptingRecord) -> None:
+ raise NotImplementedError
+
+ def publish_output(self, name: str, data: str) -> None:
+ # from vendor.protobuf import google3.protobuf.timestamp
+ # ts = timestamp.Timestamp()
+ # ts.GetCurrentTime()
+ # now = datetime.now()
+ if name == "stdout":
+ otype = pb.OutputRecord.OutputType.STDOUT
+ elif name == "stderr":
+ otype = pb.OutputRecord.OutputType.STDERR
+ else:
+ # TODO(jhr): throw error?
+ termwarn("unknown type")
+ o = pb.OutputRecord(output_type=otype, line=data)
+ o.timestamp.GetCurrentTime()
+ self._publish_output(o)
+
+ @abstractmethod
+ def _publish_output(self, outdata: pb.OutputRecord) -> None:
+ raise NotImplementedError
+
+ def publish_output_raw(self, name: str, data: str) -> None:
+ # from vendor.protobuf import google3.protobuf.timestamp
+ # ts = timestamp.Timestamp()
+ # ts.GetCurrentTime()
+ # now = datetime.now()
+ if name == "stdout":
+ otype = pb.OutputRawRecord.OutputType.STDOUT
+ elif name == "stderr":
+ otype = pb.OutputRawRecord.OutputType.STDERR
+ else:
+ # TODO(jhr): throw error?
+ termwarn("unknown type")
+ o = pb.OutputRawRecord(output_type=otype, line=data)
+ o.timestamp.GetCurrentTime()
+ self._publish_output_raw(o)
+
+ @abstractmethod
+ def _publish_output_raw(self, outdata: pb.OutputRawRecord) -> None:
+ raise NotImplementedError
+
+ def publish_pause(self) -> None:
+ pause = pb.PauseRequest()
+ self._publish_pause(pause)
+
+ @abstractmethod
+ def _publish_pause(self, pause: pb.PauseRequest) -> None:
+ raise NotImplementedError
+
+ def publish_resume(self) -> None:
+ resume = pb.ResumeRequest()
+ self._publish_resume(resume)
+
+ @abstractmethod
+ def _publish_resume(self, resume: pb.ResumeRequest) -> None:
+ raise NotImplementedError
+
+ def publish_alert(
+ self, title: str, text: str, level: str, wait_duration: int
+ ) -> None:
+ proto_alert = pb.AlertRecord()
+ proto_alert.title = title
+ proto_alert.text = text
+ proto_alert.level = level
+ proto_alert.wait_duration = wait_duration
+ self._publish_alert(proto_alert)
+
+ @abstractmethod
+ def _publish_alert(self, alert: pb.AlertRecord) -> None:
+ raise NotImplementedError
+
+ def _make_exit(self, exit_code: Optional[int]) -> pb.RunExitRecord:
+ exit = pb.RunExitRecord()
+ if exit_code is not None:
+ exit.exit_code = exit_code
+ return exit
+
+ def publish_exit(self, exit_code: Optional[int]) -> None:
+ exit_data = self._make_exit(exit_code)
+ self._publish_exit(exit_data)
+
+ @abstractmethod
+ def _publish_exit(self, exit_data: pb.RunExitRecord) -> None:
+ raise NotImplementedError
+
+ def publish_keepalive(self) -> None:
+ keepalive = pb.KeepaliveRequest()
+ self._publish_keepalive(keepalive)
+
+ @abstractmethod
+ def _publish_keepalive(self, keepalive: pb.KeepaliveRequest) -> None:
+ raise NotImplementedError
+
+ def publish_job_input(
+ self,
+ include_paths: List[List[str]],
+ exclude_paths: List[List[str]],
+ input_schema: Optional[dict],
+ run_config: bool = False,
+ file_path: str = "",
+ ):
+ """Publishes a request to add inputs to the job.
+
+ If run_config is True, the wandb.config will be added as a job input.
+ If file_path is provided, the file at file_path will be added as a job
+ input.
+
+ The paths provided as arguments are sequences of dictionary keys that
+ specify a path within the wandb.config. If a path is included, the
+ corresponding field will be treated as a job input. If a path is
+ excluded, the corresponding field will not be treated as a job input.
+
+ Args:
+ include_paths: paths within config to include as job inputs.
+ exclude_paths: paths within config to exclude as job inputs.
+ input_schema: A JSON Schema describing which attributes will be
+ editable from the Launch drawer.
+ run_config: bool indicating whether wandb.config is the input source.
+ file_path: path to file to include as a job input.
+ """
+ if run_config and file_path:
+ raise ValueError(
+ "run_config and file_path are mutually exclusive arguments."
+ )
+ request = pb.JobInputRequest()
+ include_records = [pb.JobInputPath(path=path) for path in include_paths]
+ exclude_records = [pb.JobInputPath(path=path) for path in exclude_paths]
+ request.include_paths.extend(include_records)
+ request.exclude_paths.extend(exclude_records)
+ source = pb.JobInputSource(
+ run_config=pb.JobInputSource.RunConfigSource(),
+ )
+ if run_config:
+ source.run_config.CopyFrom(pb.JobInputSource.RunConfigSource())
+ else:
+ source.file.CopyFrom(
+ pb.JobInputSource.ConfigFileSource(path=file_path),
+ )
+ request.input_source.CopyFrom(source)
+ if input_schema:
+ request.input_schema = json_dumps_safer(input_schema)
+
+ return self._publish_job_input(request)
+
+ @abstractmethod
+ def _publish_job_input(
+ self, request: pb.JobInputRequest
+ ) -> MailboxHandle[pb.Result]:
+ raise NotImplementedError
+
+ def publish_probe_system_info(self) -> None:
+ probe_system_info = pb.ProbeSystemInfoRequest()
+ return self._publish_probe_system_info(probe_system_info)
+
+ @abstractmethod
+ def _publish_probe_system_info(
+ self, probe_system_info: pb.ProbeSystemInfoRequest
+ ) -> None:
+ raise NotImplementedError
+
+ def join(self) -> None:
+ # Drop indicates that the internal process has already been shutdown
+ if self._drop:
+ return
+
+ handle = self._deliver_shutdown()
+
+ try:
+ handle.wait_or(timeout=30)
+ except TimeoutError:
+ # This can happen if the server fails to respond due to a bug
+ # or due to being very busy.
+ logger.warning("timed out communicating shutdown")
+ except HandleAbandonedError:
+ # This can happen if the connection to the server is closed
+ # before a response is read.
+ logger.warning("handle abandoned while communicating shutdown")
+
+ @abstractmethod
+ def _deliver_shutdown(self) -> MailboxHandle[pb.Result]:
+ raise NotImplementedError
+
+ def deliver_run(self, run: "Run") -> MailboxHandle[pb.Result]:
+ run_record = self._make_run(run)
+ return self._deliver_run(run_record)
+
+ def deliver_finish_sync(
+ self,
+ ) -> MailboxHandle[pb.Result]:
+ sync = pb.SyncFinishRequest()
+ return self._deliver_finish_sync(sync)
+
+ @abstractmethod
+ def _deliver_finish_sync(
+ self, sync: pb.SyncFinishRequest
+ ) -> MailboxHandle[pb.Result]:
+ raise NotImplementedError
+
+ @abstractmethod
+ def _deliver_run(self, run: pb.RunRecord) -> MailboxHandle[pb.Result]:
+ raise NotImplementedError
+
+ def deliver_run_start(self, run: "Run") -> MailboxHandle[pb.Result]:
+ run_start = pb.RunStartRequest(run=self._make_run(run))
+ return self._deliver_run_start(run_start)
+
+ @abstractmethod
+ def _deliver_run_start(
+ self, run_start: pb.RunStartRequest
+ ) -> MailboxHandle[pb.Result]:
+ raise NotImplementedError
+
+ def deliver_attach(self, attach_id: str) -> MailboxHandle[pb.Result]:
+ attach = pb.AttachRequest(attach_id=attach_id)
+ return self._deliver_attach(attach)
+
+ @abstractmethod
+ def _deliver_attach(
+ self,
+ status: pb.AttachRequest,
+ ) -> MailboxHandle[pb.Result]:
+ raise NotImplementedError
+
+ def deliver_stop_status(self) -> MailboxHandle[pb.Result]:
+ status = pb.StopStatusRequest()
+ return self._deliver_stop_status(status)
+
+ @abstractmethod
+ def _deliver_stop_status(
+ self,
+ status: pb.StopStatusRequest,
+ ) -> MailboxHandle[pb.Result]:
+ raise NotImplementedError
+
+ def deliver_network_status(self) -> MailboxHandle[pb.Result]:
+ status = pb.NetworkStatusRequest()
+ return self._deliver_network_status(status)
+
+ @abstractmethod
+ def _deliver_network_status(
+ self,
+ status: pb.NetworkStatusRequest,
+ ) -> MailboxHandle[pb.Result]:
+ raise NotImplementedError
+
+ def deliver_internal_messages(self) -> MailboxHandle[pb.Result]:
+ internal_message = pb.InternalMessagesRequest()
+ return self._deliver_internal_messages(internal_message)
+
+ @abstractmethod
+ def _deliver_internal_messages(
+ self, internal_message: pb.InternalMessagesRequest
+ ) -> MailboxHandle[pb.Result]:
+ raise NotImplementedError
+
+ def deliver_get_summary(self) -> MailboxHandle[pb.Result]:
+ get_summary = pb.GetSummaryRequest()
+ return self._deliver_get_summary(get_summary)
+
+ @abstractmethod
+ def _deliver_get_summary(
+ self,
+ get_summary: pb.GetSummaryRequest,
+ ) -> MailboxHandle[pb.Result]:
+ raise NotImplementedError
+
+ def deliver_get_system_metrics(self) -> MailboxHandle[pb.Result]:
+ get_system_metrics = pb.GetSystemMetricsRequest()
+ return self._deliver_get_system_metrics(get_system_metrics)
+
+ @abstractmethod
+ def _deliver_get_system_metrics(
+ self, get_summary: pb.GetSystemMetricsRequest
+ ) -> MailboxHandle[pb.Result]:
+ raise NotImplementedError
+
+ def deliver_exit(self, exit_code: Optional[int]) -> MailboxHandle[pb.Result]:
+ exit_data = self._make_exit(exit_code)
+ return self._deliver_exit(exit_data)
+
+ @abstractmethod
+ def _deliver_exit(
+ self,
+ exit_data: pb.RunExitRecord,
+ ) -> MailboxHandle[pb.Result]:
+ raise NotImplementedError
+
+ def deliver_poll_exit(self) -> MailboxHandle[pb.Result]:
+ poll_exit = pb.PollExitRequest()
+ return self._deliver_poll_exit(poll_exit)
+
+ @abstractmethod
+ def _deliver_poll_exit(
+ self,
+ poll_exit: pb.PollExitRequest,
+ ) -> MailboxHandle[pb.Result]:
+ raise NotImplementedError
+
+ def deliver_finish_without_exit(self) -> MailboxHandle[pb.Result]:
+ run_finish_without_exit = pb.RunFinishWithoutExitRequest()
+ return self._deliver_finish_without_exit(run_finish_without_exit)
+
+ @abstractmethod
+ def _deliver_finish_without_exit(
+ self, run_finish_without_exit: pb.RunFinishWithoutExitRequest
+ ) -> MailboxHandle[pb.Result]:
+ raise NotImplementedError
+
+ def deliver_request_sampled_history(self) -> MailboxHandle[pb.Result]:
+ sampled_history = pb.SampledHistoryRequest()
+ return self._deliver_request_sampled_history(sampled_history)
+
+ @abstractmethod
+ def _deliver_request_sampled_history(
+ self, sampled_history: pb.SampledHistoryRequest
+ ) -> MailboxHandle[pb.Result]:
+ raise NotImplementedError
+
+ def deliver_request_run_status(self) -> MailboxHandle[pb.Result]:
+ run_status = pb.RunStatusRequest()
+ return self._deliver_request_run_status(run_status)
+
+ @abstractmethod
+ def _deliver_request_run_status(
+ self, run_status: pb.RunStatusRequest
+ ) -> MailboxHandle[pb.Result]:
+ raise NotImplementedError
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/interface/interface_queue.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/interface/interface_queue.py
new file mode 100644
index 0000000000000000000000000000000000000000..73c256b82ce41b5d779b5cdc53d694d99a8d8743
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/interface/interface_queue.py
@@ -0,0 +1,50 @@
+"""InterfaceQueue - Derived from InterfaceShared using queues to send to internal thread.
+
+See interface.py for how interface classes relate to each other.
+
+"""
+
+import logging
+from multiprocessing.process import BaseProcess
+from typing import TYPE_CHECKING, Optional
+
+from typing_extensions import override
+
+from .interface_shared import InterfaceShared
+
+if TYPE_CHECKING:
+ from queue import Queue
+
+ from wandb.proto import wandb_internal_pb2 as pb
+ from wandb.sdk.mailbox.mailbox_handle import MailboxHandle
+
+
+logger = logging.getLogger("wandb")
+
+
+class InterfaceQueue(InterfaceShared):
+ def __init__(
+ self,
+ record_q: Optional["Queue[pb.Record]"] = None,
+ result_q: Optional["Queue[pb.Result]"] = None,
+ process: Optional[BaseProcess] = None,
+ ) -> None:
+ self.record_q = record_q
+ self.result_q = result_q
+ self._process = process
+ super().__init__()
+
+ @override
+ async def deliver_async(
+ self,
+ record: "pb.Record",
+ ) -> "MailboxHandle[pb.Result]":
+ raise NotImplementedError
+
+ def _publish(self, record: "pb.Record", local: Optional[bool] = None) -> None:
+ if self._process and not self._process.is_alive():
+ raise Exception("The wandb backend process has shutdown")
+ if local:
+ record.control.local = local
+ if self.record_q:
+ self.record_q.put(record)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/interface/interface_shared.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/interface/interface_shared.py
new file mode 100644
index 0000000000000000000000000000000000000000..82164fbf2dcbfb02baffefd2ca41013deb5d3596
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/interface/interface_shared.py
@@ -0,0 +1,473 @@
+"""InterfaceShared - Derived from InterfaceBase - shared with InterfaceQueue and InterfaceSock.
+
+See interface.py for how interface classes relate to each other.
+
+"""
+
+import logging
+from abc import abstractmethod
+from typing import Any, Optional, cast
+
+from wandb.proto import wandb_internal_pb2 as pb
+from wandb.proto import wandb_telemetry_pb2 as tpb
+from wandb.sdk.mailbox import MailboxHandle
+from wandb.util import json_dumps_safer, json_friendly
+
+from .interface import InterfaceBase
+
+logger = logging.getLogger("wandb")
+
+
+class InterfaceShared(InterfaceBase):
+ def __init__(self) -> None:
+ super().__init__()
+
+ def _publish_output(self, outdata: pb.OutputRecord) -> None:
+ rec = pb.Record()
+ rec.output.CopyFrom(outdata)
+ self._publish(rec)
+
+ def _publish_cancel(self, cancel: pb.CancelRequest) -> None:
+ rec = self._make_request(cancel=cancel)
+ self._publish(rec)
+
+ def _publish_output_raw(self, outdata: pb.OutputRawRecord) -> None:
+ rec = pb.Record()
+ rec.output_raw.CopyFrom(outdata)
+ self._publish(rec)
+
+ def _publish_tbdata(self, tbrecord: pb.TBRecord) -> None:
+ rec = self._make_record(tbrecord=tbrecord)
+ self._publish(rec)
+
+ def _publish_partial_history(
+ self, partial_history: pb.PartialHistoryRequest
+ ) -> None:
+ rec = self._make_request(partial_history=partial_history)
+ self._publish(rec)
+
+ def _publish_history(self, history: pb.HistoryRecord) -> None:
+ rec = self._make_record(history=history)
+ self._publish(rec)
+
+ def _publish_preempting(self, preempt_rec: pb.RunPreemptingRecord) -> None:
+ rec = self._make_record(preempting=preempt_rec)
+ self._publish(rec)
+
+ def _publish_telemetry(self, telem: tpb.TelemetryRecord) -> None:
+ rec = self._make_record(telemetry=telem)
+ self._publish(rec)
+
+ def _publish_environment(self, environment: pb.EnvironmentRecord) -> None:
+ rec = self._make_record(environment=environment)
+ self._publish(rec)
+
+ def _publish_job_input(
+ self, job_input: pb.JobInputRequest
+ ) -> MailboxHandle[pb.Result]:
+ record = self._make_request(job_input=job_input)
+ return self._deliver(record)
+
+ def _make_stats(self, stats_dict: dict) -> pb.StatsRecord:
+ stats = pb.StatsRecord()
+ stats.stats_type = pb.StatsRecord.StatsType.SYSTEM
+ stats.timestamp.GetCurrentTime() # todo: fix this, this is wrong :)
+ for k, v in stats_dict.items():
+ item = stats.item.add()
+ item.key = k
+ item.value_json = json_dumps_safer(json_friendly(v)[0])
+ return stats
+
+ def _make_request( # noqa: C901
+ self,
+ get_summary: Optional[pb.GetSummaryRequest] = None,
+ pause: Optional[pb.PauseRequest] = None,
+ resume: Optional[pb.ResumeRequest] = None,
+ status: Optional[pb.StatusRequest] = None,
+ stop_status: Optional[pb.StopStatusRequest] = None,
+ internal_messages: Optional[pb.InternalMessagesRequest] = None,
+ network_status: Optional[pb.NetworkStatusRequest] = None,
+ poll_exit: Optional[pb.PollExitRequest] = None,
+ partial_history: Optional[pb.PartialHistoryRequest] = None,
+ sampled_history: Optional[pb.SampledHistoryRequest] = None,
+ run_start: Optional[pb.RunStartRequest] = None,
+ check_version: Optional[pb.CheckVersionRequest] = None,
+ log_artifact: Optional[pb.LogArtifactRequest] = None,
+ download_artifact: Optional[pb.DownloadArtifactRequest] = None,
+ link_artifact: Optional[pb.LinkArtifactRequest] = None,
+ defer: Optional[pb.DeferRequest] = None,
+ attach: Optional[pb.AttachRequest] = None,
+ server_info: Optional[pb.ServerInfoRequest] = None,
+ keepalive: Optional[pb.KeepaliveRequest] = None,
+ run_status: Optional[pb.RunStatusRequest] = None,
+ sender_mark: Optional[pb.SenderMarkRequest] = None,
+ sender_read: Optional[pb.SenderReadRequest] = None,
+ sync_finish: Optional[pb.SyncFinishRequest] = None,
+ status_report: Optional[pb.StatusReportRequest] = None,
+ cancel: Optional[pb.CancelRequest] = None,
+ summary_record: Optional[pb.SummaryRecordRequest] = None,
+ telemetry_record: Optional[pb.TelemetryRecordRequest] = None,
+ get_system_metrics: Optional[pb.GetSystemMetricsRequest] = None,
+ python_packages: Optional[pb.PythonPackagesRequest] = None,
+ job_input: Optional[pb.JobInputRequest] = None,
+ run_finish_without_exit: Optional[pb.RunFinishWithoutExitRequest] = None,
+ probe_system_info: Optional[pb.ProbeSystemInfoRequest] = None,
+ ) -> pb.Record:
+ request = pb.Request()
+ if get_summary:
+ request.get_summary.CopyFrom(get_summary)
+ elif pause:
+ request.pause.CopyFrom(pause)
+ elif resume:
+ request.resume.CopyFrom(resume)
+ elif status:
+ request.status.CopyFrom(status)
+ elif stop_status:
+ request.stop_status.CopyFrom(stop_status)
+ elif internal_messages:
+ request.internal_messages.CopyFrom(internal_messages)
+ elif network_status:
+ request.network_status.CopyFrom(network_status)
+ elif poll_exit:
+ request.poll_exit.CopyFrom(poll_exit)
+ elif partial_history:
+ request.partial_history.CopyFrom(partial_history)
+ elif sampled_history:
+ request.sampled_history.CopyFrom(sampled_history)
+ elif run_start:
+ request.run_start.CopyFrom(run_start)
+ elif check_version:
+ request.check_version.CopyFrom(check_version)
+ elif log_artifact:
+ request.log_artifact.CopyFrom(log_artifact)
+ elif download_artifact:
+ request.download_artifact.CopyFrom(download_artifact)
+ elif link_artifact:
+ request.link_artifact.CopyFrom(link_artifact)
+ elif defer:
+ request.defer.CopyFrom(defer)
+ elif attach:
+ request.attach.CopyFrom(attach)
+ elif server_info:
+ request.server_info.CopyFrom(server_info)
+ elif keepalive:
+ request.keepalive.CopyFrom(keepalive)
+ elif run_status:
+ request.run_status.CopyFrom(run_status)
+ elif sender_mark:
+ request.sender_mark.CopyFrom(sender_mark)
+ elif sender_read:
+ request.sender_read.CopyFrom(sender_read)
+ elif cancel:
+ request.cancel.CopyFrom(cancel)
+ elif status_report:
+ request.status_report.CopyFrom(status_report)
+ elif summary_record:
+ request.summary_record.CopyFrom(summary_record)
+ elif telemetry_record:
+ request.telemetry_record.CopyFrom(telemetry_record)
+ elif get_system_metrics:
+ request.get_system_metrics.CopyFrom(get_system_metrics)
+ elif sync_finish:
+ request.sync_finish.CopyFrom(sync_finish)
+ elif python_packages:
+ request.python_packages.CopyFrom(python_packages)
+ elif job_input:
+ request.job_input.CopyFrom(job_input)
+ elif run_finish_without_exit:
+ request.run_finish_without_exit.CopyFrom(run_finish_without_exit)
+ elif probe_system_info:
+ request.probe_system_info.CopyFrom(probe_system_info)
+ else:
+ raise Exception("Invalid request")
+ record = self._make_record(request=request)
+ # All requests do not get persisted
+ record.control.local = True
+ if status_report:
+ record.control.flow_control = True
+ return record
+
+ def _make_record( # noqa: C901
+ self,
+ run: Optional[pb.RunRecord] = None,
+ config: Optional[pb.ConfigRecord] = None,
+ files: Optional[pb.FilesRecord] = None,
+ summary: Optional[pb.SummaryRecord] = None,
+ history: Optional[pb.HistoryRecord] = None,
+ stats: Optional[pb.StatsRecord] = None,
+ exit: Optional[pb.RunExitRecord] = None,
+ artifact: Optional[pb.ArtifactRecord] = None,
+ tbrecord: Optional[pb.TBRecord] = None,
+ alert: Optional[pb.AlertRecord] = None,
+ final: Optional[pb.FinalRecord] = None,
+ metric: Optional[pb.MetricRecord] = None,
+ header: Optional[pb.HeaderRecord] = None,
+ footer: Optional[pb.FooterRecord] = None,
+ request: Optional[pb.Request] = None,
+ telemetry: Optional[tpb.TelemetryRecord] = None,
+ preempting: Optional[pb.RunPreemptingRecord] = None,
+ use_artifact: Optional[pb.UseArtifactRecord] = None,
+ output: Optional[pb.OutputRecord] = None,
+ output_raw: Optional[pb.OutputRawRecord] = None,
+ environment: Optional[pb.EnvironmentRecord] = None,
+ ) -> pb.Record:
+ record = pb.Record()
+ if run:
+ record.run.CopyFrom(run)
+ elif config:
+ record.config.CopyFrom(config)
+ elif summary:
+ record.summary.CopyFrom(summary)
+ elif history:
+ record.history.CopyFrom(history)
+ elif files:
+ record.files.CopyFrom(files)
+ elif stats:
+ record.stats.CopyFrom(stats)
+ elif exit:
+ record.exit.CopyFrom(exit)
+ elif artifact:
+ record.artifact.CopyFrom(artifact)
+ elif tbrecord:
+ record.tbrecord.CopyFrom(tbrecord)
+ elif alert:
+ record.alert.CopyFrom(alert)
+ elif final:
+ record.final.CopyFrom(final)
+ elif header:
+ record.header.CopyFrom(header)
+ elif footer:
+ record.footer.CopyFrom(footer)
+ elif request:
+ record.request.CopyFrom(request)
+ elif telemetry:
+ record.telemetry.CopyFrom(telemetry)
+ elif metric:
+ record.metric.CopyFrom(metric)
+ elif preempting:
+ record.preempting.CopyFrom(preempting)
+ elif use_artifact:
+ record.use_artifact.CopyFrom(use_artifact)
+ elif output:
+ record.output.CopyFrom(output)
+ elif output_raw:
+ record.output_raw.CopyFrom(output_raw)
+ elif environment:
+ record.environment.CopyFrom(environment)
+ else:
+ raise Exception("Invalid record")
+ return record
+
+ @abstractmethod
+ def _publish(self, record: pb.Record, local: Optional[bool] = None) -> None:
+ raise NotImplementedError
+
+ def _deliver(self, record: pb.Record) -> "MailboxHandle[pb.Result]":
+ raise NotImplementedError
+
+ def _publish_defer(self, state: "pb.DeferRequest.DeferState.V") -> None:
+ defer = pb.DeferRequest(state=state)
+ rec = self._make_request(defer=defer)
+ self._publish(rec, local=True)
+
+ def publish_defer(self, state: int = 0) -> None:
+ self._publish_defer(cast("pb.DeferRequest.DeferState.V", state))
+
+ def _publish_header(self, header: pb.HeaderRecord) -> None:
+ rec = self._make_record(header=header)
+ self._publish(rec)
+
+ def publish_footer(self) -> None:
+ footer = pb.FooterRecord()
+ rec = self._make_record(footer=footer)
+ self._publish(rec)
+
+ def publish_final(self) -> None:
+ final = pb.FinalRecord()
+ rec = self._make_record(final=final)
+ self._publish(rec)
+
+ def _publish_pause(self, pause: pb.PauseRequest) -> None:
+ rec = self._make_request(pause=pause)
+ self._publish(rec)
+
+ def _publish_resume(self, resume: pb.ResumeRequest) -> None:
+ rec = self._make_request(resume=resume)
+ self._publish(rec)
+
+ def _publish_run(self, run: pb.RunRecord) -> None:
+ rec = self._make_record(run=run)
+ self._publish(rec)
+
+ def _publish_config(self, cfg: pb.ConfigRecord) -> None:
+ rec = self._make_record(config=cfg)
+ self._publish(rec)
+
+ def _publish_summary(self, summary: pb.SummaryRecord) -> None:
+ rec = self._make_record(summary=summary)
+ self._publish(rec)
+
+ def _publish_metric(self, metric: pb.MetricRecord) -> None:
+ rec = self._make_record(metric=metric)
+ self._publish(rec)
+
+ def publish_stats(self, stats_dict: dict) -> None:
+ stats = self._make_stats(stats_dict)
+ rec = self._make_record(stats=stats)
+ self._publish(rec)
+
+ def _publish_python_packages(
+ self, python_packages: pb.PythonPackagesRequest
+ ) -> None:
+ rec = self._make_request(python_packages=python_packages)
+ self._publish(rec)
+
+ def _publish_files(self, files: pb.FilesRecord) -> None:
+ rec = self._make_record(files=files)
+ self._publish(rec)
+
+ def _publish_use_artifact(self, use_artifact: pb.UseArtifactRecord) -> Any:
+ rec = self._make_record(use_artifact=use_artifact)
+ self._publish(rec)
+
+ def _publish_probe_system_info(
+ self, probe_system_info: pb.ProbeSystemInfoRequest
+ ) -> None:
+ record = self._make_request(probe_system_info=probe_system_info)
+ self._publish(record)
+
+ def _deliver_artifact(
+ self,
+ log_artifact: pb.LogArtifactRequest,
+ ) -> MailboxHandle[pb.Result]:
+ rec = self._make_request(log_artifact=log_artifact)
+ return self._deliver(rec)
+
+ def _deliver_download_artifact(
+ self, download_artifact: pb.DownloadArtifactRequest
+ ) -> MailboxHandle[pb.Result]:
+ rec = self._make_request(download_artifact=download_artifact)
+ return self._deliver(rec)
+
+ def _deliver_link_artifact(
+ self, link_artifact: pb.LinkArtifactRequest
+ ) -> MailboxHandle[pb.Result]:
+ rec = self._make_request(link_artifact=link_artifact)
+ return self._deliver(rec)
+
+ def _publish_artifact(self, proto_artifact: pb.ArtifactRecord) -> None:
+ rec = self._make_record(artifact=proto_artifact)
+ self._publish(rec)
+
+ def _publish_alert(self, proto_alert: pb.AlertRecord) -> None:
+ rec = self._make_record(alert=proto_alert)
+ self._publish(rec)
+
+ def _deliver_status(
+ self,
+ status: pb.StatusRequest,
+ ) -> MailboxHandle[pb.Result]:
+ req = self._make_request(status=status)
+ return self._deliver(req)
+
+ def _publish_exit(self, exit_data: pb.RunExitRecord) -> None:
+ rec = self._make_record(exit=exit_data)
+ self._publish(rec)
+
+ def _publish_keepalive(self, keepalive: pb.KeepaliveRequest) -> None:
+ record = self._make_request(keepalive=keepalive)
+ self._publish(record)
+
+ def _deliver_shutdown(self) -> MailboxHandle[pb.Result]:
+ request = pb.Request(shutdown=pb.ShutdownRequest())
+ record = self._make_record(request=request)
+ return self._deliver(record)
+
+ def _deliver_run(self, run: pb.RunRecord) -> MailboxHandle[pb.Result]:
+ record = self._make_record(run=run)
+ return self._deliver(record)
+
+ def _deliver_finish_sync(
+ self,
+ sync_finish: pb.SyncFinishRequest,
+ ) -> MailboxHandle[pb.Result]:
+ record = self._make_request(sync_finish=sync_finish)
+ return self._deliver(record)
+
+ def _deliver_run_start(
+ self,
+ run_start: pb.RunStartRequest,
+ ) -> MailboxHandle[pb.Result]:
+ record = self._make_request(run_start=run_start)
+ return self._deliver(record)
+
+ def _deliver_get_summary(
+ self,
+ get_summary: pb.GetSummaryRequest,
+ ) -> MailboxHandle[pb.Result]:
+ record = self._make_request(get_summary=get_summary)
+ return self._deliver(record)
+
+ def _deliver_get_system_metrics(
+ self, get_system_metrics: pb.GetSystemMetricsRequest
+ ) -> MailboxHandle[pb.Result]:
+ record = self._make_request(get_system_metrics=get_system_metrics)
+ return self._deliver(record)
+
+ def _deliver_exit(
+ self,
+ exit_data: pb.RunExitRecord,
+ ) -> MailboxHandle[pb.Result]:
+ record = self._make_record(exit=exit_data)
+ return self._deliver(record)
+
+ def _deliver_poll_exit(
+ self,
+ poll_exit: pb.PollExitRequest,
+ ) -> MailboxHandle[pb.Result]:
+ record = self._make_request(poll_exit=poll_exit)
+ return self._deliver(record)
+
+ def _deliver_finish_without_exit(
+ self, run_finish_without_exit: pb.RunFinishWithoutExitRequest
+ ) -> MailboxHandle[pb.Result]:
+ record = self._make_request(run_finish_without_exit=run_finish_without_exit)
+ return self._deliver(record)
+
+ def _deliver_stop_status(
+ self,
+ stop_status: pb.StopStatusRequest,
+ ) -> MailboxHandle[pb.Result]:
+ record = self._make_request(stop_status=stop_status)
+ return self._deliver(record)
+
+ def _deliver_attach(
+ self,
+ attach: pb.AttachRequest,
+ ) -> MailboxHandle[pb.Result]:
+ record = self._make_request(attach=attach)
+ return self._deliver(record)
+
+ def _deliver_network_status(
+ self, network_status: pb.NetworkStatusRequest
+ ) -> MailboxHandle[pb.Result]:
+ record = self._make_request(network_status=network_status)
+ return self._deliver(record)
+
+ def _deliver_internal_messages(
+ self, internal_message: pb.InternalMessagesRequest
+ ) -> MailboxHandle[pb.Result]:
+ record = self._make_request(internal_messages=internal_message)
+ return self._deliver(record)
+
+ def _deliver_request_sampled_history(
+ self, sampled_history: pb.SampledHistoryRequest
+ ) -> MailboxHandle[pb.Result]:
+ record = self._make_request(sampled_history=sampled_history)
+ return self._deliver(record)
+
+ def _deliver_request_run_status(
+ self, run_status: pb.RunStatusRequest
+ ) -> MailboxHandle[pb.Result]:
+ record = self._make_request(run_status=run_status)
+ return self._deliver(record)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/interface/interface_sock.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/interface/interface_sock.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9cbd5986f77c05a56fb50e14ca4a7717dbc4420
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/interface/interface_sock.py
@@ -0,0 +1,55 @@
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING, Any
+
+from typing_extensions import override
+
+from wandb.proto import wandb_server_pb2 as spb
+from wandb.sdk.lib import asyncio_manager
+
+from .interface_shared import InterfaceShared
+
+if TYPE_CHECKING:
+ from wandb.proto import wandb_internal_pb2 as pb
+ from wandb.sdk.lib.service.service_client import ServiceClient
+ from wandb.sdk.mailbox import MailboxHandle
+
+
+logger = logging.getLogger("wandb")
+
+
+class InterfaceSock(InterfaceShared):
+ def __init__(
+ self,
+ asyncer: asyncio_manager.AsyncioManager,
+ client: ServiceClient,
+ stream_id: str,
+ ) -> None:
+ super().__init__()
+ self._asyncer = asyncer
+ self._client = client
+ self._stream_id = stream_id
+
+ def _assign(self, record: Any) -> None:
+ assert self._stream_id
+ record._info.stream_id = self._stream_id
+
+ @override
+ def _publish(self, record: pb.Record, local: bool | None = None) -> None:
+ self._assign(record)
+ request = spb.ServerRequest()
+ request.record_publish.CopyFrom(record)
+ self._asyncer.run(lambda: self._client.publish(request))
+
+ def _deliver(self, record: pb.Record) -> MailboxHandle[pb.Result]:
+ return self._asyncer.run(lambda: self.deliver_async(record))
+
+ @override
+ async def deliver_async(self, record: pb.Record) -> MailboxHandle[pb.Result]:
+ self._assign(record)
+ request = spb.ServerRequest()
+ request.record_publish.CopyFrom(record)
+
+ handle = await self._client.deliver(request)
+ return handle.map(lambda response: response.result_communicate)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/interface/summary_record.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/interface/summary_record.py
new file mode 100644
index 0000000000000000000000000000000000000000..2050a39080759ef12c54364aaf76b1dee6ab7e1d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/interface/summary_record.py
@@ -0,0 +1,67 @@
+"""Summary Record.
+
+This module implements a summary record as an intermediate format before being converted
+to a protocol buffer.
+"""
+
+import typing as t
+
+
+class SummaryRecord:
+ """Encodes a diff -- analogous to the SummaryRecord protobuf message."""
+
+ update: t.List["SummaryItem"]
+ remove: t.List["SummaryItem"]
+
+ def __init__(self):
+ self.update = []
+ self.remove = []
+
+ def __str__(self):
+ s = "SummaryRecord:\n Update:\n "
+ s += "\n ".join([str(item) for item in self.update])
+ s += "\n Remove:\n "
+ s += "\n ".join([str(item) for item in self.remove])
+ s += "\n"
+ return s
+
+ __repr__ = __str__
+
+ def _add_next_parent(self, parent_key):
+ with_next_parent = SummaryRecord()
+ with_next_parent.update = [
+ item._add_next_parent(parent_key) for item in self.update
+ ]
+ with_next_parent.remove = [
+ item._add_next_parent(parent_key) for item in self.remove
+ ]
+
+ return with_next_parent
+
+
+class SummaryItem:
+ """Analogous to the SummaryItem protobuf message."""
+
+ key: t.Tuple[str]
+ value: t.Any
+
+ def __init__(self):
+ self.key = tuple()
+ self.value = None
+
+ def __str__(self):
+ return "SummaryItem: key: " + str(self.key) + " value: " + str(self.value)
+
+ __repr__ = __str__
+
+ def _add_next_parent(self, parent_key):
+ with_next_parent = SummaryItem()
+
+ key = self.key
+ if not isinstance(key, tuple):
+ key = (key,)
+
+ with_next_parent.key = (parent_key,) + self.key
+ with_next_parent.value = self.value
+
+ return with_next_parent
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/_generated/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/_generated/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..efba046d8a690634a316a9033f74e8320370e61e
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/_generated/__init__.py
@@ -0,0 +1,5 @@
+# Generated by ariadne-codegen
+
+__all__ = ["SERVER_FEATURES_QUERY_GQL", "ServerFeaturesQuery"]
+from .operations import SERVER_FEATURES_QUERY_GQL
+from .server_features_query import ServerFeaturesQuery
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/_generated/enums.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/_generated/enums.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc7d61d95669bab416e88c3acc378913704e64e8
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/_generated/enums.py
@@ -0,0 +1,4 @@
+# Generated by ariadne-codegen
+# Source: core/api/graphql/schemas/schema-latest.graphql
+
+from __future__ import annotations
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/_generated/input_types.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/_generated/input_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc7d61d95669bab416e88c3acc378913704e64e8
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/_generated/input_types.py
@@ -0,0 +1,4 @@
+# Generated by ariadne-codegen
+# Source: core/api/graphql/schemas/schema-latest.graphql
+
+from __future__ import annotations
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/_generated/operations.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/_generated/operations.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d204236d0154d142ccc4ac22ade6befe7e6e012
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/_generated/operations.py
@@ -0,0 +1,15 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/utils/
+
+__all__ = ["SERVER_FEATURES_QUERY_GQL"]
+
+SERVER_FEATURES_QUERY_GQL = """
+query ServerFeaturesQuery {
+ serverInfo {
+ features {
+ name
+ isEnabled
+ }
+ }
+}
+"""
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/_generated/server_features_query.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/_generated/server_features_query.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9bd8543434ed3cbfdef6f2636ba472d8bfa7f00
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/_generated/server_features_query.py
@@ -0,0 +1,27 @@
+# Generated by ariadne-codegen
+# Source: tools/graphql_codegen/utils/
+
+from __future__ import annotations
+
+from typing import List, Optional
+
+from pydantic import Field
+
+from wandb._pydantic import GQLBase
+
+
+class ServerFeaturesQuery(GQLBase):
+ server_info: Optional[ServerFeaturesQueryServerInfo] = Field(alias="serverInfo")
+
+
+class ServerFeaturesQueryServerInfo(GQLBase):
+ features: List[Optional[ServerFeaturesQueryServerInfoFeatures]]
+
+
+class ServerFeaturesQueryServerInfoFeatures(GQLBase):
+ name: str
+ is_enabled: bool = Field(alias="isEnabled")
+
+
+ServerFeaturesQuery.model_rebuild()
+ServerFeaturesQueryServerInfo.model_rebuild()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/context.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/context.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ad49ee15a1e15b76c1cfacdbc2158fe8cfa9ad7
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/context.py
@@ -0,0 +1,89 @@
+"""Context Keeper."""
+
+import logging
+import threading
+from typing import Dict, Optional
+
+from wandb.proto.wandb_internal_pb2 import Record, Result
+
+logger = logging.getLogger(__name__)
+
+
+class Context:
+ _cancel_event: threading.Event
+ # TODO(debug_context) add debug setting to enable this
+ # _debug_record: Optional[Record]
+
+ def __init__(self) -> None:
+ self._cancel_event = threading.Event()
+ # TODO(debug_context) see above
+ # self._debug_record = None
+
+ def cancel(self) -> None:
+ self._cancel_event.set()
+
+ @property
+ def cancel_event(self) -> threading.Event:
+ return self._cancel_event
+
+
+def context_id_from_record(record: Record) -> str:
+ context_id = record.control.mailbox_slot
+ return context_id
+
+
+def context_id_from_result(result: Result) -> str:
+ context_id = result.control.mailbox_slot
+ return context_id
+
+
+class ContextKeeper:
+ _active_items: Dict[str, Context]
+
+ def __init__(self) -> None:
+ self._active_items = {}
+
+ def add_from_record(self, record: Record) -> Optional[Context]:
+ context_id = context_id_from_record(record)
+ if not context_id:
+ return None
+ context_obj = self.add(context_id)
+
+ # TODO(debug_context) see above
+ # context_obj._debug_record = record
+
+ return context_obj
+
+ def add(self, context_id: str) -> Context:
+ assert context_id
+ context_obj = Context()
+ self._active_items[context_id] = context_obj
+ return context_obj
+
+ def get(self, context_id: str) -> Optional[Context]:
+ item = self._active_items.get(context_id)
+ return item
+
+ def release(self, context_id: str) -> None:
+ if not context_id:
+ return
+ _ = self._active_items.pop(context_id, None)
+
+ def cancel(self, context_id: str) -> bool:
+ item = self.get(context_id)
+ if item:
+ item.cancel()
+ return True
+ return False
+
+ # TODO(debug_context) see above
+ # def _debug_print_orphans(self, print_to_stdout: bool) -> None:
+ # for context_id, context in self._active_items.items():
+ # record = context._debug_record
+ # record_type = record.WhichOneof("record_type") if record else "unknown"
+ # message = (
+ # f"Context: {context_id} {context.cancel_event.is_set()} {record_type}"
+ # )
+ # logger.warning(message)
+ # if print_to_stdout:
+ # print(message)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/datastore.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/datastore.py
new file mode 100644
index 0000000000000000000000000000000000000000..76376f9b1535473d698d56db85a3af316f76ec16
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/datastore.py
@@ -0,0 +1,293 @@
+"""leveldb log datastore.
+
+Format is described at:
+ https://github.com/google/leveldb/blob/master/doc/log_format.md
+
+block := record* trailer?
+record :=
+ checksum: uint32 // crc32c of type and data[] ; little-endian
+ length: uint16 // little-endian
+ type: uint8 // One of FULL, FIRST, MIDDLE, LAST
+ data: uint8[length]
+
+header :=
+ ident: char[4]
+ magic: uint16
+ version: uint8
+"""
+
+# TODO: possibly restructure code by porting the C++ or go implementation
+
+import logging
+import os
+import struct
+import zlib
+from typing import TYPE_CHECKING, Optional, Tuple
+
+import wandb
+
+if TYPE_CHECKING:
+ from typing import IO, Any
+
+ from wandb.proto.wandb_internal_pb2 import Record
+
+logger = logging.getLogger(__name__)
+
+LEVELDBLOG_HEADER_LEN = 7
+LEVELDBLOG_BLOCK_LEN = 32768
+LEVELDBLOG_DATA_LEN = LEVELDBLOG_BLOCK_LEN - LEVELDBLOG_HEADER_LEN
+
+LEVELDBLOG_FULL = 1
+LEVELDBLOG_FIRST = 2
+LEVELDBLOG_MIDDLE = 3
+LEVELDBLOG_LAST = 4
+
+LEVELDBLOG_HEADER_IDENT = ":W&B"
+LEVELDBLOG_HEADER_MAGIC = (
+ 0xBEE1 # zlib.crc32(bytes("Weights & Biases", 'iso8859-1')) & 0xffff
+)
+LEVELDBLOG_HEADER_VERSION = 0
+
+try:
+ bytes("", "ascii")
+
+ def strtobytes(x):
+ """Strtobytes."""
+ return bytes(x, "iso8859-1")
+
+ # def bytestostr(x):
+ # return str(x, 'iso8859-1')
+
+except Exception:
+ strtobytes = str
+ # bytestostr = str
+
+
+class DataStore:
+ _index: int
+ _flush_offset: int
+
+ def __init__(self) -> None:
+ self._opened_for_scan = False
+ self._fp: Optional[IO[Any]] = None
+ self._index = 0
+ self._flush_offset = 0
+ self._size_bytes = 0
+
+ self._crc = [0] * (LEVELDBLOG_LAST + 1)
+ for x in range(1, LEVELDBLOG_LAST + 1):
+ self._crc[x] = zlib.crc32(strtobytes(chr(x))) & 0xFFFFFFFF
+
+ assert (
+ wandb._assert_is_internal_process # type: ignore
+ ), "DataStore can only be used in the internal process"
+
+ def open_for_write(self, fname: str) -> None:
+ self._fname = fname
+ logger.info("open: %s", fname)
+ open_flags = "xb"
+ self._fp = open(fname, open_flags)
+ self._write_header()
+
+ def open_for_append(self, fname):
+ # TODO: implement
+ self._fname = fname
+ logger.info("open: %s", fname)
+ self._fp = open(fname, "wb")
+ # do something with _index
+
+ def open_for_scan(self, fname):
+ self._fname = fname
+ logger.info("open for scan: %s", fname)
+ self._fp = open(fname, "r+b")
+ self._index = 0
+ self._size_bytes = os.stat(fname).st_size
+ self._opened_for_scan = True
+ self._read_header()
+
+ def seek(self, offset: int) -> None:
+ self._fp.seek(offset) # type: ignore
+ self._index = offset
+
+ def get_offset(self) -> int:
+ offset = self._fp.tell() # type: ignore
+ return offset
+
+ def in_last_block(self):
+ """Determine if we're in the last block to handle in-progress writes."""
+ return self._index > self._size_bytes - LEVELDBLOG_DATA_LEN
+
+ def scan_record(self):
+ assert self._opened_for_scan, "file not open for scanning"
+ # TODO(jhr): handle some assertions as file corruption issues
+ # assume we have enough room to read header, checked by caller?
+ header = self._fp.read(LEVELDBLOG_HEADER_LEN)
+ if len(header) == 0:
+ return None
+ assert len(header) == LEVELDBLOG_HEADER_LEN, (
+ f"record header is {len(header)} bytes instead of the expected {LEVELDBLOG_HEADER_LEN}"
+ )
+ fields = struct.unpack(" LEVELDBLOG_DATA_LEN:
+ self._write_record(
+ s[data_used : data_used + LEVELDBLOG_DATA_LEN],
+ LEVELDBLOG_MIDDLE,
+ )
+ data_used += LEVELDBLOG_DATA_LEN
+ data_left -= LEVELDBLOG_DATA_LEN
+
+ # write last and flush the entire block to disk
+ self._write_record(s[data_used:], LEVELDBLOG_LAST)
+ self._fp.flush()
+ os.fsync(self._fp.fileno())
+ self._flush_offset = self._index
+
+ return start_offset, self._index, self._flush_offset
+
+ def ensure_flushed(self, off: int) -> None:
+ self._fp.flush() # type: ignore
+
+ def write(self, obj: "Record") -> Tuple[int, int, int]:
+ """Write a protocol buffer.
+
+ Args:
+ obj: Protocol buffer to write.
+
+ Returns:
+ (start_offset, end_offset, flush_offset) if successful,
+ None otherwise
+
+ """
+ raw_size = obj.ByteSize()
+ s = obj.SerializeToString()
+ assert len(s) == raw_size, "invalid serialization"
+ ret = self._write_data(s)
+ return ret
+
+ def close(self) -> None:
+ if self._fp is not None:
+ logger.info("close: %s", self._fname)
+ self._fp.close()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/file_pusher.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/file_pusher.py
new file mode 100644
index 0000000000000000000000000000000000000000..72b5b2d8ca41af9d44ccb284c78d600289570f6c
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/file_pusher.py
@@ -0,0 +1,177 @@
+import concurrent.futures
+import logging
+import os
+import queue
+import tempfile
+import threading
+import time
+from typing import TYPE_CHECKING, Optional, Tuple
+
+import wandb
+import wandb.util
+from wandb.filesync import stats, step_checksum, step_upload
+from wandb.sdk.lib.paths import LogicalPath
+
+if TYPE_CHECKING:
+ from wandb.sdk.artifacts.artifact_manifest import ArtifactManifest
+ from wandb.sdk.artifacts.artifact_saver import SaveFn
+ from wandb.sdk.internal import file_stream, internal_api
+ from wandb.sdk.internal.settings_static import SettingsStatic
+
+
+logger = logging.getLogger(__name__)
+
+
+class FilePusher:
+ """Parallel file upload class.
+
+ This manages uploading multiple files in parallel. It will restart a given file's
+ upload job if it receives a notification that that file has been modified. The
+ finish() method will block until all events have been processed and all uploads are
+ complete.
+ """
+
+ MAX_UPLOAD_JOBS = 64
+
+ def __init__(
+ self,
+ api: "internal_api.Api",
+ file_stream: "file_stream.FileStreamApi",
+ settings: Optional["SettingsStatic"] = None,
+ ) -> None:
+ self._api = api
+
+ # Temporary directory for copies we make of some file types to
+ # reduce the probability that the file gets changed while we're
+ # uploading it.
+ self._tempdir = tempfile.TemporaryDirectory("wandb")
+
+ self._stats = stats.Stats()
+
+ self._incoming_queue: queue.Queue[step_checksum.Event] = queue.Queue()
+ self._event_queue: queue.Queue[step_upload.Event] = queue.Queue()
+
+ self._step_checksum = step_checksum.StepChecksum(
+ self._api,
+ self._tempdir,
+ self._incoming_queue,
+ self._event_queue,
+ self._stats,
+ )
+ self._step_checksum.start()
+
+ self._step_upload = step_upload.StepUpload(
+ self._api,
+ self._stats,
+ self._event_queue,
+ self.MAX_UPLOAD_JOBS,
+ file_stream=file_stream,
+ settings=settings,
+ )
+ self._step_upload.start()
+
+ self._stats_thread_stop = threading.Event()
+ if os.environ.get("WANDB_DEBUG"):
+ # debug thread to monitor and report file pusher stats
+ self._stats_thread = threading.Thread(
+ target=self._file_pusher_stats,
+ daemon=True,
+ name="FPStatsThread",
+ )
+ self._stats_thread.start()
+
+ def _file_pusher_stats(self) -> None:
+ while not self._stats_thread_stop.is_set():
+ logger.info(f"FilePusher stats: {self._stats._stats}")
+ time.sleep(1)
+
+ def get_status(self) -> Tuple[bool, stats.Summary]:
+ running = self.is_alive()
+ summary = self._stats.summary()
+ return running, summary
+
+ def print_status(self, prefix: bool = True) -> None:
+ step = 0
+ spinner_states = ["-", "\\", "|", "/"]
+ stop = False
+ while True:
+ if not self.is_alive():
+ stop = True
+ summary = self._stats.summary()
+ line = f" {summary.uploaded_bytes / 1048576.0:.2f}MB of {summary.total_bytes / 1048576.0:.2f}MB uploaded ({summary.deduped_bytes / 1048576.0:.2f}MB deduped)\r"
+ line = spinner_states[step % 4] + line
+ step += 1
+ wandb.termlog(line, newline=False, prefix=prefix)
+ if stop:
+ break
+ time.sleep(0.25)
+ dedupe_fraction = (
+ summary.deduped_bytes / float(summary.total_bytes)
+ if summary.total_bytes > 0
+ else 0
+ )
+ if dedupe_fraction > 0.01:
+ wandb.termlog(
+ "W&B sync reduced upload amount by %.1f%% "
+ % (dedupe_fraction * 100),
+ prefix=prefix,
+ )
+ # clear progress line.
+ wandb.termlog(" " * 79, prefix=prefix)
+
+ def file_counts_by_category(self) -> stats.FileCountsByCategory:
+ return self._stats.file_counts_by_category()
+
+ def file_changed(self, save_name: LogicalPath, path: str, copy: bool = True):
+ """Tell the file pusher that a file's changed and should be uploaded.
+
+ Args:
+ save_name: string logical location of the file relative to the run
+ directory.
+ path: actual string path of the file to upload on the filesystem.
+ """
+ # Tests in linux were failing because wandb-events.jsonl didn't exist
+ if not os.path.exists(path) or not os.path.isfile(path):
+ return
+ if os.path.getsize(path) == 0:
+ return
+
+ event = step_checksum.RequestUpload(path, save_name, copy)
+ self._incoming_queue.put(event)
+
+ def store_manifest_files(
+ self,
+ manifest: "ArtifactManifest",
+ artifact_id: str,
+ save_fn: "SaveFn",
+ ) -> None:
+ event = step_checksum.RequestStoreManifestFiles(manifest, artifact_id, save_fn)
+ self._incoming_queue.put(event)
+
+ def commit_artifact(
+ self,
+ artifact_id: str,
+ *,
+ finalize: bool = True,
+ before_commit: step_upload.PreCommitFn,
+ result_future: "concurrent.futures.Future[None]",
+ ):
+ event = step_checksum.RequestCommitArtifact(
+ artifact_id, finalize, before_commit, result_future
+ )
+ self._incoming_queue.put(event)
+
+ def finish(self, callback: Optional[step_upload.OnRequestFinishFn] = None):
+ logger.info("shutting down file pusher")
+ self._incoming_queue.put(step_checksum.RequestFinish(callback))
+ self._stats_thread_stop.set()
+
+ def join(self) -> None:
+ # NOTE: must have called finish before join
+ logger.info("waiting for file pusher")
+ while self.is_alive():
+ time.sleep(0.5)
+ self._tempdir.cleanup()
+
+ def is_alive(self) -> bool:
+ return self._step_checksum.is_alive() or self._step_upload.is_alive()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/file_stream.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/file_stream.py
new file mode 100644
index 0000000000000000000000000000000000000000..644659c65281bcfd155d77c537ffaaf6f874d204
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/file_stream.py
@@ -0,0 +1,686 @@
+import functools
+import itertools
+import json
+import logging
+import os
+import queue
+import random
+import sys
+import threading
+import time
+from types import TracebackType
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Dict,
+ List,
+ NamedTuple,
+ Optional,
+ Set,
+ Tuple,
+ Type,
+ Union,
+)
+
+if TYPE_CHECKING:
+ from typing import TypedDict
+
+ class ProcessedChunk(TypedDict):
+ offset: int
+ content: List[str]
+
+ class ProcessedBinaryChunk(TypedDict):
+ offset: int
+ content: str
+ encoding: str
+
+
+import requests
+
+import wandb
+from wandb import util
+from wandb.sdk.internal import internal_api
+
+from ..lib import file_stream_utils
+
+logger = logging.getLogger(__name__)
+
+
+class Chunk(NamedTuple):
+ filename: str
+ data: str
+
+
+class DefaultFilePolicy:
+ def __init__(self, start_chunk_id: int = 0) -> None:
+ self._chunk_id = start_chunk_id
+ self.has_debug_log = False
+
+ def process_chunks(
+ self, chunks: List[Chunk]
+ ) -> Union[bool, "ProcessedChunk", "ProcessedBinaryChunk", List["ProcessedChunk"]]:
+ chunk_id = self._chunk_id
+ self._chunk_id += len(chunks)
+ return {"offset": chunk_id, "content": [c.data for c in chunks]}
+
+ # TODO: this is very inefficient, this is meant for temporary debugging and will be removed in future releases
+ def _debug_log(self, data: Any):
+ if self.has_debug_log or not os.environ.get("WANDB_DEBUG_FILESTREAM_LOG"):
+ return
+
+ loaded = json.loads(data)
+ if not isinstance(loaded, dict):
+ return
+
+ # get key size and convert to MB
+ key_sizes = [(k, len(json.dumps(v))) for k, v in loaded.items()]
+ key_msg = [f"{k}: {v / 1048576:.5f} MB" for k, v in key_sizes]
+ wandb.termerror(f"Step: {loaded['_step']} | {key_msg}", repeat=False)
+ self.has_debug_log = True
+
+
+class JsonlFilePolicy(DefaultFilePolicy):
+ def process_chunks(self, chunks: List[Chunk]) -> "ProcessedChunk":
+ chunk_id = self._chunk_id
+ # TODO: chunk_id is getting reset on each request...
+ self._chunk_id += len(chunks)
+ chunk_data = []
+ for chunk in chunks:
+ if len(chunk.data) > util.MAX_LINE_BYTES:
+ msg = f"Metric data exceeds maximum size of {util.to_human_size(util.MAX_LINE_BYTES)} ({util.to_human_size(len(chunk.data))})"
+ wandb.termerror(msg, repeat=False)
+ wandb._sentry.message(msg, repeat=False)
+ self._debug_log(chunk.data)
+ else:
+ chunk_data.append(chunk.data)
+
+ return {
+ "offset": chunk_id,
+ "content": chunk_data,
+ }
+
+
+class SummaryFilePolicy(DefaultFilePolicy):
+ def process_chunks(self, chunks: List[Chunk]) -> Union[bool, "ProcessedChunk"]:
+ data = chunks[-1].data
+ if len(data) > util.MAX_LINE_BYTES:
+ msg = f"Summary data exceeds maximum size of {util.to_human_size(util.MAX_LINE_BYTES)}. Dropping it."
+ wandb.termerror(msg, repeat=False)
+ wandb._sentry.message(msg, repeat=False)
+ self._debug_log(data)
+ return False
+ return {"offset": 0, "content": [data]}
+
+
+class StreamCRState:
+ r"""Stream state that tracks carriage returns.
+
+ There are two streams: stdout and stderr. We create two instances for each stream.
+ An instance holds state about:
+ found_cr: if a carriage return has been found in this stream.
+ cr: most recent offset (line number) where we found \r.
+ We update this offset with every progress bar update.
+ last_normal: most recent offset without a \r in this stream.
+ i.e. the most recent "normal" line.
+ """
+
+ found_cr: bool
+ cr: Optional[int]
+ last_normal: Optional[int]
+
+ def __init__(self) -> None:
+ self.found_cr = False
+ self.cr = None
+ self.last_normal = None
+
+
+class CRDedupeFilePolicy(DefaultFilePolicy):
+ r"""File stream policy for removing carriage-return erased characters.
+
+ This is what a terminal does. We use it for console output to reduce the amount of
+ data we need to send over the network (eg. for progress bars), while preserving the
+ output's appearance in the web app.
+
+ CR stands for "carriage return", for the character \r. It tells the terminal to move
+ the cursor back to the start of the current line. Progress bars (like tqdm) use \r
+ repeatedly to overwrite a line with newer updates. This gives the illusion of the
+ progress bar filling up in real-time.
+ """
+
+ def __init__(self, start_chunk_id: int = 0) -> None:
+ super().__init__(start_chunk_id=start_chunk_id)
+ self._prev_chunk = None
+
+ self.global_offset = 0
+ # cr refers to carriage return \r
+ self.stderr = StreamCRState()
+ self.stdout = StreamCRState()
+
+ @staticmethod
+ def get_consecutive_offsets(console: Dict[int, str]) -> List[List[int]]:
+ """Compress consecutive line numbers into an interval.
+
+ Args:
+ console: Dict[int, str] which maps offsets (line numbers) to lines of text.
+ It represents a mini version of our console dashboard on the UI.
+
+ Returns:
+ A list of intervals (we compress consecutive line numbers into an interval).
+
+ Example:
+ >>> console = {2: "", 3: "", 4: "", 5: "", 10: "", 11: "", 20: ""}
+ >>> get_consecutive_offsets(console)
+ [(2, 5), (10, 11), (20, 20)]
+ """
+ offsets = sorted(list(console.keys()))
+ intervals: List = []
+ for i, num in enumerate(offsets):
+ if i == 0:
+ intervals.append([num, num])
+ continue
+ largest = intervals[-1][1]
+ if num == largest + 1:
+ intervals[-1][1] = num
+ else:
+ intervals.append([num, num])
+ return intervals
+
+ @staticmethod
+ def split_chunk(chunk: Chunk) -> Tuple[str, str]:
+ r"""Split chunks.
+
+ Args:
+ chunk: object with two fields: filename (str) & data (str)
+ `chunk.data` is a str containing the lines we want. It usually contains \n or \r or both.
+ `chunk.data` has two possible formats (for the two streams - stdout and stderr):
+ - "2020-08-25T20:38:36.895321 this is my line of text\nsecond line\n"
+ - "ERROR 2020-08-25T20:38:36.895321 this is my line of text\nsecond line\nthird\n".
+
+ Here's another example with a carriage return \r.
+ - "ERROR 2020-08-25T20:38:36.895321 \r progress bar\n"
+
+ Returns:
+ A 2-tuple of strings.
+ First str is prefix, either "ERROR {timestamp} " or "{timestamp} ".
+ Second str is the rest of the string.
+
+ Example:
+ >>> chunk = Chunk(
+ ... filename="output.log",
+ ... data="ERROR 2020-08-25T20:38 this is my line of text\n",
+ ... )
+ >>> split_chunk(chunk)
+ ("ERROR 2020-08-25T20:38 ", "this is my line of text\n")
+ """
+ prefix = ""
+ token, rest = chunk.data.split(" ", 1)
+ if token == "ERROR":
+ prefix += token + " "
+ token, rest = rest.split(" ", 1)
+ prefix += token + " "
+ return prefix, rest
+
+ def process_chunks(self, chunks: List[Chunk]) -> List["ProcessedChunk"]:
+ r"""Process chunks.
+
+ Args:
+ chunks: List of Chunk objects. See description of chunk above in `split_chunk(...)`.
+
+ Returns:
+ List[Dict]. Each dict in the list contains two keys: an `offset` which holds the line number
+ and `content` which maps to a list of consecutive lines starting from that offset.
+ `offset` here means global line number in our console on the UI.
+
+ Example:
+ >>> chunks = [
+ Chunk("output.log", "ERROR 2020-08-25T20:38 this is my line of text\nboom\n"),
+ Chunk("output.log", "2020-08-25T20:38 this is test\n"),
+ ]
+ >>> process_chunks(chunks)
+ [
+ {"offset": 0, "content": [
+ "ERROR 2020-08-25T20:38 this is my line of text\n",
+ "ERROR 2020-08-25T20:38 boom\n",
+ "2020-08-25T20:38 this is test\n"
+ ]
+ }
+ ]
+ """
+ # Dict[int->str], each offset (line number) mapped to a line.
+ # Represents a mini-version of our console pane on the UI.
+ console = {}
+ sep = os.linesep
+
+ for c in chunks:
+ prefix, logs_str = self.split_chunk(c)
+ logs = logs_str.split(sep)
+
+ for line in logs:
+ stream = self.stderr if prefix.startswith("ERROR ") else self.stdout
+ if line.startswith("\r"):
+ # line starting with \r will always overwrite a previous offset.
+ offset: int = (
+ stream.cr
+ if (stream.found_cr and stream.cr is not None)
+ else (stream.last_normal or 0)
+ )
+ stream.cr = offset
+ stream.found_cr = True
+ console[offset] = prefix + line[1:] + "\n"
+
+ # Usually logs_str = "\r progress bar\n" for progress bar updates.
+ # If instead logs_str = "\r progress bar\n text\n text\n",
+ # treat this as the end of a progress bar and reset accordingly.
+ if (
+ logs_str.count(sep) > 1
+ and logs_str.replace(sep, "").count("\r") == 1
+ ):
+ stream.found_cr = False
+
+ elif line:
+ console[self.global_offset] = prefix + line + "\n"
+ stream.last_normal = self.global_offset
+ self.global_offset += 1
+
+ intervals = self.get_consecutive_offsets(console)
+ ret = []
+ for a, b in intervals:
+ processed_chunk: ProcessedChunk = {
+ "offset": self._chunk_id + a,
+ "content": [console[i] for i in range(a, b + 1)],
+ }
+ ret.append(processed_chunk)
+ return ret
+
+
+class FileStreamApi:
+ """Pushes chunks of files to our streaming endpoint.
+
+ This class is used as a singleton. It has a thread that serializes access to
+ the streaming endpoint and performs rate-limiting and batching.
+
+ TODO: Differentiate between binary/text encoding.
+ """
+
+ class Finish(NamedTuple):
+ exitcode: int
+
+ class Preempting(NamedTuple):
+ pass
+
+ class PushSuccess(NamedTuple):
+ artifact_id: str
+ save_name: str
+
+ MAX_ITEMS_PER_PUSH = 10000
+
+ def __init__(
+ self,
+ api: "internal_api.Api",
+ run_id: str,
+ start_time: float,
+ timeout: float = 0,
+ settings: Optional[dict] = None,
+ ) -> None:
+ settings = settings or dict()
+ # NOTE: exc_info is set in thread_except_body context and readable by calling threads
+ self._exc_info: Optional[
+ Union[
+ Tuple[Type[BaseException], BaseException, TracebackType],
+ Tuple[None, None, None],
+ ]
+ ] = None
+ self._settings = settings
+ self._api = api
+ self._run_id = run_id
+ self._start_time = start_time
+ self._client = requests.Session()
+ timeout = timeout or 0
+ if timeout > 0:
+ self._client.post = functools.partial(self._client.post, timeout=timeout) # type: ignore[method-assign]
+ self._client.auth = api.client.transport.session.auth
+ self._client.headers.update(api.client.transport.headers or {})
+ self._client.cookies.update(api.client.transport.cookies or {}) # type: ignore[no-untyped-call]
+ self._client.proxies.update(api.client.transport.session.proxies or {})
+ self._file_policies: Dict[str, DefaultFilePolicy] = {}
+ self._dropped_chunks: int = 0
+ self._queue: queue.Queue = queue.Queue()
+ self._thread = threading.Thread(target=self._thread_except_body)
+ # It seems we need to make this a daemon thread to get sync.py's atexit handler to run, which
+ # cleans this thread up.
+ self._thread.name = "FileStreamThread"
+ self._thread.daemon = True
+ self._init_endpoint()
+
+ def _init_endpoint(self) -> None:
+ settings = self._api.settings()
+ settings.update(self._settings)
+ self._endpoint = "{base}/files/{entity}/{project}/{run}/file_stream".format(
+ base=settings["base_url"],
+ entity=settings["entity"],
+ project=settings["project"],
+ run=self._run_id,
+ )
+
+ def start(self) -> None:
+ self._init_endpoint()
+ self._thread.start()
+
+ def set_default_file_policy(
+ self, filename: str, file_policy: "DefaultFilePolicy"
+ ) -> None:
+ """Set an upload policy for a file unless one has already been set."""
+ if filename not in self._file_policies:
+ self._file_policies[filename] = file_policy
+
+ def set_file_policy(self, filename: str, file_policy: "DefaultFilePolicy") -> None:
+ self._file_policies[filename] = file_policy
+
+ @property
+ def heartbeat_seconds(self) -> Union[int, float]:
+ # Defaults to 30
+ heartbeat_seconds: Union[int, float] = self._api.dynamic_settings[
+ "heartbeat_seconds"
+ ]
+ return heartbeat_seconds
+
+ def rate_limit_seconds(self) -> Union[int, float]:
+ run_time = time.time() - self._start_time
+ if run_time < 60:
+ return max(1.0, self.heartbeat_seconds / 15)
+ elif run_time < 300:
+ return max(2.5, self.heartbeat_seconds / 3)
+ else:
+ return max(5.0, self.heartbeat_seconds)
+
+ def _read_queue(self) -> List:
+ # called from the push thread (_thread_body), this does an initial read
+ # that'll block for up to rate_limit_seconds. Then it tries to read
+ # as much out of the queue as it can. We do this because the http post
+ # to the server happens within _thread_body, and can take longer than
+ # our rate limit. So next time we get a chance to read the queue we want
+ # read all the stuff that queue'd up since last time.
+ #
+ # If we have more than MAX_ITEMS_PER_PUSH in the queue then the push thread
+ # will get behind and data will buffer up in the queue.
+ return util.read_many_from_queue(
+ self._queue, self.MAX_ITEMS_PER_PUSH, self.rate_limit_seconds()
+ )
+
+ def _thread_body(self) -> None:
+ posted_data_time = time.time()
+ posted_anything_time = time.time()
+ ready_chunks = []
+ uploaded: Set[str] = set()
+ finished: Optional[FileStreamApi.Finish] = None
+ while finished is None:
+ items = self._read_queue()
+ for item in items:
+ if isinstance(item, self.Finish):
+ finished = item
+ elif isinstance(item, self.Preempting):
+ request_with_retry(
+ self._client.post,
+ self._endpoint,
+ json={
+ "complete": False,
+ "preempting": True,
+ "dropped": self._dropped_chunks,
+ "uploaded": list(uploaded),
+ },
+ )
+ uploaded = set()
+ elif isinstance(item, self.PushSuccess):
+ uploaded.add(item.save_name)
+ else:
+ # item is Chunk
+ ready_chunks.append(item)
+
+ cur_time = time.time()
+
+ if ready_chunks and (
+ finished or cur_time - posted_data_time > self.rate_limit_seconds()
+ ):
+ posted_data_time = cur_time
+ posted_anything_time = cur_time
+ success = self._send(ready_chunks, uploaded=uploaded)
+ ready_chunks = []
+ if success:
+ uploaded = set()
+
+ # If there aren't ready chunks or uploaded files, we still want to
+ # send regular heartbeats so the backend doesn't erroneously mark this
+ # run as crashed.
+ if cur_time - posted_anything_time > self.heartbeat_seconds:
+ posted_anything_time = cur_time
+
+ # If we encountered an error trying to publish the
+ # list of uploaded files, don't reset the `uploaded`
+ # list. Retry publishing the list on the next attempt.
+ if not isinstance(
+ request_with_retry(
+ self._client.post,
+ self._endpoint,
+ json={
+ "complete": False,
+ "failed": False,
+ "dropped": self._dropped_chunks,
+ "uploaded": list(uploaded),
+ },
+ ),
+ Exception,
+ ):
+ uploaded = set()
+
+ # post the final close message. (item is self.Finish instance now)
+ request_with_retry(
+ self._client.post,
+ self._endpoint,
+ json={
+ "complete": True,
+ "exitcode": int(finished.exitcode),
+ "dropped": self._dropped_chunks,
+ "uploaded": list(uploaded),
+ },
+ )
+
+ def _thread_except_body(self) -> None:
+ # TODO: Consolidate with internal_util.ExceptionThread
+ try:
+ self._thread_body()
+ except Exception:
+ exc_info = sys.exc_info()
+ self._exc_info = exc_info
+ logger.exception("generic exception in filestream thread")
+ wandb._sentry.exception(exc_info)
+ raise
+
+ def _handle_response(self, response: Union[Exception, "requests.Response"]) -> None:
+ """Log dropped chunks and updates dynamic settings."""
+ if isinstance(response, Exception):
+ wandb.termerror(
+ "Dropped streaming file chunk (see wandb/debug-internal.log)"
+ )
+ logger.exception(f"dropped chunk {response}")
+ self._dropped_chunks += 1
+ else:
+ parsed: Optional[dict] = None
+ try:
+ parsed = response.json()
+ except Exception:
+ pass
+ if isinstance(parsed, dict):
+ limits = parsed.get("limits")
+ if isinstance(limits, dict):
+ self._api.dynamic_settings.update(limits)
+
+ def _send(self, chunks: List[Chunk], uploaded: Optional[Set[str]] = None) -> bool:
+ uploaded_list = list(uploaded or [])
+ # create files dict. dict of pairs where chunks are a list of
+ # [chunk_id, chunk_data] tuples (as lists since this will be json).
+ files = {}
+ # Groupby needs group keys to be consecutive, so sort first.
+ chunks.sort(key=lambda c: c.filename)
+ for filename, file_chunks in itertools.groupby(chunks, lambda c: c.filename):
+ file_chunks_list = list(file_chunks) # groupby returns iterator
+ # Specific file policies are set by internal/sender.py
+ self.set_default_file_policy(filename, DefaultFilePolicy())
+ files[filename] = self._file_policies[filename].process_chunks(
+ file_chunks_list
+ )
+ if not files[filename]:
+ del files[filename]
+
+ for fs in file_stream_utils.split_files(files, max_bytes=util.MAX_LINE_BYTES):
+ self._handle_response(
+ request_with_retry(
+ self._client.post,
+ self._endpoint,
+ json={"files": fs, "dropped": self._dropped_chunks},
+ retry_callback=self._api.retry_callback,
+ )
+ )
+
+ if uploaded_list:
+ if isinstance(
+ request_with_retry(
+ self._client.post,
+ self._endpoint,
+ json={
+ "complete": False,
+ "failed": False,
+ "dropped": self._dropped_chunks,
+ "uploaded": uploaded_list,
+ },
+ ),
+ Exception,
+ ):
+ return False
+ return True
+
+ def stream_file(self, path: str) -> None:
+ name = path.split("/")[-1]
+ with open(path) as f:
+ self._send([Chunk(name, line) for line in f])
+
+ def enqueue_preempting(self) -> None:
+ self._queue.put(self.Preempting())
+
+ def push(self, filename: str, data: str) -> None:
+ """Push a chunk of a file to the streaming endpoint.
+
+ Args:
+ filename: Name of file to append to.
+ data: Text to append to the file.
+ """
+ self._queue.put(Chunk(filename, data))
+
+ def push_success(self, artifact_id: str, save_name: str) -> None:
+ """Notification that a file upload has been successfully completed.
+
+ Args:
+ artifact_id: ID of artifact
+ save_name: saved name of the uploaded file
+ """
+ self._queue.put(self.PushSuccess(artifact_id, save_name))
+
+ def finish(self, exitcode: int) -> None:
+ """Clean up.
+
+ Anything pushed after finish will be dropped.
+
+ Args:
+ exitcode: The exitcode of the watched process.
+ """
+ logger.info("file stream finish called")
+ self._queue.put(self.Finish(exitcode))
+ # TODO(jhr): join on a thread which exited with an exception is a noop, clean up this path
+ self._thread.join()
+ logger.info("file stream finish is done")
+ if self._exc_info:
+ logger.error("FileStream exception", exc_info=self._exc_info)
+ # re-raising the original exception, will get re-caught in internal.py for the sender thread
+ if self._exc_info[1] is not None:
+ raise self._exc_info[1].with_traceback(self._exc_info[2])
+
+
+MAX_SLEEP_SECONDS = 60 * 5
+
+
+def request_with_retry(
+ func: Callable,
+ *args: Any,
+ **kwargs: Any,
+) -> Union["requests.Response", "requests.RequestException"]:
+ """Perform a requests http call, retrying with exponential backoff.
+
+ Args:
+ func: An http-requesting function to call, like requests.post
+ max_retries: Maximum retries before giving up.
+ By default, we retry 30 times in ~2 hours before dropping the chunk
+ *args: passed through to func
+ **kwargs: passed through to func
+ """
+ max_retries: int = kwargs.pop("max_retries", 30)
+ retry_callback: Optional[Callable] = kwargs.pop("retry_callback", None)
+ sleep = 2
+ retry_count = 0
+ while True:
+ try:
+ response: requests.Response = func(*args, **kwargs)
+ response.raise_for_status()
+ return response
+ except (
+ requests.exceptions.ConnectionError,
+ requests.exceptions.HTTPError,
+ requests.exceptions.Timeout,
+ ) as e:
+ if isinstance(e, requests.exceptions.HTTPError):
+ # Non-retriable HTTP errors.
+ #
+ # We retry 500s just to be cautious, and because the back end
+ # returns them when there are infrastructure issues. If retrying
+ # some request winds up being problematic, we'll change the
+ # back end to indicate that it shouldn't be retried.
+ if e.response is not None and e.response.status_code in {
+ 400,
+ 403,
+ 404,
+ 409,
+ }:
+ return e
+
+ if retry_count == max_retries:
+ return e
+ retry_count += 1
+ delay = sleep + random.random() * 0.25 * sleep
+ if isinstance(e, requests.exceptions.HTTPError) and (
+ e.response is not None and e.response.status_code == 429
+ ):
+ err_str = (
+ f"Filestream rate limit exceeded, retrying in {delay:.1f} seconds. "
+ )
+ if retry_callback:
+ retry_callback(e.response.status_code, err_str)
+ logger.info(err_str)
+ else:
+ logger.warning(
+ "requests_with_retry encountered retryable exception: %s. func: %s, args: %s, kwargs: %s",
+ e,
+ func,
+ args,
+ kwargs,
+ )
+ time.sleep(delay)
+ sleep *= 2
+ if sleep > MAX_SLEEP_SECONDS:
+ sleep = MAX_SLEEP_SECONDS
+ except requests.exceptions.RequestException as e:
+ error_message = "unknown error"
+ try:
+ error_message = response.json()["error"] # todo: clean this up
+ except Exception:
+ pass
+ logger.exception(f"requests_with_retry error: {error_message}")
+ return e
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/handler.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/handler.py
new file mode 100644
index 0000000000000000000000000000000000000000..4defa1f2bc76f83bf267f5bc6f3fcd95780e950f
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/handler.py
@@ -0,0 +1,854 @@
+"""Handle Manager."""
+
+import json
+import logging
+import math
+import numbers
+import time
+from collections import defaultdict
+from queue import Queue
+from threading import Event
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Dict,
+ Iterable,
+ List,
+ Optional,
+ Sequence,
+ Tuple,
+ cast,
+)
+
+from wandb.errors.links import url_registry
+from wandb.proto.wandb_internal_pb2 import (
+ HistoryRecord,
+ InternalMessages,
+ MetricRecord,
+ Record,
+ Result,
+ RunRecord,
+ SampledHistoryItem,
+ SummaryItem,
+ SummaryRecord,
+ SummaryRecordRequest,
+)
+
+from ..interface.interface_queue import InterfaceQueue
+from ..lib import handler_util, proto_util
+from . import context, sample, tb_watcher
+from .settings_static import SettingsStatic
+
+if TYPE_CHECKING:
+ from wandb.proto.wandb_internal_pb2 import MetricSummary
+
+
+SummaryDict = Dict[str, Any]
+
+logger = logging.getLogger(__name__)
+
+# Update (March 5, 2024): Since ~2020/2021, when constructing the summary
+# object, we had replaced the artifact path for media types with the latest
+# artifact path. The primary purpose of this was to support live updating of
+# media objects in the UI (since the default artifact path was fully qualified
+# and would not update). However, in March of 2024, a bug was discovered with
+# this approach which causes this path to be incorrect in cases where the media
+# object is logged to another artifact before being logged to the run. Setting
+# this to `False` disables this copy behavior. The impact is that users will
+# need to refresh to see updates. Ironically, this updating behavior is not
+# currently supported in the UI, so the impact of this change is minimal.
+REPLACE_SUMMARY_ART_PATH_WITH_LATEST = False
+
+
+def _dict_nested_set(target: Dict[str, Any], key_list: Sequence[str], v: Any) -> None:
+ # recurse down the dictionary structure:
+
+ for k in key_list[:-1]:
+ target.setdefault(k, {})
+ new_target = target.get(k)
+ if TYPE_CHECKING:
+ new_target = cast(Dict[str, Any], new_target)
+ target = new_target
+ # use the last element of the key to write the leaf:
+ target[key_list[-1]] = v
+
+
+class HandleManager:
+ _consolidated_summary: SummaryDict
+ _sampled_history: Dict[str, sample.UniformSampleAccumulator]
+ _partial_history: Dict[str, Any]
+ _run_proto: Optional[RunRecord]
+ _settings: SettingsStatic
+ _record_q: "Queue[Record]"
+ _result_q: "Queue[Result]"
+ _stopped: Event
+ _writer_q: "Queue[Record]"
+ _interface: InterfaceQueue
+ _tb_watcher: Optional[tb_watcher.TBWatcher]
+ _metric_defines: Dict[str, MetricRecord]
+ _metric_globs: Dict[str, MetricRecord]
+ _metric_track: Dict[Tuple[str, ...], float]
+ _metric_copy: Dict[Tuple[str, ...], Any]
+ _track_time: Optional[float]
+ _accumulate_time: float
+ _run_start_time: Optional[float]
+ _context_keeper: context.ContextKeeper
+
+ def __init__(
+ self,
+ settings: SettingsStatic,
+ record_q: "Queue[Record]",
+ result_q: "Queue[Result]",
+ stopped: Event,
+ writer_q: "Queue[Record]",
+ interface: InterfaceQueue,
+ context_keeper: context.ContextKeeper,
+ ) -> None:
+ self._settings = settings
+ self._record_q = record_q
+ self._result_q = result_q
+ self._stopped = stopped
+ self._writer_q = writer_q
+ self._interface = interface
+ self._context_keeper = context_keeper
+
+ self._tb_watcher = None
+ self._step = 0
+
+ self._track_time = None
+ self._accumulate_time = 0
+ self._run_start_time = None
+
+ # keep track of summary from key/val updates
+ self._consolidated_summary = dict()
+ self._sampled_history = defaultdict(sample.UniformSampleAccumulator)
+ self._run_proto = None
+ self._partial_history = dict()
+ self._metric_defines = defaultdict(MetricRecord)
+ self._metric_globs = defaultdict(MetricRecord)
+ self._metric_track = dict()
+ self._metric_copy = dict()
+ self._internal_messages = InternalMessages()
+
+ self._dropped_history = False
+
+ def __len__(self) -> int:
+ return self._record_q.qsize()
+
+ def handle(self, record: Record) -> None:
+ self._context_keeper.add_from_record(record)
+ record_type = record.WhichOneof("record_type")
+ assert record_type
+ handler_str = "handle_" + record_type
+ handler: Callable[[Record], None] = getattr(self, handler_str, None) # type: ignore
+ assert handler, f"unknown handle: {handler_str}" # type: ignore
+ handler(record)
+
+ def handle_request(self, record: Record) -> None:
+ request_type = record.request.WhichOneof("request_type")
+ assert request_type
+ handler_str = "handle_request_" + request_type
+ handler: Callable[[Record], None] = getattr(self, handler_str, None) # type: ignore
+ if request_type != "network_status":
+ logger.debug(f"handle_request: {request_type}")
+ assert handler, f"unknown handle: {handler_str}" # type: ignore
+ handler(record)
+
+ def _dispatch_record(self, record: Record, always_send: bool = False) -> None:
+ if always_send:
+ record.control.always_send = True
+ self._writer_q.put(record)
+
+ def _respond_result(self, result: Result) -> None:
+ context_id = context.context_id_from_result(result)
+ self._context_keeper.release(context_id)
+ self._result_q.put(result)
+
+ def debounce(self) -> None:
+ pass
+
+ def handle_request_cancel(self, record: Record) -> None:
+ self._dispatch_record(record)
+
+ def handle_request_defer(self, record: Record) -> None:
+ defer = record.request.defer
+ state = defer.state
+
+ logger.info(f"handle defer: {state}")
+ if state == defer.FLUSH_TB:
+ if self._tb_watcher:
+ # shutdown tensorboard workers so we get all metrics flushed
+ self._tb_watcher.finish()
+ self._tb_watcher = None
+ elif state == defer.FLUSH_PARTIAL_HISTORY:
+ self._flush_partial_history()
+ elif state == defer.FLUSH_SUM:
+ self._save_summary(self._consolidated_summary, flush=True)
+
+ # defer is used to drive the sender finish state machine
+ self._dispatch_record(record, always_send=True)
+
+ def handle_request_python_packages(self, record: Record) -> None:
+ self._dispatch_record(record)
+
+ def handle_run(self, record: Record) -> None:
+ if self._settings._offline:
+ self._run_proto = record.run
+ result = proto_util._result_from_record(record)
+ result.run_result.run.CopyFrom(record.run)
+ self._respond_result(result)
+ self._dispatch_record(record)
+
+ def handle_stats(self, record: Record) -> None:
+ self._dispatch_record(record)
+
+ def handle_config(self, record: Record) -> None:
+ self._dispatch_record(record)
+
+ def handle_output(self, record: Record) -> None:
+ self._dispatch_record(record)
+
+ def handle_output_raw(self, record: Record) -> None:
+ self._dispatch_record(record)
+
+ def handle_files(self, record: Record) -> None:
+ self._dispatch_record(record)
+
+ def handle_request_link_artifact(self, record: Record) -> None:
+ self._dispatch_record(record)
+
+ def handle_use_artifact(self, record: Record) -> None:
+ self._dispatch_record(record)
+
+ def handle_artifact(self, record: Record) -> None:
+ self._dispatch_record(record)
+
+ def handle_alert(self, record: Record) -> None:
+ self._dispatch_record(record)
+
+ def _save_summary(self, summary_dict: SummaryDict, flush: bool = False) -> None:
+ summary = SummaryRecord()
+ for k, v in summary_dict.items():
+ update = summary.update.add()
+ update.key = k
+ update.value_json = json.dumps(v)
+ if flush:
+ record = Record(summary=summary)
+ self._dispatch_record(record)
+ elif not self._settings._offline:
+ # Send this summary update as a request since we aren't persisting every update
+ summary_record = SummaryRecordRequest(summary=summary)
+ request_record = self._interface._make_request(
+ summary_record=summary_record
+ )
+ self._dispatch_record(request_record)
+
+ def _save_history(
+ self,
+ history: HistoryRecord,
+ ) -> None:
+ for item in history.item:
+ # TODO(jhr) save nested keys?
+ k = item.key
+ v = json.loads(item.value_json)
+ if isinstance(v, numbers.Real):
+ self._sampled_history[k].add(v)
+
+ def _update_summary_metrics(
+ self,
+ s: "MetricSummary",
+ kl: List[str],
+ v: "numbers.Real",
+ float_v: float,
+ goal_max: Optional[bool],
+ ) -> bool:
+ updated = False
+ best_key: Optional[Tuple[str, ...]] = None
+ if s.none:
+ return False
+ if s.copy:
+ # non-key list copy already done in _update_summary
+ if len(kl) > 1:
+ _dict_nested_set(self._consolidated_summary, kl, v)
+ return True
+ if s.last:
+ last_key = tuple(kl + ["last"])
+ old_last = self._metric_track.get(last_key)
+ if old_last is None or float_v != old_last:
+ self._metric_track[last_key] = float_v
+ _dict_nested_set(self._consolidated_summary, last_key, v)
+ updated = True
+ if s.best:
+ best_key = tuple(kl + ["best"])
+ if s.max or best_key and goal_max:
+ max_key = tuple(kl + ["max"])
+ old_max = self._metric_track.get(max_key)
+ if old_max is None or float_v > old_max:
+ self._metric_track[max_key] = float_v
+ if s.max:
+ _dict_nested_set(self._consolidated_summary, max_key, v)
+ updated = True
+ if best_key:
+ _dict_nested_set(self._consolidated_summary, best_key, v)
+ updated = True
+ # defaulting to minimize if goal is not specified
+ if s.min or best_key and not goal_max:
+ min_key = tuple(kl + ["min"])
+ old_min = self._metric_track.get(min_key)
+ if old_min is None or float_v < old_min:
+ self._metric_track[min_key] = float_v
+ if s.min:
+ _dict_nested_set(self._consolidated_summary, min_key, v)
+ updated = True
+ if best_key:
+ _dict_nested_set(self._consolidated_summary, best_key, v)
+ updated = True
+ if s.mean:
+ tot_key = tuple(kl + ["tot"])
+ num_key = tuple(kl + ["num"])
+ avg_key = tuple(kl + ["mean"])
+ tot = self._metric_track.get(tot_key, 0.0)
+ num = self._metric_track.get(num_key, 0)
+ tot += float_v
+ num += 1
+ self._metric_track[tot_key] = tot
+ self._metric_track[num_key] = num
+ _dict_nested_set(self._consolidated_summary, avg_key, tot / num)
+ updated = True
+ return updated
+
+ def _update_summary_leaf(
+ self,
+ kl: List[str],
+ v: Any,
+ d: Optional[MetricRecord] = None,
+ ) -> bool:
+ has_summary = d and d.HasField("summary")
+ if len(kl) == 1:
+ copy_key = tuple(kl)
+ old_copy = self._metric_copy.get(copy_key)
+ if old_copy is None or v != old_copy:
+ self._metric_copy[copy_key] = v
+ # Store copy metric if not specified, or copy behavior
+ if not has_summary or (d and d.summary.copy):
+ self._consolidated_summary[kl[0]] = v
+ return True
+ if not d:
+ return False
+ if not has_summary:
+ return False
+ if not isinstance(v, numbers.Real):
+ return False
+ if math.isnan(v):
+ return False
+ float_v = float(v)
+ goal_max = None
+ if d.goal:
+ goal_max = d.goal == d.GOAL_MAXIMIZE
+ if self._update_summary_metrics(
+ d.summary, kl=kl, v=v, float_v=float_v, goal_max=goal_max
+ ):
+ return True
+ return False
+
+ def _update_summary_list(
+ self,
+ kl: List[str],
+ v: Any,
+ d: Optional[MetricRecord] = None,
+ ) -> bool:
+ metric_key = ".".join([k.replace(".", "\\.") for k in kl])
+ d = self._metric_defines.get(metric_key, d)
+ # if the dict has _type key, it's a wandb table object
+ if isinstance(v, dict) and not handler_util.metric_is_wandb_dict(v):
+ updated = False
+ for nk, nv in v.items():
+ if self._update_summary_list(kl=kl[:] + [nk], v=nv, d=d):
+ updated = True
+ return updated
+ # If the dict is a media object, update the pointer to the latest alias
+ elif (
+ REPLACE_SUMMARY_ART_PATH_WITH_LATEST
+ and isinstance(v, dict)
+ and handler_util.metric_is_wandb_dict(v)
+ ):
+ if "_latest_artifact_path" in v and "artifact_path" in v:
+ # TODO: Make non-destructive?
+ v["artifact_path"] = v["_latest_artifact_path"]
+ updated = self._update_summary_leaf(kl=kl, v=v, d=d)
+ return updated
+
+ def _update_summary_media_objects(self, v: Dict[str, Any]) -> Dict[str, Any]:
+ # For now, non-recursive - just top level
+ for nk, nv in v.items():
+ if REPLACE_SUMMARY_ART_PATH_WITH_LATEST and (
+ isinstance(nv, dict)
+ and handler_util.metric_is_wandb_dict(nv)
+ and "_latest_artifact_path" in nv
+ and "artifact_path" in nv
+ ):
+ # TODO: Make non-destructive?
+ nv["artifact_path"] = nv["_latest_artifact_path"]
+ v[nk] = nv
+ return v
+
+ def _update_summary(self, history_dict: Dict[str, Any]) -> List[str]:
+ # keep old behavior fast path if no define metrics have been used
+ if not self._metric_defines:
+ history_dict = self._update_summary_media_objects(history_dict)
+ self._consolidated_summary.update(history_dict)
+ return list(history_dict.keys())
+ updated_keys = []
+ for k, v in history_dict.items():
+ if self._update_summary_list(kl=[k], v=v):
+ updated_keys.append(k)
+ return updated_keys
+
+ def _history_assign_step(
+ self,
+ history: HistoryRecord,
+ history_dict: Dict[str, Any],
+ ) -> None:
+ has_step = history.HasField("step")
+ item = history.item.add()
+ item.key = "_step"
+ if has_step:
+ step = history.step.num
+ history_dict["_step"] = step
+ item.value_json = json.dumps(step)
+ self._step = step + 1
+ else:
+ history_dict["_step"] = self._step
+ item.value_json = json.dumps(self._step)
+ self._step += 1
+
+ def _history_define_metric(self, hkey: str) -> Optional[MetricRecord]:
+ """Check for hkey match in glob metrics and return the defined metric."""
+ # Dont define metric for internal metrics
+ if hkey.startswith("_"):
+ return None
+ for k, mglob in self._metric_globs.items():
+ if k.endswith("*"):
+ if hkey.startswith(k[:-1]):
+ m = MetricRecord()
+ m.CopyFrom(mglob)
+ m.ClearField("glob_name")
+ m.options.defined = False
+ m.name = hkey
+ return m
+ return None
+
+ def _history_update_leaf(
+ self,
+ kl: List[str],
+ v: Any,
+ history_dict: Dict[str, Any],
+ update_history: Dict[str, Any],
+ ) -> None:
+ hkey = ".".join([k.replace(".", "\\.") for k in kl])
+ m = self._metric_defines.get(hkey)
+ if not m:
+ m = self._history_define_metric(hkey)
+ if not m:
+ return
+ mr = Record()
+ mr.metric.CopyFrom(m)
+ mr.control.local = True # Dont store this, just send it
+ self._handle_defined_metric(mr)
+
+ if m.options.step_sync and m.step_metric:
+ if m.step_metric not in history_dict:
+ copy_key = tuple([m.step_metric])
+ step = self._metric_copy.get(copy_key)
+ if step is not None:
+ update_history[m.step_metric] = step
+
+ def _history_update_list(
+ self,
+ kl: List[str],
+ v: Any,
+ history_dict: Dict[str, Any],
+ update_history: Dict[str, Any],
+ ) -> None:
+ if isinstance(v, dict):
+ for nk, nv in v.items():
+ self._history_update_list(
+ kl=kl[:] + [nk],
+ v=nv,
+ history_dict=history_dict,
+ update_history=update_history,
+ )
+ return
+ self._history_update_leaf(
+ kl=kl, v=v, history_dict=history_dict, update_history=update_history
+ )
+
+ def _history_update(
+ self,
+ history: HistoryRecord,
+ history_dict: Dict[str, Any],
+ ) -> None:
+ # if syncing an old run, we can skip this logic
+ if history_dict.get("_step") is None:
+ self._history_assign_step(history, history_dict)
+
+ update_history: Dict[str, Any] = {}
+ # Look for metric matches
+ if self._metric_defines or self._metric_globs:
+ for hkey, hval in history_dict.items():
+ self._history_update_list([hkey], hval, history_dict, update_history)
+
+ if update_history:
+ history_dict.update(update_history)
+ for k, v in update_history.items():
+ item = history.item.add()
+ item.key = k
+ item.value_json = json.dumps(v)
+
+ def handle_history(self, record: Record) -> None:
+ history_dict = proto_util.dict_from_proto_list(record.history.item)
+
+ # Inject _runtime if it is not present
+ if history_dict is not None:
+ if "_runtime" not in history_dict:
+ self._history_assign_runtime(record.history, history_dict)
+
+ self._history_update(record.history, history_dict)
+ self._dispatch_record(record)
+ self._save_history(record.history)
+ # update summary from history
+ updated_keys = self._update_summary(history_dict)
+ if updated_keys:
+ updated_items = {k: self._consolidated_summary[k] for k in updated_keys}
+ self._save_summary(updated_items)
+
+ def _flush_partial_history(
+ self,
+ step: Optional[int] = None,
+ ) -> None:
+ if not self._partial_history:
+ return
+
+ history = HistoryRecord()
+ for k, v in self._partial_history.items():
+ item = history.item.add()
+ item.key = k
+ item.value_json = json.dumps(v)
+ if step is not None:
+ history.step.num = step
+ self.handle_history(Record(history=history))
+ self._partial_history = {}
+
+ def handle_request_sender_mark_report(self, record: Record) -> None:
+ self._dispatch_record(record, always_send=True)
+
+ def handle_request_status_report(self, record: Record) -> None:
+ self._dispatch_record(record, always_send=True)
+
+ def handle_request_partial_history(self, record: Record) -> None:
+ partial_history = record.request.partial_history
+
+ flush = None
+ if partial_history.HasField("action"):
+ flush = partial_history.action.flush
+
+ step = None
+ if partial_history.HasField("step"):
+ step = partial_history.step.num
+
+ history_dict = proto_util.dict_from_proto_list(partial_history.item)
+ if step is not None:
+ if step < self._step:
+ if not self._dropped_history:
+ message = (
+ "Step only supports monotonically increasing values, use define_metric to set a custom x "
+ f"axis. For details see: {url_registry.url('define-metric')}"
+ )
+ self._internal_messages.warning.append(message)
+ self._dropped_history = True
+ message = (
+ f"(User provided step: {step} is less than current step: {self._step}. "
+ f"Dropping entry: {history_dict})."
+ )
+ self._internal_messages.warning.append(message)
+ return
+ elif step > self._step:
+ self._flush_partial_history()
+ self._step = step
+ elif flush is None:
+ flush = True
+
+ self._partial_history.update(history_dict)
+
+ if flush:
+ self._flush_partial_history(self._step)
+
+ def handle_summary(self, record: Record) -> None:
+ summary = record.summary
+ for item in summary.update:
+ if len(item.nested_key) > 0:
+ # we use either key or nested_key -- not both
+ assert item.key == ""
+ key = tuple(item.nested_key)
+ else:
+ # no counter-assertion here, because technically
+ # summary[""] is valid
+ key = (item.key,)
+
+ target = self._consolidated_summary
+
+ # recurse down the dictionary structure:
+ for prop in key[:-1]:
+ target = target[prop]
+
+ # use the last element of the key to write the leaf:
+ target[key[-1]] = json.loads(item.value_json)
+
+ for item in summary.remove:
+ if len(item.nested_key) > 0:
+ # we use either key or nested_key -- not both
+ assert item.key == ""
+ key = tuple(item.nested_key)
+ else:
+ # no counter-assertion here, because technically
+ # summary[""] is valid
+ key = (item.key,)
+
+ target = self._consolidated_summary
+
+ # recurse down the dictionary structure:
+ for prop in key[:-1]:
+ target = target[prop]
+
+ # use the last element of the key to erase the leaf:
+ del target[key[-1]]
+
+ self._save_summary(self._consolidated_summary)
+
+ def handle_exit(self, record: Record) -> None:
+ if self._track_time is not None:
+ self._accumulate_time += time.time() - self._track_time
+ record.exit.runtime = int(self._accumulate_time)
+ self._dispatch_record(record, always_send=True)
+
+ def handle_final(self, record: Record) -> None:
+ self._dispatch_record(record, always_send=True)
+
+ def handle_preempting(self, record: Record) -> None:
+ self._dispatch_record(record)
+
+ def handle_header(self, record: Record) -> None:
+ self._dispatch_record(record)
+
+ def handle_footer(self, record: Record) -> None:
+ self._dispatch_record(record)
+
+ def handle_metadata(self, record: Record) -> None:
+ self._dispatch_record(record)
+
+ def handle_request_attach(self, record: Record) -> None:
+ result = proto_util._result_from_record(record)
+ attach_id = record.request.attach.attach_id
+ assert attach_id
+ assert self._run_proto
+ result.response.attach_response.run.CopyFrom(self._run_proto)
+ self._respond_result(result)
+
+ def handle_request_log_artifact(self, record: Record) -> None:
+ self._dispatch_record(record)
+
+ def handle_telemetry(self, record: Record) -> None:
+ self._dispatch_record(record)
+
+ def handle_request_run_start(self, record: Record) -> None:
+ run_start = record.request.run_start
+ assert run_start
+ assert run_start.run
+
+ self._run_proto = run_start.run
+
+ self._run_start_time = run_start.run.start_time.ToMicroseconds() / 1e6
+
+ self._track_time = time.time()
+ if run_start.run.resumed and run_start.run.runtime:
+ self._accumulate_time = run_start.run.runtime
+ else:
+ self._accumulate_time = 0
+
+ self._tb_watcher = tb_watcher.TBWatcher(
+ self._settings, interface=self._interface, run_proto=run_start.run
+ )
+
+ if run_start.run.resumed or run_start.run.forked:
+ self._step = run_start.run.starting_step
+ result = proto_util._result_from_record(record)
+ self._respond_result(result)
+
+ def handle_request_resume(self, record: Record) -> None:
+ if self._track_time is not None:
+ self._accumulate_time += time.time() - self._track_time
+ self._track_time = time.time()
+
+ def handle_request_pause(self, record: Record) -> None:
+ if self._track_time is not None:
+ self._accumulate_time += time.time() - self._track_time
+ self._track_time = None
+
+ def handle_request_poll_exit(self, record: Record) -> None:
+ self._dispatch_record(record, always_send=True)
+
+ def handle_request_stop_status(self, record: Record) -> None:
+ self._dispatch_record(record)
+
+ def handle_request_network_status(self, record: Record) -> None:
+ self._dispatch_record(record)
+
+ def handle_request_internal_messages(self, record: Record) -> None:
+ result = proto_util._result_from_record(record)
+ result.response.internal_messages_response.messages.CopyFrom(
+ self._internal_messages
+ )
+ self._internal_messages.Clear()
+ self._respond_result(result)
+
+ def handle_request_status(self, record: Record) -> None:
+ result = proto_util._result_from_record(record)
+ self._respond_result(result)
+
+ def handle_request_get_summary(self, record: Record) -> None:
+ result = proto_util._result_from_record(record)
+ for key, value in self._consolidated_summary.items():
+ item = SummaryItem()
+ item.key = key
+ item.value_json = json.dumps(value)
+ result.response.get_summary_response.item.append(item)
+ self._respond_result(result)
+
+ def handle_tbrecord(self, record: Record) -> None:
+ logger.info("handling tbrecord: %s", record)
+ if self._tb_watcher:
+ tbrecord = record.tbrecord
+ self._tb_watcher.add(tbrecord.log_dir, tbrecord.save, tbrecord.root_dir)
+ self._dispatch_record(record)
+
+ def _handle_defined_metric(self, record: Record) -> None:
+ metric = record.metric
+ if metric._control.overwrite:
+ self._metric_defines[metric.name].CopyFrom(metric)
+ else:
+ self._metric_defines[metric.name].MergeFrom(metric)
+
+ # before dispatching, make sure step_metric is defined, if not define it and
+ # dispatch it locally first
+ metric = self._metric_defines[metric.name]
+ if metric.step_metric and metric.step_metric not in self._metric_defines:
+ m = MetricRecord(name=metric.step_metric)
+ self._metric_defines[metric.step_metric] = m
+ mr = Record()
+ mr.metric.CopyFrom(m)
+ mr.control.local = True # Don't store this, just send it
+ self._dispatch_record(mr)
+
+ self._dispatch_record(record)
+
+ def _handle_glob_metric(self, record: Record) -> None:
+ metric = record.metric
+ if metric._control.overwrite:
+ self._metric_globs[metric.glob_name].CopyFrom(metric)
+ else:
+ self._metric_globs[metric.glob_name].MergeFrom(metric)
+ self._dispatch_record(record)
+
+ def handle_metric(self, record: Record) -> None:
+ """Handle MetricRecord.
+
+ Walkthrough of the life of a MetricRecord:
+
+ Metric defined:
+ - run.define_metric() parses arguments create wandb_metric.Metric
+ - build MetricRecord publish to interface
+ - handler (this function) keeps list of metrics published:
+ - self._metric_defines: Fully defined metrics
+ - self._metric_globs: metrics that have a wildcard
+ - dispatch writer and sender thread
+ - writer: records are saved to persistent store
+ - sender: fully defined metrics get mapped into metadata for UI
+
+ History logged:
+ - handle_history
+ - check if metric matches _metric_defines
+ - if not, check if metric matches _metric_globs
+ - if _metric globs match, generate defined metric and call _handle_metric
+
+ Args:
+ record (Record): Metric record to process
+ """
+ if record.metric.name:
+ self._handle_defined_metric(record)
+ elif record.metric.glob_name:
+ self._handle_glob_metric(record)
+
+ def handle_request_sampled_history(self, record: Record) -> None:
+ result = proto_util._result_from_record(record)
+ for key, sampled in self._sampled_history.items():
+ item = SampledHistoryItem()
+ item.key = key
+ values: Iterable[Any] = sampled.get()
+ if all(isinstance(i, numbers.Integral) for i in values):
+ try:
+ item.values_int.extend(values)
+ except ValueError:
+ # it is safe to ignore these as this is for display information
+ pass
+ elif all(isinstance(i, numbers.Real) for i in values):
+ item.values_float.extend(values)
+ result.response.sampled_history_response.item.append(item)
+ self._respond_result(result)
+
+ def handle_request_keepalive(self, record: Record) -> None:
+ """Handle a keepalive request.
+
+ Keepalive is a noop, we just want to verify transport is alive.
+ """
+
+ def handle_request_run_status(self, record: Record) -> None:
+ self._dispatch_record(record, always_send=True)
+
+ def handle_request_shutdown(self, record: Record) -> None:
+ # TODO(jhr): should we drain things and stop new requests from coming in?
+ result = proto_util._result_from_record(record)
+ self._respond_result(result)
+ self._stopped.set()
+
+ def handle_request_operations(self, record: Record) -> None:
+ """No-op. Not implemented for the legacy-service."""
+ self._respond_result(proto_util._result_from_record(record))
+
+ def finish(self) -> None:
+ logger.info("shutting down handler")
+ if self._tb_watcher:
+ self._tb_watcher.finish()
+ # self._context_keeper._debug_print_orphans()
+
+ def __next__(self) -> Record:
+ return self._record_q.get(block=True)
+
+ next = __next__
+
+ def _history_assign_runtime(
+ self,
+ history: HistoryRecord,
+ history_dict: Dict[str, Any],
+ ) -> None:
+ # _runtime calculation is meaningless if there is no _timestamp
+ if "_timestamp" not in history_dict:
+ return
+ # if it is offline sync, self._run_start_time is None
+ # in that case set it to the first tfevent timestamp
+ if self._run_start_time is None:
+ self._run_start_time = history_dict["_timestamp"]
+ history_dict["_runtime"] = history_dict["_timestamp"] - self._run_start_time
+ item = history.item.add()
+ item.key = "_runtime"
+ item.value_json = json.dumps(history_dict[item.key])
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/incremental_table_util.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/incremental_table_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1d53f7eac0cdc19328f05937427bbd173e0bdfd
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/incremental_table_util.py
@@ -0,0 +1,53 @@
+from __future__ import annotations
+
+import time
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from wandb import Table
+ from wandb.sdk.artifacts.artifact import Artifact
+
+ from ..wandb_run import Run as LocalRun
+
+ART_TYPE = "wandb-run-incremental-table"
+
+
+def _get_artifact_name(run: LocalRun, key: str) -> str:
+ from wandb.sdk.artifacts._internal_artifact import sanitize_artifact_name
+
+ return sanitize_artifact_name(f"run-{run.id}-incr-{key}")
+
+
+def init_artifact(run: LocalRun, sanitized_key: str) -> Artifact:
+ """Initialize a new artifact for an incremental table.
+
+ Args:
+ run: The wandb run associated with this artifact
+ sanitized_key: Sanitized string key to identify the table
+
+ Returns:
+ A wandb Artifact configured for incremental table storage
+ """
+ from wandb.sdk.artifacts._internal_artifact import InternalArtifact
+
+ artifact = InternalArtifact(
+ _get_artifact_name(run, sanitized_key),
+ ART_TYPE,
+ incremental=True,
+ )
+ return artifact
+
+
+def get_entry_name(incr_table: Table, key: str) -> str:
+ """Generate a unique entry name for a table increment.
+
+ Args:
+ run: The wandb run associated with this table
+ incr_table: The incremental table being updated
+ key: String key for the table entry
+
+ Returns:
+ A unique string name for the table entry
+ """
+ epoch = time.time_ns() // 1_000_000
+ return f"{incr_table._increment_num}-{epoch}.{key}"
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/internal_api.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/internal_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e93853938baf66e3a8b82ccfc0380d88c54d7fe
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/internal_api.py
@@ -0,0 +1,4723 @@
+import base64
+import datetime
+import functools
+import http.client
+import json
+import logging
+import os
+import re
+import socket
+import sys
+import threading
+from copy import deepcopy
+from pathlib import Path
+from typing import (
+ IO,
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Dict,
+ Iterable,
+ List,
+ Literal,
+ Mapping,
+ MutableMapping,
+ NamedTuple,
+ Optional,
+ Sequence,
+ TextIO,
+ Tuple,
+ Union,
+)
+
+import click
+import requests
+import yaml
+from wandb_gql import Client, gql
+from wandb_gql.client import RetryError
+from wandb_graphql.language.ast import Document
+
+import wandb
+from wandb import env, util
+from wandb.apis.normalize import normalize_exceptions, parse_backend_error_messages
+from wandb.errors import AuthenticationError, CommError, UnsupportedError, UsageError
+from wandb.integration.sagemaker import parse_sm_secrets
+from wandb.old.settings import Settings
+from wandb.proto.wandb_internal_pb2 import ServerFeature
+from wandb.sdk.artifacts._validators import is_artifact_registry_project
+from wandb.sdk.internal._generated import SERVER_FEATURES_QUERY_GQL, ServerFeaturesQuery
+from wandb.sdk.internal.thread_local_settings import _thread_local_api_settings
+from wandb.sdk.lib.gql_request import GraphQLSession
+from wandb.sdk.lib.hashutil import B64MD5, md5_file_b64
+
+from ..lib import credentials, retry
+from ..lib.filenames import DIFF_FNAME, METADATA_FNAME
+from ..lib.gitlib import GitRepo
+from . import context
+from .progress import Progress
+
+logger = logging.getLogger(__name__)
+
+LAUNCH_DEFAULT_PROJECT = "model-registry"
+
+if TYPE_CHECKING:
+ from typing import Literal, TypedDict
+
+ from .progress import ProgressFn
+
+ class CreateArtifactFileSpecInput(TypedDict, total=False):
+ """Corresponds to `type CreateArtifactFileSpecInput` in schema.graphql."""
+
+ artifactID: str
+ name: str
+ md5: str
+ mimetype: Optional[str]
+ artifactManifestID: Optional[str]
+ uploadPartsInput: Optional[List[Dict[str, object]]]
+
+ class CreateArtifactFilesResponseFile(TypedDict):
+ id: str
+ name: str
+ displayName: str
+ uploadUrl: Optional[str]
+ uploadHeaders: Sequence[str]
+ uploadMultipartUrls: "UploadPartsResponse"
+ storagePath: str
+ artifact: "CreateArtifactFilesResponseFileNode"
+
+ class CreateArtifactFilesResponseFileNode(TypedDict):
+ id: str
+
+ class UploadPartsResponse(TypedDict):
+ uploadUrlParts: List["UploadUrlParts"]
+ uploadID: str
+
+ class UploadUrlParts(TypedDict):
+ partNumber: int
+ uploadUrl: str
+
+ class CompleteMultipartUploadArtifactInput(TypedDict):
+ """Corresponds to `type CompleteMultipartUploadArtifactInput` in schema.graphql."""
+
+ completeMultipartAction: str
+ completedParts: Dict[int, str]
+ artifactID: str
+ storagePath: str
+ uploadID: str
+ md5: str
+
+ class CompleteMultipartUploadArtifactResponse(TypedDict):
+ digest: str
+
+ class DefaultSettings(TypedDict):
+ section: str
+ git_remote: str
+ ignore_globs: Optional[List[str]]
+ base_url: Optional[str]
+ root_dir: Optional[str]
+ api_key: Optional[str]
+ entity: Optional[str]
+ organization: Optional[str]
+ project: Optional[str]
+ _extra_http_headers: Optional[Mapping[str, str]]
+ _proxies: Optional[Mapping[str, str]]
+
+ _Response = MutableMapping
+ SweepState = Literal["RUNNING", "PAUSED", "CANCELED", "FINISHED"]
+ Number = Union[int, float]
+
+# class _MappingSupportsCopy(Protocol):
+# def copy(self) -> "_MappingSupportsCopy": ...
+# def keys(self) -> Iterable: ...
+# def __getitem__(self, name: str) -> Any: ...
+
+httpclient_logger = logging.getLogger("http.client")
+if os.environ.get("WANDB_DEBUG"):
+ httpclient_logger.setLevel(logging.DEBUG)
+
+
+def check_httpclient_logger_handler() -> None:
+ # Only enable http.client logging if WANDB_DEBUG is set
+ if not os.environ.get("WANDB_DEBUG"):
+ return
+ if httpclient_logger.handlers:
+ return
+
+ # Enable HTTPConnection debug logging to the logging framework
+ level = logging.DEBUG
+
+ def httpclient_log(*args: Any) -> None:
+ httpclient_logger.log(level, " ".join(args))
+
+ # mask the print() built-in in the http.client module to use logging instead
+ http.client.print = httpclient_log # type: ignore[attr-defined]
+ # enable debugging
+ http.client.HTTPConnection.debuglevel = 1
+
+ root_logger = logging.getLogger("wandb")
+ if root_logger.handlers:
+ httpclient_logger.addHandler(root_logger.handlers[0])
+
+
+class _ThreadLocalData(threading.local):
+ context: Optional[context.Context]
+
+ def __init__(self) -> None:
+ self.context = None
+
+
+class _OrgNames(NamedTuple):
+ entity_name: str
+ display_name: str
+
+
+def _match_org_with_fetched_org_entities(
+ organization: str, orgs: Sequence[_OrgNames]
+) -> str:
+ """Match the organization provided in the path with the org entity or org name of the input entity.
+
+ Args:
+ organization: The organization name to match
+ orgs: List of tuples containing (org_entity_name, org_display_name)
+
+ Returns:
+ str: The matched org entity name
+
+ Raises:
+ ValueError: If no matching organization is found or if multiple orgs exist without a match
+ """
+ for org_names in orgs:
+ if organization in org_names:
+ return org_names.entity_name
+
+ if len(orgs) == 1:
+ raise ValueError(
+ f"Expecting the organization name or entity name to match {orgs[0].display_name!r} "
+ f"and cannot be linked/fetched with {organization!r}. "
+ "Please update the target path with the correct organization name."
+ )
+
+ raise ValueError(
+ "Personal entity belongs to multiple organizations "
+ f"and cannot be linked/fetched with {organization!r}. "
+ "Please update the target path with the correct organization name "
+ "or use a team entity in the entity settings."
+ )
+
+
+class Api:
+ """W&B Internal Api wrapper.
+
+ Note:
+ Settings are automatically overridden by looking for
+ a `wandb/settings` file in the current working directory or its parent
+ directory. If none can be found, we look in the current user's home
+ directory.
+
+ Args:
+ default_settings(dict, optional): If you aren't using a settings
+ file, or you wish to override the section to use in the settings file
+ Override the settings here.
+ """
+
+ HTTP_TIMEOUT = env.get_http_timeout(20)
+ FILE_PUSHER_TIMEOUT = env.get_file_pusher_timeout()
+ _global_context: context.Context
+ _local_data: _ThreadLocalData
+
+ def __init__(
+ self,
+ default_settings: Optional[
+ Union[
+ "wandb.sdk.wandb_settings.Settings",
+ "wandb.sdk.internal.settings_static.SettingsStatic",
+ Settings,
+ dict,
+ ]
+ ] = None,
+ load_settings: bool = True,
+ retry_timedelta: datetime.timedelta = datetime.timedelta( # okay because it's immutable
+ days=7
+ ),
+ environ: MutableMapping = os.environ,
+ retry_callback: Optional[Callable[[int, str], Any]] = None,
+ api_key: Optional[str] = None,
+ ) -> None:
+ self._environ = environ
+ self._global_context = context.Context()
+ self._local_data = _ThreadLocalData()
+ self.default_settings: DefaultSettings = {
+ "section": "default",
+ "git_remote": "origin",
+ "ignore_globs": [],
+ "base_url": "https://api.wandb.ai",
+ "root_dir": None,
+ "api_key": None,
+ "entity": None,
+ "organization": None,
+ "project": None,
+ "_extra_http_headers": None,
+ "_proxies": None,
+ }
+ self.retry_timedelta = retry_timedelta
+ # todo: Old Settings do not follow the SupportsKeysAndGetItem Protocol
+ default_settings = default_settings or {}
+ self.default_settings.update(default_settings) # type: ignore
+ self.retry_uploads = 10
+ self._settings = Settings(
+ load_settings=load_settings,
+ root_dir=self.default_settings.get("root_dir"),
+ )
+ self.git = GitRepo(remote=self.settings("git_remote"))
+ # Mutable settings set by the _file_stream_api
+ self.dynamic_settings = {
+ "system_sample_seconds": 2,
+ "system_samples": 15,
+ "heartbeat_seconds": 30,
+ }
+
+ # todo: remove these hacky hacks after settings refactor is complete
+ # keeping this code here to limit scope and so that it is easy to remove later
+ self._extra_http_headers = self.settings("_extra_http_headers") or json.loads(
+ self._environ.get("WANDB__EXTRA_HTTP_HEADERS", "{}")
+ )
+ self._extra_http_headers.update(_thread_local_api_settings.headers or {})
+
+ auth = None
+ api_key = api_key or self.default_settings.get("api_key")
+ if api_key:
+ auth = ("api", api_key)
+ elif self.access_token is not None:
+ self._extra_http_headers["Authorization"] = f"Bearer {self.access_token}"
+ elif _thread_local_api_settings.cookies is None:
+ auth = ("api", self.api_key or "")
+
+ proxies = self.settings("_proxies") or json.loads(
+ self._environ.get("WANDB__PROXIES", "{}")
+ )
+
+ self.client = Client(
+ transport=GraphQLSession(
+ headers={
+ "User-Agent": self.user_agent,
+ "X-WANDB-USERNAME": env.get_username(env=self._environ),
+ "X-WANDB-USER-EMAIL": env.get_user_email(env=self._environ),
+ **self._extra_http_headers,
+ },
+ use_json=True,
+ # this timeout won't apply when the DNS lookup fails. in that case, it will be 60s
+ # https://bugs.python.org/issue22889
+ timeout=self.HTTP_TIMEOUT,
+ auth=auth,
+ url=f"{self.settings('base_url')}/graphql",
+ cookies=_thread_local_api_settings.cookies,
+ proxies=proxies,
+ )
+ )
+
+ self.retry_callback = retry_callback
+ self._retry_gql = retry.Retry(
+ self.execute,
+ retry_timedelta=retry_timedelta,
+ check_retry_fn=util.no_retry_auth,
+ retryable_exceptions=(RetryError, requests.RequestException),
+ retry_callback=retry_callback,
+ )
+ self._current_run_id: Optional[str] = None
+ self._file_stream_api = None
+ self._upload_file_session = requests.Session()
+ if self.FILE_PUSHER_TIMEOUT:
+ self._upload_file_session.put = functools.partial( # type: ignore
+ self._upload_file_session.put,
+ timeout=self.FILE_PUSHER_TIMEOUT,
+ )
+ if proxies:
+ self._upload_file_session.proxies.update(proxies)
+ # This Retry class is initialized once for each Api instance, so this
+ # defaults to retrying 1 million times per process or 7 days
+ self.upload_file_retry = normalize_exceptions(
+ retry.retriable(retry_timedelta=retry_timedelta)(self.upload_file)
+ )
+ self.upload_multipart_file_chunk_retry = normalize_exceptions(
+ retry.retriable(retry_timedelta=retry_timedelta)(
+ self.upload_multipart_file_chunk
+ )
+ )
+ self._client_id_mapping: Dict[str, str] = {}
+ # Large file uploads to azure can optionally use their SDK
+ self._azure_blob_module = util.get_module("azure.storage.blob")
+
+ self.query_types: Optional[List[str]] = None
+ self.mutation_types: Optional[List[str]] = None
+ self.server_info_types: Optional[List[str]] = None
+ self.server_use_artifact_input_info: Optional[List[str]] = None
+ self.server_create_artifact_input_info: Optional[List[str]] = None
+ self.server_artifact_fields_info: Optional[List[str]] = None
+ self.server_organization_type_fields_info: Optional[List[str]] = None
+ self.server_supports_enabling_artifact_usage_tracking: Optional[bool] = None
+ self._max_cli_version: Optional[str] = None
+ self._server_settings_type: Optional[List[str]] = None
+ self.fail_run_queue_item_input_info: Optional[List[str]] = None
+ self.create_launch_agent_input_info: Optional[List[str]] = None
+ self.server_create_run_queue_supports_drc: Optional[bool] = None
+ self.server_create_run_queue_supports_priority: Optional[bool] = None
+ self.server_supports_template_variables: Optional[bool] = None
+ self.server_push_to_run_queue_supports_priority: Optional[bool] = None
+
+ self._server_features_cache: Optional[Dict[str, bool]] = None
+
+ def gql(self, *args: Any, **kwargs: Any) -> Any:
+ ret = self._retry_gql(
+ *args,
+ retry_cancel_event=self.context.cancel_event,
+ **kwargs,
+ )
+ return ret
+
+ def set_local_context(self, api_context: Optional[context.Context]) -> None:
+ self._local_data.context = api_context
+
+ def clear_local_context(self) -> None:
+ self._local_data.context = None
+
+ @property
+ def context(self) -> context.Context:
+ return self._local_data.context or self._global_context
+
+ def reauth(self) -> None:
+ """Ensure the current api key is set in the transport."""
+ self.client.transport.session.auth = ("api", self.api_key or "")
+
+ def relocate(self) -> None:
+ """Ensure the current api points to the right server."""
+ self.client.transport.url = "{}/graphql".format(self.settings("base_url"))
+
+ def execute(self, *args: Any, **kwargs: Any) -> "_Response":
+ """Wrapper around execute that logs in cases of failure."""
+ try:
+ return self.client.execute(*args, **kwargs) # type: ignore
+ except requests.exceptions.HTTPError as err:
+ response = err.response
+ assert response is not None
+ logger.exception("Error executing GraphQL.")
+ for error in parse_backend_error_messages(response):
+ wandb.termerror(f"Error while calling W&B API: {error} ({response})")
+ raise
+
+ def validate_api_key(self) -> bool:
+ """Returns whether the API key stored on initialization is valid."""
+ res = self.execute(gql("query { viewer { id } }"))
+ return res is not None and res["viewer"] is not None
+
+ def set_current_run_id(self, run_id: str) -> None:
+ self._current_run_id = run_id
+
+ @property
+ def current_run_id(self) -> Optional[str]:
+ return self._current_run_id
+
+ @property
+ def user_agent(self) -> str:
+ return f"W&B Internal Client {wandb.__version__}"
+
+ @property
+ def api_key(self) -> Optional[str]:
+ if _thread_local_api_settings.api_key:
+ return _thread_local_api_settings.api_key
+ auth = requests.utils.get_netrc_auth(self.api_url)
+ key = None
+ if auth:
+ key = auth[-1]
+
+ # Environment should take precedence
+ env_key: Optional[str] = self._environ.get(env.API_KEY)
+ sagemaker_key: Optional[str] = parse_sm_secrets().get(env.API_KEY)
+ default_key: Optional[str] = self.default_settings.get("api_key")
+ return env_key or key or sagemaker_key or default_key
+
+ @property
+ def access_token(self) -> Optional[str]:
+ """Retrieves an access token for authentication.
+
+ This function attempts to exchange an identity token for a temporary
+ access token from the server, and save it to the credentials file.
+ It uses the path to the identity token as defined in the environment
+ variables. If the environment variable is not set, it returns None.
+
+ Returns:
+ Optional[str]: The access token if available, otherwise None if
+ no identity token is supplied.
+ Raises:
+ AuthenticationError: If the path to the identity token is not found.
+ """
+ token_file_str = self._environ.get(env.IDENTITY_TOKEN_FILE)
+ if not token_file_str:
+ return None
+
+ token_file = Path(token_file_str)
+ if not token_file.exists():
+ raise AuthenticationError(f"Identity token file not found: {token_file}")
+
+ base_url = self.settings("base_url")
+ credentials_file = env.get_credentials_file(
+ str(credentials.DEFAULT_WANDB_CREDENTIALS_FILE), self._environ
+ )
+ return credentials.access_token(base_url, token_file, credentials_file)
+
+ @property
+ def api_url(self) -> str:
+ return self.settings("base_url") # type: ignore
+
+ @property
+ def app_url(self) -> str:
+ return wandb.util.app_url(self.api_url)
+
+ @property
+ def default_entity(self) -> str:
+ return self.viewer().get("entity") # type: ignore
+
+ def settings(self, key: Optional[str] = None, section: Optional[str] = None) -> Any:
+ """The settings overridden from the wandb/settings file.
+
+ Args:
+ key (str, optional): If provided only this setting is returned
+ section (str, optional): If provided this section of the setting file is
+ used, defaults to "default"
+
+ Returns:
+ A dict with the current settings
+
+ {
+ "entity": "models",
+ "base_url": "https://api.wandb.ai",
+ "project": None,
+ "organization": "my-org",
+ }
+ """
+ result = self.default_settings.copy()
+ result.update(self._settings.items(section=section)) # type: ignore
+ result.update(
+ {
+ "entity": env.get_entity(
+ self._settings.get(
+ Settings.DEFAULT_SECTION,
+ "entity",
+ fallback=result.get("entity"),
+ ),
+ env=self._environ,
+ ),
+ "organization": env.get_organization(
+ self._settings.get(
+ Settings.DEFAULT_SECTION,
+ "organization",
+ fallback=result.get("organization"),
+ ),
+ env=self._environ,
+ ),
+ "project": env.get_project(
+ self._settings.get(
+ Settings.DEFAULT_SECTION,
+ "project",
+ fallback=result.get("project"),
+ ),
+ env=self._environ,
+ ),
+ "base_url": env.get_base_url(
+ self._settings.get(
+ Settings.DEFAULT_SECTION,
+ "base_url",
+ fallback=result.get("base_url"),
+ ),
+ env=self._environ,
+ ),
+ "ignore_globs": env.get_ignore(
+ self._settings.get(
+ Settings.DEFAULT_SECTION,
+ "ignore_globs",
+ fallback=result.get("ignore_globs"),
+ ),
+ env=self._environ,
+ ),
+ }
+ )
+
+ return result if key is None else result[key] # type: ignore
+
+ def clear_setting(
+ self, key: str, globally: bool = False, persist: bool = False
+ ) -> None:
+ self._settings.clear(
+ Settings.DEFAULT_SECTION, key, globally=globally, persist=persist
+ )
+
+ def set_setting(
+ self, key: str, value: Any, globally: bool = False, persist: bool = False
+ ) -> None:
+ self._settings.set(
+ Settings.DEFAULT_SECTION, key, value, globally=globally, persist=persist
+ )
+ if key == "entity":
+ env.set_entity(value, env=self._environ)
+ elif key == "project":
+ env.set_project(value, env=self._environ)
+ elif key == "base_url":
+ self.relocate()
+
+ def parse_slug(
+ self, slug: str, project: Optional[str] = None, run: Optional[str] = None
+ ) -> Tuple[str, str]:
+ """Parse a slug into a project and run.
+
+ Args:
+ slug (str): The slug to parse
+ project (str, optional): The project to use, if not provided it will be
+ inferred from the slug
+ run (str, optional): The run to use, if not provided it will be inferred
+ from the slug
+
+ Returns:
+ A dict with the project and run
+ """
+ if slug and "/" in slug:
+ parts = slug.split("/")
+ project = parts[0]
+ run = parts[1]
+ else:
+ project = project or self.settings().get("project")
+ if project is None:
+ raise CommError("No default project configured.")
+ run = run or slug or self.current_run_id or env.get_run(env=self._environ)
+ assert run, "run must be specified"
+ return project, run
+
+ @normalize_exceptions
+ def server_info_introspection(self) -> Tuple[List[str], List[str], List[str]]:
+ query_string = """
+ query ProbeServerCapabilities {
+ QueryType: __type(name: "Query") {
+ ...fieldData
+ }
+ MutationType: __type(name: "Mutation") {
+ ...fieldData
+ }
+ ServerInfoType: __type(name: "ServerInfo") {
+ ...fieldData
+ }
+ }
+
+ fragment fieldData on __Type {
+ fields {
+ name
+ }
+ }
+ """
+ if (
+ self.query_types is None
+ or self.mutation_types is None
+ or self.server_info_types is None
+ ):
+ query = gql(query_string)
+ res = self.gql(query)
+
+ self.query_types = [
+ field.get("name", "")
+ for field in res.get("QueryType", {}).get("fields", [{}])
+ ]
+ self.mutation_types = [
+ field.get("name", "")
+ for field in res.get("MutationType", {}).get("fields", [{}])
+ ]
+ self.server_info_types = [
+ field.get("name", "")
+ for field in res.get("ServerInfoType", {}).get("fields", [{}])
+ ]
+ return self.query_types, self.server_info_types, self.mutation_types
+
+ @normalize_exceptions
+ def server_settings_introspection(self) -> None:
+ query_string = """
+ query ProbeServerSettings {
+ ServerSettingsType: __type(name: "ServerSettings") {
+ ...fieldData
+ }
+ }
+
+ fragment fieldData on __Type {
+ fields {
+ name
+ }
+ }
+ """
+ if self._server_settings_type is None:
+ query = gql(query_string)
+ res = self.gql(query)
+ self._server_settings_type = (
+ [
+ field.get("name", "")
+ for field in res.get("ServerSettingsType", {}).get("fields", [{}])
+ ]
+ if res
+ else []
+ )
+
+ def server_use_artifact_input_introspection(self) -> List:
+ query_string = """
+ query ProbeServerUseArtifactInput {
+ UseArtifactInputInfoType: __type(name: "UseArtifactInput") {
+ name
+ inputFields {
+ name
+ }
+ }
+ }
+ """
+
+ if self.server_use_artifact_input_info is None:
+ query = gql(query_string)
+ res = self.gql(query)
+ self.server_use_artifact_input_info = [
+ field.get("name", "")
+ for field in res.get("UseArtifactInputInfoType", {}).get(
+ "inputFields", [{}]
+ )
+ ]
+ return self.server_use_artifact_input_info
+
+ @normalize_exceptions
+ def launch_agent_introspection(self) -> Optional[str]:
+ query = gql(
+ """
+ query LaunchAgentIntrospection {
+ LaunchAgentType: __type(name: "LaunchAgent") {
+ name
+ }
+ }
+ """
+ )
+
+ res = self.gql(query)
+ return res.get("LaunchAgentType") or None
+
+ @normalize_exceptions
+ def create_run_queue_introspection(self) -> Tuple[bool, bool, bool]:
+ _, _, mutations = self.server_info_introspection()
+ query_string = """
+ query ProbeCreateRunQueueInput {
+ CreateRunQueueInputType: __type(name: "CreateRunQueueInput") {
+ name
+ inputFields {
+ name
+ }
+ }
+ }
+ """
+ if (
+ self.server_create_run_queue_supports_drc is None
+ or self.server_create_run_queue_supports_priority is None
+ ):
+ query = gql(query_string)
+ res = self.gql(query)
+ if res is None:
+ raise CommError("Could not get CreateRunQueue input from GQL.")
+ self.server_create_run_queue_supports_drc = "defaultResourceConfigID" in [
+ x["name"]
+ for x in (
+ res.get("CreateRunQueueInputType", {}).get("inputFields", [{}])
+ )
+ ]
+ self.server_create_run_queue_supports_priority = "prioritizationMode" in [
+ x["name"]
+ for x in (
+ res.get("CreateRunQueueInputType", {}).get("inputFields", [{}])
+ )
+ ]
+ return (
+ "createRunQueue" in mutations,
+ self.server_create_run_queue_supports_drc,
+ self.server_create_run_queue_supports_priority,
+ )
+
+ @normalize_exceptions
+ def upsert_run_queue_introspection(self) -> bool:
+ _, _, mutations = self.server_info_introspection()
+ return "upsertRunQueue" in mutations
+
+ @normalize_exceptions
+ def push_to_run_queue_introspection(self) -> Tuple[bool, bool]:
+ query_string = """
+ query ProbePushToRunQueueInput {
+ PushToRunQueueInputType: __type(name: "PushToRunQueueInput") {
+ name
+ inputFields {
+ name
+ }
+ }
+ }
+ """
+
+ if (
+ self.server_supports_template_variables is None
+ or self.server_push_to_run_queue_supports_priority is None
+ ):
+ query = gql(query_string)
+ res = self.gql(query)
+ self.server_supports_template_variables = "templateVariableValues" in [
+ x["name"]
+ for x in (
+ res.get("PushToRunQueueInputType", {}).get("inputFields", [{}])
+ )
+ ]
+ self.server_push_to_run_queue_supports_priority = "priority" in [
+ x["name"]
+ for x in (
+ res.get("PushToRunQueueInputType", {}).get("inputFields", [{}])
+ )
+ ]
+
+ return (
+ self.server_supports_template_variables,
+ self.server_push_to_run_queue_supports_priority,
+ )
+
+ @normalize_exceptions
+ def create_default_resource_config_introspection(self) -> bool:
+ _, _, mutations = self.server_info_introspection()
+ return "createDefaultResourceConfig" in mutations
+
+ @normalize_exceptions
+ def fail_run_queue_item_introspection(self) -> bool:
+ _, _, mutations = self.server_info_introspection()
+ return "failRunQueueItem" in mutations
+
+ @normalize_exceptions
+ def fail_run_queue_item_fields_introspection(self) -> List:
+ if self.fail_run_queue_item_input_info:
+ return self.fail_run_queue_item_input_info
+ query_string = """
+ query ProbeServerFailRunQueueItemInput {
+ FailRunQueueItemInputInfoType: __type(name:"FailRunQueueItemInput") {
+ inputFields{
+ name
+ }
+ }
+ }
+ """
+
+ query = gql(query_string)
+ res = self.gql(query)
+
+ self.fail_run_queue_item_input_info = [
+ field.get("name", "")
+ for field in res.get("FailRunQueueItemInputInfoType", {}).get(
+ "inputFields", [{}]
+ )
+ ]
+ return self.fail_run_queue_item_input_info
+
+ @normalize_exceptions
+ def fail_run_queue_item(
+ self,
+ run_queue_item_id: str,
+ message: str,
+ stage: str,
+ file_paths: Optional[List[str]] = None,
+ ) -> bool:
+ if not self.fail_run_queue_item_introspection():
+ return False
+ variable_values: Dict[str, Union[str, Optional[List[str]]]] = {
+ "runQueueItemId": run_queue_item_id,
+ }
+ if "message" in self.fail_run_queue_item_fields_introspection():
+ variable_values.update({"message": message, "stage": stage})
+ if file_paths is not None:
+ variable_values["filePaths"] = file_paths
+ mutation_string = """
+ mutation failRunQueueItem($runQueueItemId: ID!, $message: String!, $stage: String!, $filePaths: [String!]) {
+ failRunQueueItem(
+ input: {
+ runQueueItemId: $runQueueItemId
+ message: $message
+ stage: $stage
+ filePaths: $filePaths
+ }
+ ) {
+ success
+ }
+ }
+ """
+ else:
+ mutation_string = """
+ mutation failRunQueueItem($runQueueItemId: ID!) {
+ failRunQueueItem(
+ input: {
+ runQueueItemId: $runQueueItemId
+ }
+ ) {
+ success
+ }
+ }
+ """
+
+ mutation = gql(mutation_string)
+ response = self.gql(mutation, variable_values=variable_values)
+ result: bool = response["failRunQueueItem"]["success"]
+ return result
+
+ @normalize_exceptions
+ def update_run_queue_item_warning_introspection(self) -> bool:
+ _, _, mutations = self.server_info_introspection()
+ return "updateRunQueueItemWarning" in mutations
+
+ def _server_features(self) -> Dict[str, bool]:
+ # NOTE: Avoid caching via `@cached_property`, due to undocumented
+ # locking behavior before Python 3.12.
+ # See: https://github.com/python/cpython/issues/87634
+ query = gql(SERVER_FEATURES_QUERY_GQL)
+ try:
+ response = self.gql(query)
+ except Exception as e:
+ # Unfortunately we currently have to match on the text of the error message,
+ # as the `gql` client raises `Exception` rather than a more specific error.
+ if 'Cannot query field "features" on type "ServerInfo".' in str(e):
+ self._server_features_cache = {}
+ else:
+ raise
+ else:
+ info = ServerFeaturesQuery.model_validate(response).server_info
+ if info and (feats := info.features):
+ self._server_features_cache = {f.name: f.is_enabled for f in feats if f}
+ else:
+ self._server_features_cache = {}
+ return self._server_features_cache
+
+ def _server_supports(self, feature: Union[int, str]) -> bool:
+ """Return whether the current server supports the given feature.
+
+ This also caches the underlying lookup of server feature flags,
+ and it maps {feature_name (str) -> is_enabled (bool)}.
+
+ Good to use for features that have a fallback mechanism for older servers.
+ """
+ # If we're given the protobuf enum value, convert to a string name.
+ # NOTE: We deliberately use names (str) instead of enum values (int)
+ # as the keys here, since:
+ # - the server identifies features by their name, rather than (client-side) enum value
+ # - the defined list of client-side flags may be behind the server-side list of flags
+ key = ServerFeature.Name(feature) if isinstance(feature, int) else feature
+ return self._server_features().get(key) or False
+
+ @normalize_exceptions
+ def update_run_queue_item_warning(
+ self,
+ run_queue_item_id: str,
+ message: str,
+ stage: str,
+ file_paths: Optional[List[str]] = None,
+ ) -> bool:
+ if not self.update_run_queue_item_warning_introspection():
+ return False
+ mutation = gql(
+ """
+ mutation updateRunQueueItemWarning($runQueueItemId: ID!, $message: String!, $stage: String!, $filePaths: [String!]) {
+ updateRunQueueItemWarning(
+ input: {
+ runQueueItemId: $runQueueItemId
+ message: $message
+ stage: $stage
+ filePaths: $filePaths
+ }
+ ) {
+ success
+ }
+ }
+ """
+ )
+ response = self.gql(
+ mutation,
+ variable_values={
+ "runQueueItemId": run_queue_item_id,
+ "message": message,
+ "stage": stage,
+ "filePaths": file_paths,
+ },
+ )
+ result: bool = response["updateRunQueueItemWarning"]["success"]
+ return result
+
+ @normalize_exceptions
+ def viewer(self) -> Dict[str, Any]:
+ query = gql(
+ """
+ query Viewer{
+ viewer {
+ id
+ entity
+ username
+ flags
+ teams {
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ }
+ }
+ """
+ )
+ res = self.gql(query)
+ return res.get("viewer") or {}
+
+ @normalize_exceptions
+ def max_cli_version(self) -> Optional[str]:
+ if self._max_cli_version is not None:
+ return self._max_cli_version
+
+ query_types, server_info_types, _ = self.server_info_introspection()
+ cli_version_exists = (
+ "serverInfo" in query_types and "cliVersionInfo" in server_info_types
+ )
+ if not cli_version_exists:
+ return None
+
+ _, server_info = self.viewer_server_info()
+ self._max_cli_version = server_info.get("cliVersionInfo", {}).get(
+ "max_cli_version"
+ )
+ return self._max_cli_version
+
+ @normalize_exceptions
+ def viewer_server_info(self) -> Tuple[Dict[str, Any], Dict[str, Any]]:
+ local_query = """
+ latestLocalVersionInfo {
+ outOfDate
+ latestVersionString
+ versionOnThisInstanceString
+ }
+ """
+ cli_query = """
+ serverInfo {
+ cliVersionInfo
+ _LOCAL_QUERY_
+ }
+ """
+ query_template = """
+ query Viewer{
+ viewer {
+ id
+ entity
+ username
+ email
+ flags
+ teams {
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ }
+ _CLI_QUERY_
+ }
+ """
+ query_types, server_info_types, _ = self.server_info_introspection()
+
+ cli_version_exists = (
+ "serverInfo" in query_types and "cliVersionInfo" in server_info_types
+ )
+
+ local_version_exists = (
+ "serverInfo" in query_types
+ and "latestLocalVersionInfo" in server_info_types
+ )
+
+ cli_query_string = "" if not cli_version_exists else cli_query
+ local_query_string = "" if not local_version_exists else local_query
+
+ query_string = query_template.replace("_CLI_QUERY_", cli_query_string).replace(
+ "_LOCAL_QUERY_", local_query_string
+ )
+ query = gql(query_string)
+ res = self.gql(query)
+ return res.get("viewer") or {}, res.get("serverInfo") or {}
+
+ @normalize_exceptions
+ def list_projects(self, entity: Optional[str] = None) -> List[Dict[str, str]]:
+ """List projects in W&B scoped by entity.
+
+ Args:
+ entity (str, optional): The entity to scope this project to.
+
+ Returns:
+ [{"id","name","description"}]
+ """
+ query = gql(
+ """
+ query EntityProjects($entity: String) {
+ models(first: 10, entityName: $entity) {
+ edges {
+ node {
+ id
+ name
+ description
+ }
+ }
+ }
+ }
+ """
+ )
+ project_list: List[Dict[str, str]] = self._flatten_edges(
+ self.gql(
+ query, variable_values={"entity": entity or self.settings("entity")}
+ )["models"]
+ )
+ return project_list
+
+ @normalize_exceptions
+ def project(self, project: str, entity: Optional[str] = None) -> "_Response":
+ """Retrieve project.
+
+ Args:
+ project (str): The project to get details for
+ entity (str, optional): The entity to scope this project to.
+
+ Returns:
+ [{"id","name","repo","dockerImage","description"}]
+ """
+ query = gql(
+ """
+ query ProjectDetails($entity: String, $project: String) {
+ model(name: $project, entityName: $entity) {
+ id
+ name
+ repo
+ dockerImage
+ description
+ }
+ }
+ """
+ )
+ response: _Response = self.gql(
+ query, variable_values={"entity": entity, "project": project}
+ )["model"]
+ return response
+
+ @normalize_exceptions
+ def sweep(
+ self,
+ sweep: str,
+ specs: str,
+ project: Optional[str] = None,
+ entity: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """Retrieve sweep.
+
+ Args:
+ sweep (str): The sweep to get details for
+ specs (str): history specs
+ project (str, optional): The project to scope this sweep to.
+ entity (str, optional): The entity to scope this sweep to.
+
+ Returns:
+ [{"id","name","repo","dockerImage","description"}]
+ """
+ query = gql(
+ """
+ query SweepWithRuns($entity: String, $project: String, $sweep: String!, $specs: [JSONString!]!) {
+ project(name: $project, entityName: $entity) {
+ sweep(sweepName: $sweep) {
+ id
+ name
+ method
+ state
+ description
+ config
+ createdAt
+ heartbeatAt
+ updatedAt
+ earlyStopJobRunning
+ bestLoss
+ controller
+ scheduler
+ runs {
+ edges {
+ node {
+ name
+ state
+ config
+ exitcode
+ heartbeatAt
+ shouldStop
+ failed
+ stopped
+ running
+ summaryMetrics
+ sampledHistory(specs: $specs)
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+ )
+ entity = entity or self.settings("entity")
+ project = project or self.settings("project")
+ response = self.gql(
+ query,
+ variable_values={
+ "entity": entity,
+ "project": project,
+ "sweep": sweep,
+ "specs": specs,
+ },
+ )
+ if response["project"] is None or response["project"]["sweep"] is None:
+ raise ValueError(f"Sweep {entity}/{project}/{sweep} not found")
+ data: Dict[str, Any] = response["project"]["sweep"]
+ if data:
+ data["runs"] = self._flatten_edges(data["runs"])
+ return data
+
+ @normalize_exceptions
+ def list_runs(
+ self, project: str, entity: Optional[str] = None
+ ) -> List[Dict[str, str]]:
+ """List runs in W&B scoped by project.
+
+ Args:
+ project (str): The project to scope the runs to
+ entity (str, optional): The entity to scope this project to. Defaults to public models
+
+ Returns:
+ [{"id","name","description"}]
+ """
+ query = gql(
+ """
+ query ProjectRuns($model: String!, $entity: String) {
+ model(name: $model, entityName: $entity) {
+ buckets(first: 10) {
+ edges {
+ node {
+ id
+ name
+ displayName
+ description
+ }
+ }
+ }
+ }
+ }
+ """
+ )
+ return self._flatten_edges(
+ self.gql(
+ query,
+ variable_values={
+ "entity": entity or self.settings("entity"),
+ "model": project or self.settings("project"),
+ },
+ )["model"]["buckets"]
+ )
+
+ @normalize_exceptions
+ def run_config(
+ self, project: str, run: Optional[str] = None, entity: Optional[str] = None
+ ) -> Tuple[str, Dict[str, Any], Optional[str], Dict[str, Any]]:
+ """Get the relevant configs for a run.
+
+ Args:
+ project (str): The project to download, (can include bucket)
+ run (str, optional): The run to download
+ entity (str, optional): The entity to scope this project to.
+ """
+ check_httpclient_logger_handler()
+
+ query = gql(
+ """
+ query RunConfigs(
+ $name: String!,
+ $entity: String,
+ $run: String!,
+ $pattern: String!,
+ $includeConfig: Boolean!,
+ ) {
+ model(name: $name, entityName: $entity) {
+ bucket(name: $run) {
+ config @include(if: $includeConfig)
+ commit @include(if: $includeConfig)
+ files(pattern: $pattern) {
+ pageInfo {
+ hasNextPage
+ endCursor
+ }
+ edges {
+ node {
+ name
+ directUrl
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+ )
+
+ variable_values = {
+ "name": project,
+ "run": run,
+ "entity": entity,
+ "includeConfig": True,
+ }
+
+ commit: str = ""
+ config: Dict[str, Any] = {}
+ patch: Optional[str] = None
+ metadata: Dict[str, Any] = {}
+
+ # If we use the `names` parameter on the `files` node, then the server
+ # will helpfully give us and 'open' file handle to the files that don't
+ # exist. This is so that we can upload data to it. However, in this
+ # case, we just want to download that file and not upload to it, so
+ # let's instead query for the files that do exist using `pattern`
+ # (with no wildcards).
+ #
+ # Unfortunately we're unable to construct a single pattern that matches
+ # our 2 files, we would need something like regex for that.
+ for filename in [DIFF_FNAME, METADATA_FNAME]:
+ variable_values["pattern"] = filename
+ response = self.gql(query, variable_values=variable_values)
+ if response["model"] is None:
+ raise CommError(f"Run {entity}/{project}/{run} not found")
+ run_obj: Dict = response["model"]["bucket"]
+ # we only need to fetch this config once
+ if variable_values["includeConfig"]:
+ commit = run_obj["commit"]
+ config = json.loads(run_obj["config"] or "{}")
+ variable_values["includeConfig"] = False
+ if run_obj["files"] is not None:
+ for file_edge in run_obj["files"]["edges"]:
+ name = file_edge["node"]["name"]
+ url = file_edge["node"]["directUrl"]
+ res = requests.get(url)
+ res.raise_for_status()
+ if name == METADATA_FNAME:
+ metadata = res.json()
+ elif name == DIFF_FNAME:
+ patch = res.text
+
+ return commit, config, patch, metadata
+
+ @normalize_exceptions
+ def run_resume_status(
+ self, entity: str, project_name: str, name: str
+ ) -> Optional[Dict[str, Any]]:
+ """Check if a run exists and get resume information.
+
+ Args:
+ entity (str): The entity to scope this project to.
+ project_name (str): The project to download, (can include bucket)
+ name (str): The run to download
+ """
+ # Pulling wandbConfig.start_time is required so that we can determine if a run has actually started
+ query = gql(
+ """
+ query RunResumeStatus($project: String, $entity: String, $name: String!) {
+ model(name: $project, entityName: $entity) {
+ id
+ name
+ entity {
+ id
+ name
+ }
+
+ bucket(name: $name, missingOk: true) {
+ id
+ name
+ summaryMetrics
+ displayName
+ logLineCount
+ historyLineCount
+ eventsLineCount
+ historyTail
+ eventsTail
+ config
+ tags
+ wandbConfig(keys: ["t"])
+ }
+ }
+ }
+ """
+ )
+
+ response = self.gql(
+ query,
+ variable_values={
+ "entity": entity,
+ "project": project_name,
+ "name": name,
+ },
+ )
+
+ if "model" not in response or "bucket" not in (response["model"] or {}):
+ return None
+
+ project = response["model"]
+ self.set_setting("project", project_name)
+ if "entity" in project:
+ self.set_setting("entity", project["entity"]["name"])
+
+ result: Dict[str, Any] = project["bucket"]
+
+ return result
+
+ @normalize_exceptions
+ def check_stop_requested(
+ self, project_name: str, entity_name: str, run_id: str
+ ) -> bool:
+ query = gql(
+ """
+ query RunStoppedStatus($projectName: String, $entityName: String, $runId: String!) {
+ project(name:$projectName, entityName:$entityName) {
+ run(name:$runId) {
+ stopped
+ }
+ }
+ }
+ """
+ )
+
+ response = self.gql(
+ query,
+ variable_values={
+ "projectName": project_name,
+ "entityName": entity_name,
+ "runId": run_id,
+ },
+ )
+
+ project = response.get("project", None)
+ if not project:
+ return False
+ run = project.get("run", None)
+ if not run:
+ return False
+
+ status: bool = run["stopped"]
+ return status
+
+ def format_project(self, project: str) -> str:
+ return re.sub(r"\W+", "-", project.lower()).strip("-_")
+
+ @normalize_exceptions
+ def upsert_project(
+ self,
+ project: str,
+ id: Optional[str] = None,
+ description: Optional[str] = None,
+ entity: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """Create a new project.
+
+ Args:
+ project (str): The project to create
+ description (str, optional): A description of this project
+ entity (str, optional): The entity to scope this project to.
+ """
+ mutation = gql(
+ """
+ mutation UpsertModel($name: String!, $id: String, $entity: String!, $description: String, $repo: String) {
+ upsertModel(input: { id: $id, name: $name, entityName: $entity, description: $description, repo: $repo }) {
+ model {
+ name
+ description
+ }
+ }
+ }
+ """
+ )
+ response = self.gql(
+ mutation,
+ variable_values={
+ "name": self.format_project(project),
+ "entity": entity or self.settings("entity"),
+ "description": description,
+ "id": id,
+ },
+ )
+ # TODO(jhr): Commenting out 'repo' field for cling, add back
+ # 'description': description, 'repo': self.git.remote_url, 'id': id})
+ result: Dict[str, Any] = response["upsertModel"]["model"]
+ return result
+
+ @normalize_exceptions
+ def entity_is_team(self, entity: str) -> bool:
+ query = gql(
+ """
+ query EntityIsTeam($entity: String!) {
+ entity(name: $entity) {
+ id
+ isTeam
+ }
+ }
+ """
+ )
+ variable_values = {
+ "entity": entity,
+ }
+
+ res = self.gql(query, variable_values)
+ if res.get("entity") is None:
+ raise Exception(
+ f"Error fetching entity {entity} "
+ "check that you have access to this entity"
+ )
+
+ is_team: bool = res["entity"]["isTeam"]
+ return is_team
+
+ @normalize_exceptions
+ def get_project_run_queues(self, entity: str, project: str) -> List[Dict[str, str]]:
+ query = gql(
+ """
+ query ProjectRunQueues($entity: String!, $projectName: String!){
+ project(entityName: $entity, name: $projectName) {
+ runQueues {
+ id
+ name
+ createdBy
+ access
+ }
+ }
+ }
+ """
+ )
+ variable_values = {
+ "projectName": project,
+ "entity": entity,
+ }
+
+ res = self.gql(query, variable_values)
+ if res.get("project") is None:
+ # circular dependency: (LAUNCH_DEFAULT_PROJECT = model-registry)
+ if project == "model-registry":
+ msg = (
+ f"Error fetching run queues for {entity} "
+ "check that you have access to this entity and project"
+ )
+ else:
+ msg = (
+ f"Error fetching run queues for {entity}/{project} "
+ "check that you have access to this entity and project"
+ )
+
+ raise Exception(msg)
+
+ project_run_queues: List[Dict[str, str]] = res["project"]["runQueues"]
+ return project_run_queues
+
+ @normalize_exceptions
+ def create_default_resource_config(
+ self,
+ entity: str,
+ resource: str,
+ config: str,
+ template_variables: Optional[Dict[str, Union[float, int, str]]],
+ ) -> Optional[Dict[str, Any]]:
+ if not self.create_default_resource_config_introspection():
+ raise Exception()
+ supports_template_vars, _ = self.push_to_run_queue_introspection()
+
+ mutation_params = """
+ $entityName: String!,
+ $resource: String!,
+ $config: JSONString!
+ """
+ mutation_inputs = """
+ entityName: $entityName,
+ resource: $resource,
+ config: $config
+ """
+
+ if supports_template_vars:
+ mutation_params += ", $templateVariables: JSONString"
+ mutation_inputs += ", templateVariables: $templateVariables"
+ else:
+ if template_variables is not None:
+ raise UnsupportedError(
+ "server does not support template variables, please update server instance to >=0.46"
+ )
+
+ variable_values = {
+ "entityName": entity,
+ "resource": resource,
+ "config": config,
+ }
+ if supports_template_vars:
+ if template_variables is not None:
+ variable_values["templateVariables"] = json.dumps(template_variables)
+ else:
+ variable_values["templateVariables"] = "{}"
+
+ query = gql(
+ f"""
+ mutation createDefaultResourceConfig(
+ {mutation_params}
+ ) {{
+ createDefaultResourceConfig(
+ input: {{
+ {mutation_inputs}
+ }}
+ ) {{
+ defaultResourceConfigID
+ success
+ }}
+ }}
+ """
+ )
+
+ result: Optional[Dict[str, Any]] = self.gql(query, variable_values)[
+ "createDefaultResourceConfig"
+ ]
+ return result
+
+ @normalize_exceptions
+ def create_run_queue(
+ self,
+ entity: str,
+ project: str,
+ queue_name: str,
+ access: str,
+ prioritization_mode: Optional[str] = None,
+ config_id: Optional[str] = None,
+ ) -> Optional[Dict[str, Any]]:
+ (
+ create_run_queue,
+ supports_drc,
+ supports_prioritization,
+ ) = self.create_run_queue_introspection()
+ if not create_run_queue:
+ raise UnsupportedError(
+ "run queue creation is not supported by this version of "
+ "wandb server. Consider updating to the latest version."
+ )
+ if not supports_drc and config_id is not None:
+ raise UnsupportedError(
+ "default resource configurations are not supported by this version "
+ "of wandb server. Consider updating to the latest version."
+ )
+ if not supports_prioritization and prioritization_mode is not None:
+ raise UnsupportedError(
+ "launch prioritization is not supported by this version of "
+ "wandb server. Consider updating to the latest version."
+ )
+
+ if supports_prioritization:
+ query = gql(
+ """
+ mutation createRunQueue(
+ $entity: String!,
+ $project: String!,
+ $queueName: String!,
+ $access: RunQueueAccessType!,
+ $prioritizationMode: RunQueuePrioritizationMode,
+ $defaultResourceConfigID: ID,
+ ) {
+ createRunQueue(
+ input: {
+ entityName: $entity,
+ projectName: $project,
+ queueName: $queueName,
+ access: $access,
+ prioritizationMode: $prioritizationMode
+ defaultResourceConfigID: $defaultResourceConfigID
+ }
+ ) {
+ success
+ queueID
+ }
+ }
+ """
+ )
+ variable_values = {
+ "entity": entity,
+ "project": project,
+ "queueName": queue_name,
+ "access": access,
+ "prioritizationMode": prioritization_mode,
+ "defaultResourceConfigID": config_id,
+ }
+ else:
+ query = gql(
+ """
+ mutation createRunQueue(
+ $entity: String!,
+ $project: String!,
+ $queueName: String!,
+ $access: RunQueueAccessType!,
+ $defaultResourceConfigID: ID,
+ ) {
+ createRunQueue(
+ input: {
+ entityName: $entity,
+ projectName: $project,
+ queueName: $queueName,
+ access: $access,
+ defaultResourceConfigID: $defaultResourceConfigID
+ }
+ ) {
+ success
+ queueID
+ }
+ }
+ """
+ )
+ variable_values = {
+ "entity": entity,
+ "project": project,
+ "queueName": queue_name,
+ "access": access,
+ "defaultResourceConfigID": config_id,
+ }
+
+ result: Optional[Dict[str, Any]] = self.gql(query, variable_values)[
+ "createRunQueue"
+ ]
+ return result
+
+ @normalize_exceptions
+ def upsert_run_queue(
+ self,
+ queue_name: str,
+ entity: str,
+ resource_type: str,
+ resource_config: dict,
+ project: str = LAUNCH_DEFAULT_PROJECT,
+ prioritization_mode: Optional[str] = None,
+ template_variables: Optional[dict] = None,
+ external_links: Optional[dict] = None,
+ ) -> Optional[Dict[str, Any]]:
+ if not self.upsert_run_queue_introspection():
+ raise UnsupportedError(
+ "upserting run queues is not supported by this version of "
+ "wandb server. Consider updating to the latest version."
+ )
+ query = gql(
+ """
+ mutation upsertRunQueue(
+ $entityName: String!
+ $projectName: String!
+ $queueName: String!
+ $resourceType: String!
+ $resourceConfig: JSONString!
+ $templateVariables: JSONString
+ $prioritizationMode: RunQueuePrioritizationMode
+ $externalLinks: JSONString
+ $clientMutationId: String
+ ) {
+ upsertRunQueue(
+ input: {
+ entityName: $entityName
+ projectName: $projectName
+ queueName: $queueName
+ resourceType: $resourceType
+ resourceConfig: $resourceConfig
+ templateVariables: $templateVariables
+ prioritizationMode: $prioritizationMode
+ externalLinks: $externalLinks
+ clientMutationId: $clientMutationId
+ }
+ ) {
+ success
+ configSchemaValidationErrors
+ }
+ }
+ """
+ )
+ variable_values = {
+ "entityName": entity,
+ "projectName": project,
+ "queueName": queue_name,
+ "resourceType": resource_type,
+ "resourceConfig": json.dumps(resource_config),
+ "templateVariables": (
+ json.dumps(template_variables) if template_variables else None
+ ),
+ "prioritizationMode": prioritization_mode,
+ "externalLinks": json.dumps(external_links) if external_links else None,
+ }
+ result: Dict[str, Any] = self.gql(query, variable_values)
+ return result["upsertRunQueue"]
+
+ @normalize_exceptions
+ def push_to_run_queue_by_name(
+ self,
+ entity: str,
+ project: str,
+ queue_name: str,
+ run_spec: str,
+ template_variables: Optional[Dict[str, Union[int, float, str]]],
+ priority: Optional[int] = None,
+ ) -> Optional[Dict[str, Any]]:
+ self.push_to_run_queue_introspection()
+ """Queryless mutation, should be used before legacy fallback method."""
+
+ mutation_params = """
+ $entityName: String!,
+ $projectName: String!,
+ $queueName: String!,
+ $runSpec: JSONString!
+ """
+
+ mutation_input = """
+ entityName: $entityName,
+ projectName: $projectName,
+ queueName: $queueName,
+ runSpec: $runSpec
+ """
+
+ variables: Dict[str, Any] = {
+ "entityName": entity,
+ "projectName": project,
+ "queueName": queue_name,
+ "runSpec": run_spec,
+ }
+ if self.server_push_to_run_queue_supports_priority:
+ if priority is not None:
+ variables["priority"] = priority
+ mutation_params += ", $priority: Int"
+ mutation_input += ", priority: $priority"
+ else:
+ if priority is not None:
+ raise UnsupportedError(
+ "server does not support priority, please update server instance to >=0.46"
+ )
+
+ if self.server_supports_template_variables:
+ if template_variables is not None:
+ variables.update(
+ {"templateVariableValues": json.dumps(template_variables)}
+ )
+ mutation_params += ", $templateVariableValues: JSONString"
+ mutation_input += ", templateVariableValues: $templateVariableValues"
+ else:
+ if template_variables is not None:
+ raise UnsupportedError(
+ "server does not support template variables, please update server instance to >=0.46"
+ )
+
+ mutation = gql(
+ f"""
+ mutation pushToRunQueueByName(
+ {mutation_params}
+ ) {{
+ pushToRunQueueByName(
+ input: {{
+ {mutation_input}
+ }}
+ ) {{
+ runQueueItemId
+ runSpec
+ }}
+ }}
+ """
+ )
+
+ try:
+ result: Optional[Dict[str, Any]] = self.gql(
+ mutation, variables, check_retry_fn=util.no_retry_4xx
+ ).get("pushToRunQueueByName")
+ if not result:
+ return None
+
+ if result.get("runSpec"):
+ run_spec = json.loads(str(result["runSpec"]))
+ result["runSpec"] = run_spec
+
+ return result
+ except Exception as e:
+ if (
+ 'Cannot query field "runSpec" on type "PushToRunQueueByNamePayload"'
+ not in str(e)
+ ):
+ return None
+
+ mutation_no_runspec = gql(
+ """
+ mutation pushToRunQueueByName(
+ $entityName: String!,
+ $projectName: String!,
+ $queueName: String!,
+ $runSpec: JSONString!,
+ ) {
+ pushToRunQueueByName(
+ input: {
+ entityName: $entityName,
+ projectName: $projectName,
+ queueName: $queueName,
+ runSpec: $runSpec
+ }
+ ) {
+ runQueueItemId
+ }
+ }
+ """
+ )
+
+ try:
+ result = self.gql(
+ mutation_no_runspec, variables, check_retry_fn=util.no_retry_4xx
+ ).get("pushToRunQueueByName")
+ except Exception:
+ result = None
+
+ return result
+
+ @normalize_exceptions
+ def push_to_run_queue(
+ self,
+ queue_name: str,
+ launch_spec: Dict[str, str],
+ template_variables: Optional[dict],
+ project_queue: str,
+ priority: Optional[int] = None,
+ ) -> Optional[Dict[str, Any]]:
+ self.push_to_run_queue_introspection()
+ entity = launch_spec.get("queue_entity") or launch_spec["entity"]
+ run_spec = json.dumps(launch_spec)
+
+ push_result = self.push_to_run_queue_by_name(
+ entity, project_queue, queue_name, run_spec, template_variables, priority
+ )
+
+ if push_result:
+ return push_result
+
+ if priority is not None:
+ # Cannot proceed with legacy method if priority is set
+ return None
+
+ """ Legacy Method """
+ queues_found = self.get_project_run_queues(entity, project_queue)
+ matching_queues = [
+ q
+ for q in queues_found
+ if q["name"] == queue_name
+ # ensure user has access to queue
+ and (
+ # TODO: User created queues in the UI have USER access
+ q["access"] in ["PROJECT", "USER"]
+ or q["createdBy"] == self.default_entity
+ )
+ ]
+ if not matching_queues:
+ # in the case of a missing default queue. create it
+ if queue_name == "default":
+ wandb.termlog(
+ f"No default queue existing for entity: {entity} in project: {project_queue}, creating one."
+ )
+ res = self.create_run_queue(
+ launch_spec["entity"],
+ project_queue,
+ queue_name,
+ access="PROJECT",
+ )
+
+ if res is None or res.get("queueID") is None:
+ wandb.termerror(
+ f"Unable to create default queue for entity: {entity} on project: {project_queue}. Run could not be added to a queue"
+ )
+ return None
+ queue_id = res["queueID"]
+
+ else:
+ if project_queue == "model-registry":
+ _msg = f"Unable to push to run queue {queue_name}. Queue not found."
+ else:
+ _msg = f"Unable to push to run queue {project_queue}/{queue_name}. Queue not found."
+ wandb.termwarn(_msg)
+ return None
+ elif len(matching_queues) > 1:
+ wandb.termerror(
+ f"Unable to push to run queue {queue_name}. More than one queue found with this name."
+ )
+ return None
+ else:
+ queue_id = matching_queues[0]["id"]
+ spec_json = json.dumps(launch_spec)
+ variables = {"queueID": queue_id, "runSpec": spec_json}
+
+ mutation_params = """
+ $queueID: ID!,
+ $runSpec: JSONString!
+ """
+ mutation_input = """
+ queueID: $queueID,
+ runSpec: $runSpec
+ """
+ if self.server_supports_template_variables:
+ if template_variables is not None:
+ mutation_params += ", $templateVariableValues: JSONString"
+ mutation_input += ", templateVariableValues: $templateVariableValues"
+ variables.update(
+ {"templateVariableValues": json.dumps(template_variables)}
+ )
+ else:
+ if template_variables is not None:
+ raise UnsupportedError(
+ "server does not support template variables, please update server instance to >=0.46"
+ )
+
+ mutation = gql(
+ f"""
+ mutation pushToRunQueue(
+ {mutation_params}
+ ) {{
+ pushToRunQueue(
+ input: {{{mutation_input}}}
+ ) {{
+ runQueueItemId
+ }}
+ }}
+ """
+ )
+
+ response = self.gql(mutation, variable_values=variables)
+ if not response.get("pushToRunQueue"):
+ raise CommError(f"Error pushing run queue item to queue {queue_name}.")
+
+ result: Optional[Dict[str, Any]] = response["pushToRunQueue"]
+ return result
+
+ @normalize_exceptions
+ def pop_from_run_queue(
+ self,
+ queue_name: str,
+ entity: Optional[str] = None,
+ project: Optional[str] = None,
+ agent_id: Optional[str] = None,
+ ) -> Optional[Dict[str, Any]]:
+ mutation = gql(
+ """
+ mutation popFromRunQueue($entity: String!, $project: String!, $queueName: String!, $launchAgentId: ID) {
+ popFromRunQueue(input: {
+ entityName: $entity,
+ projectName: $project,
+ queueName: $queueName,
+ launchAgentId: $launchAgentId
+ }) {
+ runQueueItemId
+ runSpec
+ }
+ }
+ """
+ )
+ response = self.gql(
+ mutation,
+ variable_values={
+ "entity": entity,
+ "project": project,
+ "queueName": queue_name,
+ "launchAgentId": agent_id,
+ },
+ )
+ result: Optional[Dict[str, Any]] = response["popFromRunQueue"]
+ return result
+
+ @normalize_exceptions
+ def ack_run_queue_item(self, item_id: str, run_id: Optional[str] = None) -> bool:
+ mutation = gql(
+ """
+ mutation ackRunQueueItem($itemId: ID!, $runId: String!) {
+ ackRunQueueItem(input: { runQueueItemId: $itemId, runName: $runId }) {
+ success
+ }
+ }
+ """
+ )
+ response = self.gql(
+ mutation, variable_values={"itemId": item_id, "runId": str(run_id)}
+ )
+ if not response["ackRunQueueItem"]["success"]:
+ raise CommError(
+ "Error acking run queue item. Item may have already been acknowledged by another process"
+ )
+ result: bool = response["ackRunQueueItem"]["success"]
+ return result
+
+ @normalize_exceptions
+ def create_launch_agent_fields_introspection(self) -> List:
+ if self.create_launch_agent_input_info:
+ return self.create_launch_agent_input_info
+ query_string = """
+ query ProbeServerCreateLaunchAgentInput {
+ CreateLaunchAgentInputInfoType: __type(name:"CreateLaunchAgentInput") {
+ inputFields{
+ name
+ }
+ }
+ }
+ """
+
+ query = gql(query_string)
+ res = self.gql(query)
+
+ self.create_launch_agent_input_info = [
+ field.get("name", "")
+ for field in res.get("CreateLaunchAgentInputInfoType", {}).get(
+ "inputFields", [{}]
+ )
+ ]
+ return self.create_launch_agent_input_info
+
+ @normalize_exceptions
+ def create_launch_agent(
+ self,
+ entity: str,
+ project: str,
+ queues: List[str],
+ agent_config: Dict[str, Any],
+ version: str,
+ gorilla_agent_support: bool,
+ ) -> dict:
+ project_queues = self.get_project_run_queues(entity, project)
+ if not project_queues:
+ # create default queue if it doesn't already exist
+ default = self.create_run_queue(
+ entity, project, "default", access="PROJECT"
+ )
+ if default is None or default.get("queueID") is None:
+ raise CommError(
+ f"Unable to create default queue for {entity}/{project}. No queues for agent to poll"
+ )
+ project_queues = [{"id": default["queueID"], "name": "default"}]
+ polling_queue_ids = [
+ q["id"] for q in project_queues if q["name"] in queues
+ ] # filter to poll specified queues
+ if len(polling_queue_ids) != len(queues):
+ raise CommError(
+ f"Could not start launch agent: Not all of requested queues ({', '.join(queues)}) found. "
+ f"Available queues for this project: {','.join([q['name'] for q in project_queues])}"
+ )
+
+ if not gorilla_agent_support:
+ # if gorilla doesn't support launch agents, return a client-generated id
+ return {
+ "success": True,
+ "launchAgentId": None,
+ }
+
+ hostname = socket.gethostname()
+
+ variable_values = {
+ "entity": entity,
+ "project": project,
+ "queues": polling_queue_ids,
+ "hostname": hostname,
+ }
+
+ mutation_params = """
+ $entity: String!,
+ $project: String!,
+ $queues: [ID!]!,
+ $hostname: String!
+ """
+
+ mutation_input = """
+ entityName: $entity,
+ projectName: $project,
+ runQueues: $queues,
+ hostname: $hostname
+ """
+
+ if "agentConfig" in self.create_launch_agent_fields_introspection():
+ variable_values["agentConfig"] = json.dumps(agent_config)
+ mutation_params += ", $agentConfig: JSONString"
+ mutation_input += ", agentConfig: $agentConfig"
+ if "version" in self.create_launch_agent_fields_introspection():
+ variable_values["version"] = version
+ mutation_params += ", $version: String"
+ mutation_input += ", version: $version"
+
+ mutation = gql(
+ f"""
+ mutation createLaunchAgent(
+ {mutation_params}
+ ) {{
+ createLaunchAgent(
+ input: {{
+ {mutation_input}
+ }}
+ ) {{
+ launchAgentId
+ }}
+ }}
+ """
+ )
+ result: dict = self.gql(mutation, variable_values)["createLaunchAgent"]
+ return result
+
+ @normalize_exceptions
+ def update_launch_agent_status(
+ self,
+ agent_id: str,
+ status: str,
+ gorilla_agent_support: bool,
+ ) -> dict:
+ if not gorilla_agent_support:
+ # if gorilla doesn't support launch agents, this is a no-op
+ return {
+ "success": True,
+ }
+
+ mutation = gql(
+ """
+ mutation updateLaunchAgent($agentId: ID!, $agentStatus: String){
+ updateLaunchAgent(
+ input: {
+ launchAgentId: $agentId
+ agentStatus: $agentStatus
+ }
+ ) {
+ success
+ }
+ }
+ """
+ )
+ variable_values = {
+ "agentId": agent_id,
+ "agentStatus": status,
+ }
+ result: dict = self.gql(mutation, variable_values)["updateLaunchAgent"]
+ return result
+
+ @normalize_exceptions
+ def get_launch_agent(self, agent_id: str, gorilla_agent_support: bool) -> dict:
+ if not gorilla_agent_support:
+ return {
+ "id": None,
+ "name": "",
+ "stopPolling": False,
+ }
+ query = gql(
+ """
+ query LaunchAgent($agentId: ID!) {
+ launchAgent(id: $agentId) {
+ id
+ name
+ runQueues
+ hostname
+ agentStatus
+ stopPolling
+ heartbeatAt
+ }
+ }
+ """
+ )
+ variable_values = {
+ "agentId": agent_id,
+ }
+ result: dict = self.gql(query, variable_values)["launchAgent"]
+ return result
+
+ @normalize_exceptions
+ def upsert_run(
+ self,
+ id: Optional[str] = None,
+ name: Optional[str] = None,
+ project: Optional[str] = None,
+ host: Optional[str] = None,
+ group: Optional[str] = None,
+ tags: Optional[List[str]] = None,
+ config: Optional[dict] = None,
+ description: Optional[str] = None,
+ entity: Optional[str] = None,
+ state: Optional[str] = None,
+ display_name: Optional[str] = None,
+ notes: Optional[str] = None,
+ repo: Optional[str] = None,
+ job_type: Optional[str] = None,
+ program_path: Optional[str] = None,
+ commit: Optional[str] = None,
+ sweep_name: Optional[str] = None,
+ summary_metrics: Optional[str] = None,
+ num_retries: Optional[int] = None,
+ ) -> Tuple[dict, bool, Optional[List]]:
+ """Update a run.
+
+ Args:
+ id (str, optional): The existing run to update
+ name (str, optional): The name of the run to create
+ group (str, optional): Name of the group this run is a part of
+ project (str, optional): The name of the project
+ host (str, optional): The name of the host
+ tags (list, optional): A list of tags to apply to the run
+ config (dict, optional): The latest config params
+ description (str, optional): A description of this project
+ entity (str, optional): The entity to scope this project to.
+ display_name (str, optional): The display name of this project
+ notes (str, optional): Notes about this run
+ repo (str, optional): Url of the program's repository.
+ state (str, optional): State of the program.
+ job_type (str, optional): Type of job, e.g 'train'.
+ program_path (str, optional): Path to the program.
+ commit (str, optional): The Git SHA to associate the run with
+ sweep_name (str, optional): The name of the sweep this run is a part of
+ summary_metrics (str, optional): The JSON summary metrics
+ num_retries (int, optional): Number of retries
+ """
+ query_string = """
+ mutation UpsertBucket(
+ $id: String,
+ $name: String,
+ $project: String,
+ $entity: String,
+ $groupName: String,
+ $description: String,
+ $displayName: String,
+ $notes: String,
+ $commit: String,
+ $config: JSONString,
+ $host: String,
+ $debug: Boolean,
+ $program: String,
+ $repo: String,
+ $jobType: String,
+ $state: String,
+ $sweep: String,
+ $tags: [String!],
+ $summaryMetrics: JSONString,
+ ) {
+ upsertBucket(input: {
+ id: $id,
+ name: $name,
+ groupName: $groupName,
+ modelName: $project,
+ entityName: $entity,
+ description: $description,
+ displayName: $displayName,
+ notes: $notes,
+ config: $config,
+ commit: $commit,
+ host: $host,
+ debug: $debug,
+ jobProgram: $program,
+ jobRepo: $repo,
+ jobType: $jobType,
+ state: $state,
+ sweep: $sweep,
+ tags: $tags,
+ summaryMetrics: $summaryMetrics,
+ }) {
+ bucket {
+ id
+ name
+ displayName
+ description
+ config
+ sweepName
+ project {
+ id
+ name
+ entity {
+ id
+ name
+ }
+ }
+ historyLineCount
+ }
+ inserted
+ _Server_Settings_
+ }
+ }
+ """
+ self.server_settings_introspection()
+
+ server_settings_string = (
+ """
+ serverSettings {
+ serverMessages{
+ utfText
+ plainText
+ htmlText
+ messageType
+ messageLevel
+ }
+ }
+ """
+ if self._server_settings_type
+ else ""
+ )
+
+ query_string = query_string.replace("_Server_Settings_", server_settings_string)
+ mutation = gql(query_string)
+ config_str = json.dumps(config) if config else None
+ if not description or description.isspace():
+ description = None
+
+ kwargs = {}
+ if num_retries is not None:
+ kwargs["num_retries"] = num_retries
+
+ variable_values = {
+ "id": id,
+ "entity": entity or self.settings("entity"),
+ "name": name,
+ "project": project or util.auto_project_name(program_path),
+ "groupName": group,
+ "tags": tags,
+ "description": description,
+ "config": config_str,
+ "commit": commit,
+ "displayName": display_name,
+ "notes": notes,
+ "host": None
+ if self.settings().get("anonymous") in ["allow", "must"]
+ else host,
+ "debug": env.is_debug(env=self._environ),
+ "repo": repo,
+ "program": program_path,
+ "jobType": job_type,
+ "state": state,
+ "sweep": sweep_name,
+ "summaryMetrics": summary_metrics,
+ }
+
+ # retry conflict errors for 2 minutes, default to no_auth_retry
+ check_retry_fn = util.make_check_retry_fn(
+ check_fn=util.check_retry_conflict_or_gone,
+ check_timedelta=datetime.timedelta(minutes=2),
+ fallback_retry_fn=util.no_retry_auth,
+ )
+
+ response = self.gql(
+ mutation,
+ variable_values=variable_values,
+ check_retry_fn=check_retry_fn,
+ **kwargs,
+ )
+
+ run_obj: Dict[str, Dict[str, Dict[str, str]]] = response["upsertBucket"][
+ "bucket"
+ ]
+ project_obj: Dict[str, Dict[str, str]] = run_obj.get("project", {})
+ if project_obj:
+ self.set_setting("project", project_obj["name"])
+ entity_obj = project_obj.get("entity", {})
+ if entity_obj:
+ self.set_setting("entity", entity_obj["name"])
+
+ server_messages = None
+ if self._server_settings_type:
+ server_messages = (
+ response["upsertBucket"]
+ .get("serverSettings", {})
+ .get("serverMessages", [])
+ )
+
+ return (
+ response["upsertBucket"]["bucket"],
+ response["upsertBucket"]["inserted"],
+ server_messages,
+ )
+
+ @normalize_exceptions
+ def rewind_run(
+ self,
+ run_name: str,
+ metric_name: str,
+ metric_value: float,
+ program_path: Optional[str] = None,
+ entity: Optional[str] = None,
+ project: Optional[str] = None,
+ num_retries: Optional[int] = None,
+ ) -> dict:
+ """Rewinds a run to a previous state.
+
+ Args:
+ run_name (str): The name of the run to rewind
+ metric_name (str): The name of the metric to rewind to
+ metric_value (float): The value of the metric to rewind to
+ program_path (str, optional): Path to the program
+ entity (str, optional): The entity to scope this project to
+ project (str, optional): The name of the project
+ num_retries (int, optional): Number of retries
+
+ Returns:
+ A dict with the rewound run
+
+ {
+ "id": "run_id",
+ "name": "run_name",
+ "displayName": "run_display_name",
+ "description": "run_description",
+ "config": "stringified_run_config_json",
+ "sweepName": "run_sweep_name",
+ "project": {
+ "id": "project_id",
+ "name": "project_name",
+ "entity": {
+ "id": "entity_id",
+ "name": "entity_name"
+ }
+ },
+ "historyLineCount": 100,
+ }
+ """
+ query_string = """
+ mutation RewindRun($runName: String!, $entity: String, $project: String, $metricName: String!, $metricValue: Float!) {
+ rewindRun(input: {runName: $runName, entityName: $entity, projectName: $project, metricName: $metricName, metricValue: $metricValue}) {
+ rewoundRun {
+ id
+ name
+ displayName
+ description
+ config
+ sweepName
+ project {
+ id
+ name
+ entity {
+ id
+ name
+ }
+ }
+ historyLineCount
+ }
+ }
+ }
+ """
+
+ mutation = gql(query_string)
+
+ kwargs = {}
+ if num_retries is not None:
+ kwargs["num_retries"] = num_retries
+
+ variable_values = {
+ "runName": run_name,
+ "entity": entity or self.settings("entity"),
+ "project": project or util.auto_project_name(program_path),
+ "metricName": metric_name,
+ "metricValue": metric_value,
+ }
+
+ # retry conflict errors for 2 minutes, default to no_auth_retry
+ check_retry_fn = util.make_check_retry_fn(
+ check_fn=util.check_retry_conflict_or_gone,
+ check_timedelta=datetime.timedelta(minutes=2),
+ fallback_retry_fn=util.no_retry_auth,
+ )
+
+ response = self.gql(
+ mutation,
+ variable_values=variable_values,
+ check_retry_fn=check_retry_fn,
+ **kwargs,
+ )
+
+ run_obj: Dict[str, Dict[str, Dict[str, str]]] = response.get(
+ "rewindRun", {}
+ ).get("rewoundRun", {})
+ project_obj: Dict[str, Dict[str, str]] = run_obj.get("project", {})
+ if project_obj:
+ self.set_setting("project", project_obj["name"])
+ entity_obj = project_obj.get("entity", {})
+ if entity_obj:
+ self.set_setting("entity", entity_obj["name"])
+
+ return run_obj
+
+ @normalize_exceptions
+ def get_run_info(
+ self,
+ entity: str,
+ project: str,
+ name: str,
+ ) -> dict:
+ query = gql(
+ """
+ query RunInfo($project: String!, $entity: String!, $name: String!) {
+ project(name: $project, entityName: $entity) {
+ run(name: $name) {
+ runInfo {
+ program
+ args
+ os
+ python
+ colab
+ executable
+ codeSaved
+ cpuCount
+ gpuCount
+ gpu
+ git {
+ remote
+ commit
+ }
+ }
+ }
+ }
+ }
+ """
+ )
+ variable_values = {"project": project, "entity": entity, "name": name}
+ res = self.gql(query, variable_values)
+ if res.get("project") is None:
+ raise CommError(
+ f"Error fetching run info for {entity}/{project}/{name}. Check that this project exists and you have access to this entity and project"
+ )
+ elif res["project"].get("run") is None:
+ raise CommError(
+ f"Error fetching run info for {entity}/{project}/{name}. Check that this run id exists"
+ )
+ run_info: dict = res["project"]["run"]["runInfo"]
+ return run_info
+
+ @normalize_exceptions
+ def get_run_state(self, entity: str, project: str, name: str) -> str:
+ query = gql(
+ """
+ query RunState(
+ $project: String!,
+ $entity: String!,
+ $name: String!) {
+ project(name: $project, entityName: $entity) {
+ run(name: $name) {
+ state
+ }
+ }
+ }
+ """
+ )
+ variable_values = {
+ "project": project,
+ "entity": entity,
+ "name": name,
+ }
+ res = self.gql(query, variable_values)
+ if res.get("project") is None or res["project"].get("run") is None:
+ raise CommError(f"Error fetching run state for {entity}/{project}/{name}.")
+ run_state: str = res["project"]["run"]["state"]
+ return run_state
+
+ @normalize_exceptions
+ def create_run_files_introspection(self) -> bool:
+ _, _, mutations = self.server_info_introspection()
+ return "createRunFiles" in mutations
+
+ @normalize_exceptions
+ def upload_urls(
+ self,
+ project: str,
+ files: Union[List[str], Dict[str, IO]],
+ run: Optional[str] = None,
+ entity: Optional[str] = None,
+ description: Optional[str] = None,
+ ) -> Tuple[str, List[str], Dict[str, Dict[str, Any]]]:
+ """Generate temporary resumable upload urls.
+
+ Args:
+ project (str): The project to download
+ files (list or dict): The filenames to upload
+ run (str, optional): The run to upload to
+ entity (str, optional): The entity to scope this project to.
+ description (str, optional): description
+
+ Returns:
+ (run_id, upload_headers, file_info)
+ run_id: id of run we uploaded files to
+ upload_headers: A list of headers to use when uploading files.
+ file_info: A dict of filenames and urls.
+ {
+ "run_id": "run_id",
+ "upload_headers": [""],
+ "file_info": [
+ { "weights.h5": { "uploadUrl": "https://weights.url" } },
+ { "model.json": { "uploadUrl": "https://model.json" } }
+ ]
+ }
+ """
+ run_name = run or self.current_run_id
+ assert run_name, "run must be specified"
+ entity = entity or self.settings("entity")
+ assert entity, "entity must be specified"
+
+ has_create_run_files_mutation = self.create_run_files_introspection()
+ if not has_create_run_files_mutation:
+ return self.legacy_upload_urls(project, files, run, entity, description)
+
+ query = gql(
+ """
+ mutation CreateRunFiles($entity: String!, $project: String!, $run: String!, $files: [String!]!) {
+ createRunFiles(input: {entityName: $entity, projectName: $project, runName: $run, files: $files}) {
+ runID
+ uploadHeaders
+ files {
+ name
+ uploadUrl
+ }
+ }
+ }
+ """
+ )
+
+ query_result = self.gql(
+ query,
+ variable_values={
+ "project": project,
+ "run": run_name,
+ "entity": entity,
+ "files": [file for file in files],
+ },
+ )
+
+ result = query_result["createRunFiles"]
+ run_id = result["runID"]
+ if not run_id:
+ raise CommError(
+ f"Error uploading files to {entity}/{project}/{run_name}. Check that this project exists and you have access to this entity and project"
+ )
+ file_name_urls = {file["name"]: file for file in result["files"]}
+ return run_id, result["uploadHeaders"], file_name_urls
+
+ def legacy_upload_urls(
+ self,
+ project: str,
+ files: Union[List[str], Dict[str, IO]],
+ run: Optional[str] = None,
+ entity: Optional[str] = None,
+ description: Optional[str] = None,
+ ) -> Tuple[str, List[str], Dict[str, Dict[str, Any]]]:
+ """Generate temporary resumable upload urls.
+
+ A new mutation createRunFiles was introduced after 0.15.4.
+ This function is used to support older versions.
+ """
+ query = gql(
+ """
+ query RunUploadUrls($name: String!, $files: [String]!, $entity: String, $run: String!, $description: String) {
+ model(name: $name, entityName: $entity) {
+ bucket(name: $run, desc: $description) {
+ id
+ files(names: $files) {
+ uploadHeaders
+ edges {
+ node {
+ name
+ url(upload: true)
+ updatedAt
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+ )
+ run_id = run or self.current_run_id
+ assert run_id, "run must be specified"
+ entity = entity or self.settings("entity")
+ query_result = self.gql(
+ query,
+ variable_values={
+ "name": project,
+ "run": run_id,
+ "entity": entity,
+ "files": [file for file in files],
+ "description": description,
+ },
+ )
+
+ run_obj = query_result["model"]["bucket"]
+ if run_obj:
+ for file_node in run_obj["files"]["edges"]:
+ file = file_node["node"]
+ # we previously used "url" field but now use "uploadUrl"
+ # replace the "url" field with "uploadUrl for downstream compatibility
+ if "url" in file and "uploadUrl" not in file:
+ file["uploadUrl"] = file.pop("url")
+
+ result = {
+ file["name"]: file for file in self._flatten_edges(run_obj["files"])
+ }
+ return run_obj["id"], run_obj["files"]["uploadHeaders"], result
+ else:
+ raise CommError(f"Run does not exist {entity}/{project}/{run_id}.")
+
+ @normalize_exceptions
+ def download_urls(
+ self,
+ project: str,
+ run: Optional[str] = None,
+ entity: Optional[str] = None,
+ ) -> Dict[str, Dict[str, str]]:
+ """Generate download urls.
+
+ Args:
+ project (str): The project to download
+ run (str): The run to upload to
+ entity (str, optional): The entity to scope this project to. Defaults to wandb models
+
+ Returns:
+ A dict of extensions and urls
+
+ {
+ 'weights.h5': { "url": "https://weights.url", "updatedAt": '2013-04-26T22:22:23.832Z', 'md5': 'mZFLkyvTelC5g8XnyQrpOw==' },
+ 'model.json': { "url": "https://model.url", "updatedAt": '2013-04-26T22:22:23.832Z', 'md5': 'mZFLkyvTelC5g8XnyQrpOw==' }
+ }
+ """
+ query = gql(
+ """
+ query RunDownloadUrls($name: String!, $entity: String, $run: String!) {
+ model(name: $name, entityName: $entity) {
+ bucket(name: $run) {
+ files {
+ edges {
+ node {
+ name
+ url
+ md5
+ updatedAt
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+ )
+ run = run or self.current_run_id
+ assert run, "run must be specified"
+ entity = entity or self.settings("entity")
+ query_result = self.gql(
+ query,
+ variable_values={
+ "name": project,
+ "run": run,
+ "entity": entity,
+ },
+ )
+ if query_result["model"] is None:
+ raise CommError(f"Run does not exist {entity}/{project}/{run}.")
+ files = self._flatten_edges(query_result["model"]["bucket"]["files"])
+ return {file["name"]: file for file in files if file}
+
+ @normalize_exceptions
+ def download_url(
+ self,
+ project: str,
+ file_name: str,
+ run: Optional[str] = None,
+ entity: Optional[str] = None,
+ ) -> Optional[Dict[str, str]]:
+ """Generate download urls.
+
+ Args:
+ project (str): The project to download
+ file_name (str): The name of the file to download
+ run (str): The run to upload to
+ entity (str, optional): The entity to scope this project to. Defaults to wandb models
+
+ Returns:
+ A dict of extensions and urls
+
+ { "url": "https://weights.url", "updatedAt": '2013-04-26T22:22:23.832Z', 'md5': 'mZFLkyvTelC5g8XnyQrpOw==' }
+
+ """
+ query = gql(
+ """
+ query RunDownloadUrl($name: String!, $fileName: String!, $entity: String, $run: String!) {
+ model(name: $name, entityName: $entity) {
+ bucket(name: $run) {
+ files(names: [$fileName]) {
+ edges {
+ node {
+ name
+ url
+ md5
+ updatedAt
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+ )
+ run = run or self.current_run_id
+ assert run, "run must be specified"
+ query_result = self.gql(
+ query,
+ variable_values={
+ "name": project,
+ "run": run,
+ "fileName": file_name,
+ "entity": entity or self.settings("entity"),
+ },
+ )
+ if query_result["model"]:
+ files = self._flatten_edges(query_result["model"]["bucket"]["files"])
+ return files[0] if len(files) > 0 and files[0].get("updatedAt") else None
+ else:
+ return None
+
+ @normalize_exceptions
+ def download_file(self, url: str) -> Tuple[int, requests.Response]:
+ """Initiate a streaming download.
+
+ Args:
+ url (str): The url to download
+
+ Returns:
+ A tuple of the content length and the streaming response
+ """
+ check_httpclient_logger_handler()
+
+ http_headers = _thread_local_api_settings.headers or {}
+
+ auth = None
+ if self.access_token is not None:
+ http_headers["Authorization"] = f"Bearer {self.access_token}"
+ elif _thread_local_api_settings.cookies is None:
+ auth = ("api", self.api_key or "")
+
+ response = requests.get(
+ url,
+ auth=auth,
+ cookies=_thread_local_api_settings.cookies or {},
+ headers=http_headers,
+ stream=True,
+ )
+ response.raise_for_status()
+ return int(response.headers.get("content-length", 0)), response
+
+ @normalize_exceptions
+ def download_write_file(
+ self,
+ metadata: Dict[str, str],
+ out_dir: Optional[str] = None,
+ ) -> Tuple[str, Optional[requests.Response]]:
+ """Download a file from a run and write it to wandb/.
+
+ Args:
+ metadata (obj): The metadata object for the file to download. Comes from Api.download_urls().
+ out_dir (str, optional): The directory to write the file to. Defaults to wandb/
+
+ Returns:
+ A tuple of the file's local path and the streaming response. The streaming response is None if the file
+ already existed and was up-to-date.
+ """
+ filename = metadata["name"]
+ path = os.path.join(out_dir or self.settings("wandb_dir"), filename)
+ if self.file_current(filename, B64MD5(metadata["md5"])):
+ return path, None
+
+ size, response = self.download_file(metadata["url"])
+
+ with util.fsync_open(path, "wb") as file:
+ for data in response.iter_content(chunk_size=1024):
+ file.write(data)
+
+ return path, response
+
+ def upload_file_azure(
+ self, url: str, file: Any, extra_headers: Dict[str, str]
+ ) -> None:
+ """Upload a file to azure."""
+ from azure.core.exceptions import AzureError # type: ignore
+
+ # Configure the client without retries so our existing logic can handle them
+ client = self._azure_blob_module.BlobClient.from_blob_url(
+ url, retry_policy=self._azure_blob_module.LinearRetry(retry_total=0)
+ )
+ try:
+ if extra_headers.get("Content-MD5") is not None:
+ md5: Optional[bytes] = base64.b64decode(extra_headers["Content-MD5"])
+ else:
+ md5 = None
+ content_settings = self._azure_blob_module.ContentSettings(
+ content_md5=md5,
+ content_type=extra_headers.get("Content-Type"),
+ )
+ client.upload_blob(
+ file,
+ max_concurrency=4,
+ length=len(file),
+ overwrite=True,
+ content_settings=content_settings,
+ )
+ except AzureError as e:
+ if hasattr(e, "response"):
+ response = requests.models.Response()
+ response.status_code = e.response.status_code
+ response.headers = e.response.headers
+ raise requests.exceptions.RequestException(e.message, response=response)
+ else:
+ raise requests.exceptions.ConnectionError(e.message)
+
+ def upload_multipart_file_chunk(
+ self,
+ url: str,
+ upload_chunk: bytes,
+ extra_headers: Optional[Dict[str, str]] = None,
+ ) -> Optional[requests.Response]:
+ """Upload a file chunk to S3 with failure resumption.
+
+ Args:
+ url: The url to download
+ upload_chunk: The path to the file you want to upload
+ extra_headers: A dictionary of extra headers to send with the request
+
+ Returns:
+ The `requests` library response object
+ """
+ check_httpclient_logger_handler()
+ try:
+ if env.is_debug(env=self._environ):
+ logger.debug("upload_file: %s", url)
+ response = self._upload_file_session.put(
+ url, data=upload_chunk, headers=extra_headers
+ )
+ if env.is_debug(env=self._environ):
+ logger.debug("upload_file: %s complete", url)
+ response.raise_for_status()
+ except requests.exceptions.RequestException as e:
+ logger.exception(f"upload_file exception for {url=}")
+ response_content = e.response.content if e.response is not None else ""
+ status_code = e.response.status_code if e.response is not None else 0
+ # S3 reports retryable request timeouts out-of-band
+ is_aws_retryable = status_code == 400 and "RequestTimeout" in str(
+ response_content
+ )
+ # Retry errors from cloud storage or local network issues
+ if (
+ status_code in (308, 408, 409, 429, 500, 502, 503, 504)
+ or isinstance(
+ e,
+ (requests.exceptions.Timeout, requests.exceptions.ConnectionError),
+ )
+ or is_aws_retryable
+ ):
+ _e = retry.TransientError(exc=e)
+ raise _e.with_traceback(sys.exc_info()[2])
+ else:
+ wandb._sentry.reraise(e)
+ return response
+
+ def upload_file(
+ self,
+ url: str,
+ file: IO[bytes],
+ callback: Optional["ProgressFn"] = None,
+ extra_headers: Optional[Dict[str, str]] = None,
+ ) -> Optional[requests.Response]:
+ """Upload a file to W&B with failure resumption.
+
+ Args:
+ url: The url to download
+ file: The path to the file you want to upload
+ callback: A callback which is passed the number of
+ bytes uploaded since the last time it was called, used to report progress
+ extra_headers: A dictionary of extra headers to send with the request
+
+ Returns:
+ The `requests` library response object
+ """
+ check_httpclient_logger_handler()
+ extra_headers = extra_headers.copy() if extra_headers else {}
+ response: Optional[requests.Response] = None
+ progress = Progress(file, callback=callback)
+ try:
+ if "x-ms-blob-type" in extra_headers and self._azure_blob_module:
+ self.upload_file_azure(url, progress, extra_headers)
+ else:
+ if "x-ms-blob-type" in extra_headers:
+ wandb.termwarn(
+ "Azure uploads over 256MB require the azure SDK, install with pip install wandb[azure]",
+ repeat=False,
+ )
+ if env.is_debug(env=self._environ):
+ logger.debug("upload_file: %s", url)
+ response = self._upload_file_session.put(
+ url, data=progress, headers=extra_headers
+ )
+ if env.is_debug(env=self._environ):
+ logger.debug("upload_file: %s complete", url)
+ response.raise_for_status()
+ except requests.exceptions.RequestException as e:
+ logger.exception(f"upload_file exception for {url=}")
+ response_content = e.response.content if e.response is not None else ""
+ status_code = e.response.status_code if e.response is not None else 0
+ # S3 reports retryable request timeouts out-of-band
+ is_aws_retryable = (
+ "x-amz-meta-md5" in extra_headers
+ and status_code == 400
+ and "RequestTimeout" in str(response_content)
+ )
+ # We need to rewind the file for the next retry (the file passed in is `seek`'ed to 0)
+ progress.rewind()
+ # Retry errors from cloud storage or local network issues
+ if (
+ status_code in (308, 408, 409, 429, 500, 502, 503, 504)
+ or isinstance(
+ e,
+ (requests.exceptions.Timeout, requests.exceptions.ConnectionError),
+ )
+ or is_aws_retryable
+ ):
+ _e = retry.TransientError(exc=e)
+ raise _e.with_traceback(sys.exc_info()[2])
+ else:
+ wandb._sentry.reraise(e)
+
+ return response
+
+ @normalize_exceptions
+ def register_agent(
+ self,
+ host: str,
+ sweep_id: Optional[str] = None,
+ project_name: Optional[str] = None,
+ entity: Optional[str] = None,
+ ) -> dict:
+ """Register a new agent.
+
+ Args:
+ host (str): hostname
+ sweep_id (str): sweep id
+ project_name: (str): model that contains sweep
+ entity: (str): entity that contains sweep
+ """
+ mutation = gql(
+ """
+ mutation CreateAgent(
+ $host: String!
+ $projectName: String,
+ $entityName: String,
+ $sweep: String!
+ ) {
+ createAgent(input: {
+ host: $host,
+ projectName: $projectName,
+ entityName: $entityName,
+ sweep: $sweep,
+ }) {
+ agent {
+ id
+ }
+ }
+ }
+ """
+ )
+ if entity is None:
+ entity = self.settings("entity")
+ if project_name is None:
+ project_name = self.settings("project")
+
+ response = self.gql(
+ mutation,
+ variable_values={
+ "host": host,
+ "entityName": entity,
+ "projectName": project_name,
+ "sweep": sweep_id,
+ },
+ check_retry_fn=util.no_retry_4xx,
+ )
+ result: dict = response["createAgent"]["agent"]
+ return result
+
+ def agent_heartbeat(
+ self, agent_id: str, metrics: dict, run_states: dict
+ ) -> List[Dict[str, Any]]:
+ """Notify server about agent state, receive commands.
+
+ Args:
+ agent_id (str): agent_id
+ metrics (dict): system metrics
+ run_states (dict): run_id: state mapping
+ Returns:
+ List of commands to execute.
+ """
+ mutation = gql(
+ """
+ mutation Heartbeat(
+ $id: ID!,
+ $metrics: JSONString,
+ $runState: JSONString
+ ) {
+ agentHeartbeat(input: {
+ id: $id,
+ metrics: $metrics,
+ runState: $runState
+ }) {
+ agent {
+ id
+ }
+ commands
+ }
+ }
+ """
+ )
+
+ if agent_id is None:
+ raise ValueError("Cannot call heartbeat with an unregistered agent.")
+
+ try:
+ response = self.gql(
+ mutation,
+ variable_values={
+ "id": agent_id,
+ "metrics": json.dumps(metrics),
+ "runState": json.dumps(run_states),
+ },
+ timeout=60,
+ )
+ except Exception:
+ logger.exception("Error communicating with W&B.")
+ return []
+ else:
+ result: List[Dict[str, Any]] = json.loads(
+ response["agentHeartbeat"]["commands"]
+ )
+ return result
+
+ @staticmethod
+ def _validate_config_and_fill_distribution(config: dict) -> dict:
+ # verify that parameters are well specified.
+ # TODO(dag): deprecate this in favor of jsonschema validation once
+ # apiVersion 2 is released and local controller is integrated with
+ # wandb/client.
+
+ # avoid modifying the original config dict in
+ # case it is reused outside the calling func
+ config = deepcopy(config)
+
+ # explicitly cast to dict in case config was passed as a sweepconfig
+ # sweepconfig does not serialize cleanly to yaml and breaks graphql,
+ # but it is a subclass of dict, so this conversion is clean
+ config = dict(config)
+
+ if "parameters" not in config:
+ # still shows an anaconda warning, but doesn't error
+ return config
+
+ for parameter_name in config["parameters"]:
+ parameter = config["parameters"][parameter_name]
+ if "min" in parameter and "max" in parameter:
+ if "distribution" not in parameter:
+ if isinstance(parameter["min"], int) and isinstance(
+ parameter["max"], int
+ ):
+ parameter["distribution"] = "int_uniform"
+ elif isinstance(parameter["min"], float) and isinstance(
+ parameter["max"], float
+ ):
+ parameter["distribution"] = "uniform"
+ else:
+ raise ValueError(
+ f"Parameter {parameter_name} is ambiguous, please specify bounds as both floats (for a float_"
+ "uniform distribution) or ints (for an int_uniform distribution)."
+ )
+ return config
+
+ @normalize_exceptions
+ def upsert_sweep(
+ self,
+ config: dict,
+ controller: Optional[str] = None,
+ launch_scheduler: Optional[str] = None,
+ scheduler: Optional[str] = None,
+ obj_id: Optional[str] = None,
+ project: Optional[str] = None,
+ entity: Optional[str] = None,
+ state: Optional[str] = None,
+ prior_runs: Optional[List[str]] = None,
+ display_name: Optional[str] = None,
+ template_variable_values: Optional[Dict[str, Any]] = None,
+ ) -> Tuple[str, List[str]]:
+ """Upsert a sweep object.
+
+ Args:
+ config (dict): sweep config (will be converted to yaml)
+ controller (str): controller to use
+ launch_scheduler (str): launch scheduler to use
+ scheduler (str): scheduler to use
+ obj_id (str): object id
+ project (str): project to use
+ entity (str): entity to use
+ state (str): state
+ prior_runs (list): IDs of existing runs to add to the sweep
+ display_name (str): display name for the sweep
+ template_variable_values (dict): template variable values
+ """
+ project_query = """
+ project {
+ id
+ name
+ entity {
+ id
+ name
+ }
+ }
+ """
+ mutation_str = """
+ mutation UpsertSweep(
+ $id: ID,
+ $config: String,
+ $description: String,
+ $entityName: String,
+ $projectName: String,
+ $controller: JSONString,
+ $scheduler: JSONString,
+ $state: String,
+ $priorRunsFilters: JSONString,
+ $displayName: String,
+ ) {
+ upsertSweep(input: {
+ id: $id,
+ config: $config,
+ description: $description,
+ entityName: $entityName,
+ projectName: $projectName,
+ controller: $controller,
+ scheduler: $scheduler,
+ state: $state,
+ priorRunsFilters: $priorRunsFilters,
+ displayName: $displayName,
+ }) {
+ sweep {
+ name
+ _PROJECT_QUERY_
+ }
+ configValidationWarnings
+ }
+ }
+ """
+ # TODO(jhr): we need protocol versioning to know schema is not supported
+ # for now we will just try both new and old query
+ mutation_5 = gql(
+ mutation_str.replace(
+ "$controller: JSONString,",
+ "$controller: JSONString,$launchScheduler: JSONString, $templateVariableValues: JSONString,",
+ )
+ .replace(
+ "controller: $controller,",
+ "controller: $controller,launchScheduler: $launchScheduler,templateVariableValues: $templateVariableValues,",
+ )
+ .replace("_PROJECT_QUERY_", project_query)
+ )
+ # launchScheduler was introduced in core v0.14.0
+ mutation_4 = gql(
+ mutation_str.replace(
+ "$controller: JSONString,",
+ "$controller: JSONString,$launchScheduler: JSONString,",
+ )
+ .replace(
+ "controller: $controller,",
+ "controller: $controller,launchScheduler: $launchScheduler",
+ )
+ .replace("_PROJECT_QUERY_", project_query)
+ )
+
+ # mutation 3 maps to backend that can support CLI version of at least 0.10.31
+ mutation_3 = gql(mutation_str.replace("_PROJECT_QUERY_", project_query))
+ mutation_2 = gql(
+ mutation_str.replace("_PROJECT_QUERY_", project_query).replace(
+ "configValidationWarnings", ""
+ )
+ )
+ mutation_1 = gql(
+ mutation_str.replace("_PROJECT_QUERY_", "").replace(
+ "configValidationWarnings", ""
+ )
+ )
+
+ # TODO(dag): replace this with a query for protocol versioning
+ mutations = [mutation_5, mutation_4, mutation_3, mutation_2, mutation_1]
+
+ config = self._validate_config_and_fill_distribution(config)
+
+ # Silly, but attr-dicts like EasyDicts don't serialize correctly to yaml.
+ # This sanitizes them with a round trip pass through json to get a regular dict.
+ config_str = yaml.dump(
+ json.loads(json.dumps(config)), Dumper=util.NonOctalStringDumper
+ )
+ filters = None
+ if prior_runs:
+ filters = json.dumps({"$or": [{"name": r} for r in prior_runs]})
+
+ err: Optional[Exception] = None
+ for mutation in mutations:
+ try:
+ variables = {
+ "id": obj_id,
+ "config": config_str,
+ "description": config.get("description"),
+ "entityName": entity or self.settings("entity"),
+ "projectName": project or self.settings("project"),
+ "controller": controller,
+ "launchScheduler": launch_scheduler,
+ "templateVariableValues": json.dumps(template_variable_values),
+ "scheduler": scheduler,
+ "priorRunsFilters": filters,
+ "displayName": display_name,
+ }
+ if state:
+ variables["state"] = state
+
+ response = self.gql(
+ mutation,
+ variable_values=variables,
+ check_retry_fn=util.no_retry_4xx,
+ )
+ except UsageError:
+ raise
+ except Exception as e:
+ # graphql schema exception is generic
+ err = e
+ continue
+ err = None
+ break
+ if err:
+ raise err
+
+ sweep: Dict[str, Dict[str, Dict]] = response["upsertSweep"]["sweep"]
+ project_obj: Dict[str, Dict] = sweep.get("project", {})
+ if project_obj:
+ self.set_setting("project", project_obj["name"])
+ entity_obj: dict = project_obj.get("entity", {})
+ if entity_obj:
+ self.set_setting("entity", entity_obj["name"])
+
+ warnings = response["upsertSweep"].get("configValidationWarnings", [])
+ return response["upsertSweep"]["sweep"]["name"], warnings
+
+ @normalize_exceptions
+ def create_anonymous_api_key(self) -> str:
+ """Create a new API key belonging to a new anonymous user."""
+ mutation = gql(
+ """
+ mutation CreateAnonymousApiKey {
+ createAnonymousEntity(input: {}) {
+ apiKey {
+ name
+ }
+ }
+ }
+ """
+ )
+
+ response = self.gql(mutation, variable_values={})
+ key: str = str(response["createAnonymousEntity"]["apiKey"]["name"])
+ return key
+
+ @staticmethod
+ def file_current(fname: str, md5: B64MD5) -> bool:
+ """Checksum a file and compare the md5 with the known md5."""
+ return os.path.isfile(fname) and md5_file_b64(fname) == md5
+
+ @normalize_exceptions
+ def pull(
+ self, project: str, run: Optional[str] = None, entity: Optional[str] = None
+ ) -> "List[requests.Response]":
+ """Download files from W&B.
+
+ Args:
+ project (str): The project to download
+ run (str, optional): The run to upload to
+ entity (str, optional): The entity to scope this project to. Defaults to wandb models
+
+ Returns:
+ The `requests` library response object
+ """
+ project, run = self.parse_slug(project, run=run)
+ urls = self.download_urls(project, run, entity)
+ responses = []
+ for filename in urls:
+ _, response = self.download_write_file(urls[filename])
+ if response:
+ responses.append(response)
+
+ return responses
+
+ def get_project(self) -> str:
+ project: str = self.default_settings.get("project") or self.settings("project")
+ return project
+
+ @normalize_exceptions
+ def push(
+ self,
+ files: Union[List[str], Dict[str, IO]],
+ run: Optional[str] = None,
+ entity: Optional[str] = None,
+ project: Optional[str] = None,
+ description: Optional[str] = None,
+ force: bool = True,
+ progress: Union[TextIO, Literal[False]] = False,
+ ) -> "List[Optional[requests.Response]]":
+ """Uploads multiple files to W&B.
+
+ Args:
+ files (list or dict): The filenames to upload, when dict the values are open files
+ run (str, optional): The run to upload to
+ entity (str, optional): The entity to scope this project to. Defaults to wandb models
+ project (str, optional): The name of the project to upload to. Defaults to the one in settings.
+ description (str, optional): The description of the changes
+ force (bool, optional): Whether to prevent push if git has uncommitted changes
+ progress (callable, or stream): If callable, will be called with (chunk_bytes,
+ total_bytes) as argument. If TextIO, renders a progress bar to it.
+
+ Returns:
+ A list of `requests.Response` objects
+ """
+ if project is None:
+ project = self.get_project()
+ if project is None:
+ raise CommError("No project configured.")
+ if run is None:
+ run = self.current_run_id
+
+ # TODO(adrian): we use a retriable version of self.upload_file() so
+ # will never retry self.upload_urls() here. Instead, maybe we should
+ # make push itself retriable.
+ _, upload_headers, result = self.upload_urls(
+ project,
+ files,
+ run,
+ entity,
+ )
+ extra_headers = {}
+ for upload_header in upload_headers:
+ key, val = upload_header.split(":", 1)
+ extra_headers[key] = val
+ responses = []
+ for file_name, file_info in result.items():
+ file_url = file_info["uploadUrl"]
+
+ # If the upload URL is relative, fill it in with the base URL,
+ # since it's a proxied file store like the on-prem VM.
+ if file_url.startswith("/"):
+ file_url = f"{self.api_url}{file_url}"
+
+ try:
+ # To handle Windows paths
+ # TODO: this doesn't handle absolute paths...
+ normal_name = os.path.join(*file_name.split("/"))
+ open_file = (
+ files[file_name]
+ if isinstance(files, dict)
+ else open(normal_name, "rb")
+ )
+ except OSError:
+ print(f"{file_name} does not exist") # noqa: T201
+ continue
+ if progress is False:
+ responses.append(
+ self.upload_file_retry(
+ file_info["uploadUrl"], open_file, extra_headers=extra_headers
+ )
+ )
+ else:
+ if callable(progress):
+ responses.append( # type: ignore
+ self.upload_file_retry(
+ file_url, open_file, progress, extra_headers=extra_headers
+ )
+ )
+ else:
+ length = os.fstat(open_file.fileno()).st_size
+ with click.progressbar( # type: ignore
+ file=progress,
+ length=length,
+ label=f"Uploading file: {file_name}",
+ fill_char=click.style("&", fg="green"),
+ ) as bar:
+ responses.append(
+ self.upload_file_retry(
+ file_url,
+ open_file,
+ lambda bites, _: bar.update(bites),
+ extra_headers=extra_headers,
+ )
+ )
+ open_file.close()
+ return responses
+
+ def link_artifact(
+ self,
+ client_id: str,
+ server_id: str,
+ portfolio_name: str,
+ entity: str,
+ project: str,
+ aliases: Sequence[str],
+ organization: str,
+ ) -> Dict[str, Any]:
+ template = """
+ mutation LinkArtifact(
+ $artifactPortfolioName: String!,
+ $entityName: String!,
+ $projectName: String!,
+ $aliases: [ArtifactAliasInput!],
+ ID_TYPE
+ ) {
+ linkArtifact(input: {
+ artifactPortfolioName: $artifactPortfolioName,
+ entityName: $entityName,
+ projectName: $projectName,
+ aliases: $aliases,
+ ID_VALUE
+ }) {
+ versionIndex
+ }
+ }
+ """
+
+ org_entity = ""
+ if is_artifact_registry_project(project):
+ try:
+ org_entity = self._resolve_org_entity_name(
+ entity=entity, organization=organization
+ )
+ except ValueError as e:
+ wandb.termerror(str(e))
+ raise
+
+ def replace(a: str, b: str) -> None:
+ nonlocal template
+ template = template.replace(a, b)
+
+ if server_id:
+ replace("ID_TYPE", "$artifactID: ID")
+ replace("ID_VALUE", "artifactID: $artifactID")
+ elif client_id:
+ replace("ID_TYPE", "$clientID: ID")
+ replace("ID_VALUE", "clientID: $clientID")
+
+ variable_values = {
+ "clientID": client_id,
+ "artifactID": server_id,
+ "artifactPortfolioName": portfolio_name,
+ "entityName": org_entity or entity,
+ "projectName": project,
+ "aliases": [
+ {"alias": alias, "artifactCollectionName": portfolio_name}
+ for alias in aliases
+ ],
+ }
+
+ mutation = gql(template)
+ response = self.gql(mutation, variable_values=variable_values)
+ link_artifact: Dict[str, Any] = response["linkArtifact"]
+ return link_artifact
+
+ def _resolve_org_entity_name(self, entity: str, organization: str = "") -> str:
+ # resolveOrgEntityName fetches the portfolio's org entity's name.
+ #
+ # The organization parameter may be empty, an org's display name, or an org entity name.
+ #
+ # If the server doesn't support fetching the org name of a portfolio, then this returns
+ # the organization parameter, or an error if it is empty. Otherwise, this returns the
+ # fetched value after validating that the given organization, if not empty, matches
+ # either the org's display or entity name.
+
+ if not entity:
+ raise ValueError("Entity name is required to resolve org entity name.")
+
+ org_fields = self.server_organization_type_introspection()
+ can_shorthand_org_entity = "orgEntity" in org_fields
+ if not organization and not can_shorthand_org_entity:
+ raise ValueError(
+ "Fetching Registry artifacts without inputting an organization "
+ "is unavailable for your server version. "
+ "Please upgrade your server to 0.50.0 or later."
+ )
+ if not can_shorthand_org_entity:
+ # Server doesn't support fetching org entity to validate,
+ # assume org entity is correctly inputted
+ return organization
+
+ orgs_from_entity = self._fetch_orgs_and_org_entities_from_entity(entity)
+ if organization:
+ return _match_org_with_fetched_org_entities(organization, orgs_from_entity)
+
+ # If no input organization provided, error if entity belongs to multiple orgs because we
+ # cannot determine which one to use.
+ if len(orgs_from_entity) > 1:
+ raise ValueError(
+ f"Personal entity {entity!r} belongs to multiple organizations "
+ "and cannot be used without specifying the organization name. "
+ "Please specify the organization in the Registry path or use a team entity in the entity settings."
+ )
+ return orgs_from_entity[0].entity_name
+
+ def _fetch_orgs_and_org_entities_from_entity(self, entity: str) -> List[_OrgNames]:
+ """Fetches organization entity names and display names for a given entity.
+
+ Args:
+ entity (str): Entity name to lookup. Can be either a personal or team entity.
+
+ Returns:
+ List[_OrgNames]: List of _OrgNames tuples. (_OrgNames(entity_name, display_name))
+
+ Raises:
+ ValueError: If entity is not found, has no organizations, or other validation errors.
+ """
+ query = gql(
+ """
+ query FetchOrgEntityFromEntity($entityName: String!) {
+ entity(name: $entityName) {
+ organization {
+ name
+ orgEntity {
+ name
+ }
+ }
+ user {
+ organizations {
+ name
+ orgEntity {
+ name
+ }
+ }
+ }
+ }
+ }
+ """
+ )
+ response = self.gql(
+ query,
+ variable_values={
+ "entityName": entity,
+ },
+ )
+
+ # Parse organization from response
+ entity_resp = response["entity"]["organization"]
+ user_resp = response["entity"]["user"]
+ # Check for organization under team/org entity type
+ if entity_resp:
+ org_name = entity_resp.get("name")
+ org_entity_name = entity_resp.get("orgEntity") and entity_resp[
+ "orgEntity"
+ ].get("name")
+ if not org_name or not org_entity_name:
+ raise ValueError(
+ f"Unable to find an organization under entity {entity!r}."
+ )
+ return [_OrgNames(entity_name=org_entity_name, display_name=org_name)]
+ # Check for organization under personal entity type, where a user can belong to multiple orgs
+ elif user_resp:
+ orgs = user_resp.get("organizations", [])
+ org_entities_return = [
+ _OrgNames(
+ entity_name=org["orgEntity"]["name"], display_name=org["name"]
+ )
+ for org in orgs
+ if org.get("orgEntity") and org.get("name")
+ ]
+ if not org_entities_return:
+ raise ValueError(
+ f"Unable to resolve an organization associated with personal entity: {entity!r}. "
+ "This could be because its a personal entity that doesn't belong to any organizations. "
+ "Please specify the organization in the Registry path or use a team entity in the entity settings."
+ )
+ return org_entities_return
+ else:
+ raise ValueError(f"Unable to find an organization under entity {entity!r}.")
+
+ def _construct_use_artifact_query(
+ self,
+ artifact_id: str,
+ entity_name: Optional[str] = None,
+ project_name: Optional[str] = None,
+ run_name: Optional[str] = None,
+ use_as: Optional[str] = None,
+ artifact_entity_name: Optional[str] = None,
+ artifact_project_name: Optional[str] = None,
+ ) -> Tuple[Document, Dict[str, Any]]:
+ query_vars = [
+ "$entityName: String!",
+ "$projectName: String!",
+ "$runName: String!",
+ "$artifactID: ID!",
+ ]
+ query_args = [
+ "entityName: $entityName",
+ "projectName: $projectName",
+ "runName: $runName",
+ "artifactID: $artifactID",
+ ]
+
+ artifact_types = self.server_use_artifact_input_introspection()
+ if "usedAs" in artifact_types and use_as:
+ query_vars.append("$usedAs: String")
+ query_args.append("usedAs: $usedAs")
+
+ entity_name = entity_name or self.settings("entity")
+ project_name = project_name or self.settings("project")
+ run_name = run_name or self.current_run_id
+
+ variable_values: Dict[str, Any] = {
+ "entityName": entity_name,
+ "projectName": project_name,
+ "runName": run_name,
+ "artifactID": artifact_id,
+ "usedAs": use_as,
+ }
+
+ server_allows_entity_project_information = self._server_supports(
+ ServerFeature.USE_ARTIFACT_WITH_ENTITY_AND_PROJECT_INFORMATION
+ )
+ if server_allows_entity_project_information:
+ query_vars.extend(
+ [
+ "$artifactEntityName: String",
+ "$artifactProjectName: String",
+ ]
+ )
+ query_args.extend(
+ [
+ "artifactEntityName: $artifactEntityName",
+ "artifactProjectName: $artifactProjectName",
+ ]
+ )
+ variable_values["artifactEntityName"] = artifact_entity_name
+ variable_values["artifactProjectName"] = artifact_project_name
+
+ vars_str = ", ".join(query_vars)
+ args_str = ", ".join(query_args)
+
+ query = gql(
+ f"""
+ mutation UseArtifact({vars_str}) {{
+ useArtifact(input: {{{args_str}}}) {{
+ artifact {{
+ id
+ digest
+ description
+ state
+ createdAt
+ metadata
+ }}
+ }}
+ }}
+ """
+ )
+ return query, variable_values
+
+ def use_artifact(
+ self,
+ artifact_id: str,
+ entity_name: Optional[str] = None,
+ project_name: Optional[str] = None,
+ run_name: Optional[str] = None,
+ artifact_entity_name: Optional[str] = None,
+ artifact_project_name: Optional[str] = None,
+ use_as: Optional[str] = None,
+ ) -> Optional[Dict[str, Any]]:
+ query, variable_values = self._construct_use_artifact_query(
+ artifact_id,
+ entity_name,
+ project_name,
+ run_name,
+ use_as,
+ artifact_entity_name,
+ artifact_project_name,
+ )
+ response = self.gql(query, variable_values)
+
+ if response["useArtifact"]["artifact"]:
+ artifact: Dict[str, Any] = response["useArtifact"]["artifact"]
+ return artifact
+ return None
+
+ # Fetch fields available in backend of Organization type
+ def server_organization_type_introspection(self) -> List[str]:
+ query_string = """
+ query ProbeServerOrganization {
+ OrganizationInfoType: __type(name:"Organization") {
+ fields {
+ name
+ }
+ }
+ }
+ """
+
+ if self.server_organization_type_fields_info is None:
+ query = gql(query_string)
+ res = self.gql(query)
+ input_fields = res.get("OrganizationInfoType", {}).get("fields", [{}])
+ self.server_organization_type_fields_info = [
+ field["name"] for field in input_fields if "name" in field
+ ]
+
+ return self.server_organization_type_fields_info
+
+ # Fetch input arguments for the "artifact" endpoint on the "Project" type
+ def server_project_type_introspection(self) -> bool:
+ if self.server_supports_enabling_artifact_usage_tracking is not None:
+ return self.server_supports_enabling_artifact_usage_tracking
+
+ query_string = """
+ query ProbeServerProjectInfo {
+ ProjectInfoType: __type(name:"Project") {
+ fields {
+ name
+ args {
+ name
+ }
+ }
+ }
+ }
+ """
+
+ query = gql(query_string)
+ res = self.gql(query)
+ input_fields = res.get("ProjectInfoType", {}).get("fields", [{}])
+ artifact_args: List[Dict[str, str]] = next(
+ (
+ field.get("args", [])
+ for field in input_fields
+ if field.get("name") == "artifact"
+ ),
+ [],
+ )
+ self.server_supports_enabling_artifact_usage_tracking = any(
+ arg.get("name") == "enableTracking" for arg in artifact_args
+ )
+
+ return self.server_supports_enabling_artifact_usage_tracking
+
+ def create_artifact_type(
+ self,
+ artifact_type_name: str,
+ entity_name: Optional[str] = None,
+ project_name: Optional[str] = None,
+ description: Optional[str] = None,
+ ) -> Optional[str]:
+ mutation = gql(
+ """
+ mutation CreateArtifactType(
+ $entityName: String!,
+ $projectName: String!,
+ $artifactTypeName: String!,
+ $description: String
+ ) {
+ createArtifactType(input: {
+ entityName: $entityName,
+ projectName: $projectName,
+ name: $artifactTypeName,
+ description: $description
+ }) {
+ artifactType {
+ id
+ }
+ }
+ }
+ """
+ )
+ entity_name = entity_name or self.settings("entity")
+ project_name = project_name or self.settings("project")
+ response = self.gql(
+ mutation,
+ variable_values={
+ "entityName": entity_name,
+ "projectName": project_name,
+ "artifactTypeName": artifact_type_name,
+ "description": description,
+ },
+ )
+ _id: Optional[str] = response["createArtifactType"]["artifactType"]["id"]
+ return _id
+
+ def server_artifact_introspection(self) -> List[str]:
+ query_string = """
+ query ProbeServerArtifact {
+ ArtifactInfoType: __type(name:"Artifact") {
+ fields {
+ name
+ }
+ }
+ }
+ """
+
+ if self.server_artifact_fields_info is None:
+ query = gql(query_string)
+ res = self.gql(query)
+ input_fields = res.get("ArtifactInfoType", {}).get("fields", [{}])
+ self.server_artifact_fields_info = [
+ field["name"] for field in input_fields if "name" in field
+ ]
+
+ return self.server_artifact_fields_info
+
+ def server_create_artifact_introspection(self) -> List[str]:
+ query_string = """
+ query ProbeServerCreateArtifactInput {
+ CreateArtifactInputInfoType: __type(name:"CreateArtifactInput") {
+ inputFields{
+ name
+ }
+ }
+ }
+ """
+
+ if self.server_create_artifact_input_info is None:
+ query = gql(query_string)
+ res = self.gql(query)
+ input_fields = res.get("CreateArtifactInputInfoType", {}).get(
+ "inputFields", [{}]
+ )
+ self.server_create_artifact_input_info = [
+ field["name"] for field in input_fields if "name" in field
+ ]
+
+ return self.server_create_artifact_input_info
+
+ def _get_create_artifact_mutation(
+ self,
+ fields: List,
+ history_step: Optional[int],
+ distributed_id: Optional[str],
+ ) -> str:
+ types = ""
+ values = ""
+
+ if "historyStep" in fields and history_step not in [0, None]:
+ types += "$historyStep: Int64!,"
+ values += "historyStep: $historyStep,"
+
+ if distributed_id:
+ types += "$distributedID: String,"
+ values += "distributedID: $distributedID,"
+
+ if "clientID" in fields:
+ types += "$clientID: ID,"
+ values += "clientID: $clientID,"
+
+ if "sequenceClientID" in fields:
+ types += "$sequenceClientID: ID,"
+ values += "sequenceClientID: $sequenceClientID,"
+
+ if "enableDigestDeduplication" in fields:
+ values += "enableDigestDeduplication: true,"
+
+ if "ttlDurationSeconds" in fields:
+ types += "$ttlDurationSeconds: Int64,"
+ values += "ttlDurationSeconds: $ttlDurationSeconds,"
+
+ if "tags" in fields:
+ types += "$tags: [TagInput!],"
+ values += "tags: $tags,"
+
+ query_template = """
+ mutation CreateArtifact(
+ $artifactTypeName: String!,
+ $artifactCollectionNames: [String!],
+ $entityName: String!,
+ $projectName: String!,
+ $runName: String,
+ $description: String,
+ $digest: String!,
+ $aliases: [ArtifactAliasInput!],
+ $metadata: JSONString,
+ _CREATE_ARTIFACT_ADDITIONAL_TYPE_
+ ) {
+ createArtifact(input: {
+ artifactTypeName: $artifactTypeName,
+ artifactCollectionNames: $artifactCollectionNames,
+ entityName: $entityName,
+ projectName: $projectName,
+ runName: $runName,
+ description: $description,
+ digest: $digest,
+ digestAlgorithm: MANIFEST_MD5,
+ aliases: $aliases,
+ metadata: $metadata,
+ _CREATE_ARTIFACT_ADDITIONAL_VALUE_
+ }) {
+ artifact {
+ id
+ state
+ artifactSequence {
+ id
+ latestArtifact {
+ id
+ versionIndex
+ }
+ }
+ }
+ }
+ }
+ """
+
+ return query_template.replace(
+ "_CREATE_ARTIFACT_ADDITIONAL_TYPE_", types
+ ).replace("_CREATE_ARTIFACT_ADDITIONAL_VALUE_", values)
+
+ def create_artifact(
+ self,
+ artifact_type_name: str,
+ artifact_collection_name: str,
+ digest: str,
+ client_id: Optional[str] = None,
+ sequence_client_id: Optional[str] = None,
+ entity_name: Optional[str] = None,
+ project_name: Optional[str] = None,
+ run_name: Optional[str] = None,
+ description: Optional[str] = None,
+ metadata: Optional[Dict] = None,
+ ttl_duration_seconds: Optional[int] = None,
+ aliases: Optional[List[Dict[str, str]]] = None,
+ tags: Optional[List[Dict[str, str]]] = None,
+ distributed_id: Optional[str] = None,
+ is_user_created: Optional[bool] = False,
+ history_step: Optional[int] = None,
+ ) -> Tuple[Dict, Dict]:
+ fields = self.server_create_artifact_introspection()
+ artifact_fields = self.server_artifact_introspection()
+ if ("ttlIsInherited" not in artifact_fields) and ttl_duration_seconds:
+ wandb.termwarn(
+ "Server not compatible with setting Artifact TTLs, please upgrade the server to use Artifact TTL"
+ )
+ # ttlDurationSeconds is only usable if ttlIsInherited is also present
+ ttl_duration_seconds = None
+ if ("tags" not in artifact_fields) and tags:
+ wandb.termwarn(
+ "Server not compatible with Artifact tags. "
+ "To use Artifact tags, please upgrade the server to v0.85 or higher."
+ )
+
+ query_template = self._get_create_artifact_mutation(
+ fields, history_step, distributed_id
+ )
+
+ entity_name = entity_name or self.settings("entity")
+ project_name = project_name or self.settings("project")
+ if not is_user_created:
+ run_name = run_name or self.current_run_id
+
+ mutation = gql(query_template)
+ response = self.gql(
+ mutation,
+ variable_values={
+ "entityName": entity_name,
+ "projectName": project_name,
+ "runName": run_name,
+ "artifactTypeName": artifact_type_name,
+ "artifactCollectionNames": [artifact_collection_name],
+ "clientID": client_id,
+ "sequenceClientID": sequence_client_id,
+ "digest": digest,
+ "description": description,
+ "aliases": list(aliases or []),
+ "tags": list(tags or []),
+ "metadata": json.dumps(util.make_safe_for_json(metadata))
+ if metadata
+ else None,
+ "ttlDurationSeconds": ttl_duration_seconds,
+ "distributedID": distributed_id,
+ "historyStep": history_step,
+ },
+ )
+ av = response["createArtifact"]["artifact"]
+ latest = response["createArtifact"]["artifact"]["artifactSequence"].get(
+ "latestArtifact"
+ )
+ return av, latest
+
+ def commit_artifact(self, artifact_id: str) -> "_Response":
+ mutation = gql(
+ """
+ mutation CommitArtifact(
+ $artifactID: ID!,
+ ) {
+ commitArtifact(input: {
+ artifactID: $artifactID,
+ }) {
+ artifact {
+ id
+ digest
+ }
+ }
+ }
+ """
+ )
+
+ response: _Response = self.gql(
+ mutation,
+ variable_values={"artifactID": artifact_id},
+ timeout=60,
+ )
+ return response
+
+ def complete_multipart_upload_artifact(
+ self,
+ artifact_id: str,
+ storage_path: str,
+ completed_parts: List[Dict[str, Any]],
+ upload_id: Optional[str],
+ complete_multipart_action: str = "Complete",
+ ) -> Optional[str]:
+ mutation = gql(
+ """
+ mutation CompleteMultipartUploadArtifact(
+ $completeMultipartAction: CompleteMultipartAction!,
+ $completedParts: [UploadPartsInput!]!,
+ $artifactID: ID!
+ $storagePath: String!
+ $uploadID: String!
+ ) {
+ completeMultipartUploadArtifact(
+ input: {
+ completeMultipartAction: $completeMultipartAction,
+ completedParts: $completedParts,
+ artifactID: $artifactID,
+ storagePath: $storagePath
+ uploadID: $uploadID
+ }
+ ) {
+ digest
+ }
+ }
+ """
+ )
+ response = self.gql(
+ mutation,
+ variable_values={
+ "completeMultipartAction": complete_multipart_action,
+ "artifactID": artifact_id,
+ "storagePath": storage_path,
+ "completedParts": completed_parts,
+ "uploadID": upload_id,
+ },
+ )
+ digest: Optional[str] = response["completeMultipartUploadArtifact"]["digest"]
+ return digest
+
+ def create_artifact_manifest(
+ self,
+ name: str,
+ digest: str,
+ artifact_id: Optional[str],
+ base_artifact_id: Optional[str] = None,
+ entity: Optional[str] = None,
+ project: Optional[str] = None,
+ run: Optional[str] = None,
+ include_upload: bool = True,
+ type: str = "FULL",
+ ) -> Tuple[str, Dict[str, Any]]:
+ mutation = gql(
+ """
+ mutation CreateArtifactManifest(
+ $name: String!,
+ $digest: String!,
+ $artifactID: ID!,
+ $baseArtifactID: ID,
+ $entityName: String!,
+ $projectName: String!,
+ $runName: String!,
+ $includeUpload: Boolean!,
+ {}
+ ) {{
+ createArtifactManifest(input: {{
+ name: $name,
+ digest: $digest,
+ artifactID: $artifactID,
+ baseArtifactID: $baseArtifactID,
+ entityName: $entityName,
+ projectName: $projectName,
+ runName: $runName,
+ {}
+ }}) {{
+ artifactManifest {{
+ id
+ file {{
+ id
+ name
+ displayName
+ uploadUrl @include(if: $includeUpload)
+ uploadHeaders @include(if: $includeUpload)
+ }}
+ }}
+ }}
+ }}
+ """.format(
+ "$type: ArtifactManifestType = FULL" if type != "FULL" else "",
+ "type: $type" if type != "FULL" else "",
+ )
+ )
+
+ entity_name = entity or self.settings("entity")
+ project_name = project or self.settings("project")
+ run_name = run or self.current_run_id
+
+ response = self.gql(
+ mutation,
+ variable_values={
+ "name": name,
+ "digest": digest,
+ "artifactID": artifact_id,
+ "baseArtifactID": base_artifact_id,
+ "entityName": entity_name,
+ "projectName": project_name,
+ "runName": run_name,
+ "includeUpload": include_upload,
+ "type": type,
+ },
+ )
+ return (
+ response["createArtifactManifest"]["artifactManifest"]["id"],
+ response["createArtifactManifest"]["artifactManifest"]["file"],
+ )
+
+ def update_artifact_manifest(
+ self,
+ artifact_manifest_id: str,
+ base_artifact_id: Optional[str] = None,
+ digest: Optional[str] = None,
+ include_upload: Optional[bool] = True,
+ ) -> Tuple[str, Dict[str, Any]]:
+ mutation = gql(
+ """
+ mutation UpdateArtifactManifest(
+ $artifactManifestID: ID!,
+ $digest: String,
+ $baseArtifactID: ID,
+ $includeUpload: Boolean!,
+ ) {
+ updateArtifactManifest(input: {
+ artifactManifestID: $artifactManifestID,
+ digest: $digest,
+ baseArtifactID: $baseArtifactID,
+ }) {
+ artifactManifest {
+ id
+ file {
+ id
+ name
+ displayName
+ uploadUrl @include(if: $includeUpload)
+ uploadHeaders @include(if: $includeUpload)
+ }
+ }
+ }
+ }
+ """
+ )
+
+ response = self.gql(
+ mutation,
+ variable_values={
+ "artifactManifestID": artifact_manifest_id,
+ "digest": digest,
+ "baseArtifactID": base_artifact_id,
+ "includeUpload": include_upload,
+ },
+ )
+
+ return (
+ response["updateArtifactManifest"]["artifactManifest"]["id"],
+ response["updateArtifactManifest"]["artifactManifest"]["file"],
+ )
+
+ def update_artifact_metadata(
+ self, artifact_id: str, metadata: Dict[str, Any]
+ ) -> Dict[str, Any]:
+ """Set the metadata of the given artifact version."""
+ mutation = gql(
+ """
+ mutation UpdateArtifact(
+ $artifactID: ID!,
+ $metadata: JSONString,
+ ) {
+ updateArtifact(input: {
+ artifactID: $artifactID,
+ metadata: $metadata,
+ }) {
+ artifact {
+ id
+ }
+ }
+ }
+ """
+ )
+ response = self.gql(
+ mutation,
+ variable_values={
+ "artifactID": artifact_id,
+ "metadata": json.dumps(metadata),
+ },
+ )
+ return response["updateArtifact"]["artifact"]
+
+ def _resolve_client_id(
+ self,
+ client_id: str,
+ ) -> Optional[str]:
+ if client_id in self._client_id_mapping:
+ return self._client_id_mapping[client_id]
+
+ query = gql(
+ """
+ query ClientIDMapping($clientID: ID!) {
+ clientIDMapping(clientID: $clientID) {
+ serverID
+ }
+ }
+ """
+ )
+ response = self.gql(
+ query,
+ variable_values={
+ "clientID": client_id,
+ },
+ )
+ server_id = None
+ if response is not None:
+ client_id_mapping = response.get("clientIDMapping")
+ if client_id_mapping is not None:
+ server_id = client_id_mapping.get("serverID")
+ if server_id is not None:
+ self._client_id_mapping[client_id] = server_id
+ return server_id
+
+ def server_create_artifact_file_spec_input_introspection(self) -> List:
+ query_string = """
+ query ProbeServerCreateArtifactFileSpecInput {
+ CreateArtifactFileSpecInputInfoType: __type(name:"CreateArtifactFileSpecInput") {
+ inputFields{
+ name
+ }
+ }
+ }
+ """
+
+ query = gql(query_string)
+ res = self.gql(query)
+ create_artifact_file_spec_input_info = [
+ field.get("name", "")
+ for field in res.get("CreateArtifactFileSpecInputInfoType", {}).get(
+ "inputFields", [{}]
+ )
+ ]
+ return create_artifact_file_spec_input_info
+
+ @normalize_exceptions
+ def create_artifact_files(
+ self, artifact_files: Iterable["CreateArtifactFileSpecInput"]
+ ) -> Mapping[str, "CreateArtifactFilesResponseFile"]:
+ query_template = """
+ mutation CreateArtifactFiles(
+ $storageLayout: ArtifactStorageLayout!
+ $artifactFiles: [CreateArtifactFileSpecInput!]!
+ ) {
+ createArtifactFiles(input: {
+ artifactFiles: $artifactFiles,
+ storageLayout: $storageLayout,
+ }) {
+ files {
+ edges {
+ node {
+ id
+ name
+ displayName
+ uploadUrl
+ uploadHeaders
+ _MULTIPART_UPLOAD_FIELDS_
+ artifact {
+ id
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+ multipart_upload_url_query = """
+ storagePath
+ uploadMultipartUrls {
+ uploadID
+ uploadUrlParts {
+ partNumber
+ uploadUrl
+ }
+ }
+ """
+
+ # TODO: we should use constants here from interface/artifacts.py
+ # but probably don't want the dependency. We're going to remove
+ # this setting in a future release, so I'm just hard-coding the strings.
+ storage_layout = "V2"
+ if env.get_use_v1_artifacts():
+ storage_layout = "V1"
+
+ create_artifact_file_spec_input_fields = (
+ self.server_create_artifact_file_spec_input_introspection()
+ )
+ if "uploadPartsInput" in create_artifact_file_spec_input_fields:
+ query_template = query_template.replace(
+ "_MULTIPART_UPLOAD_FIELDS_", multipart_upload_url_query
+ )
+ else:
+ query_template = query_template.replace("_MULTIPART_UPLOAD_FIELDS_", "")
+
+ mutation = gql(query_template)
+ response = self.gql(
+ mutation,
+ variable_values={
+ "storageLayout": storage_layout,
+ "artifactFiles": [af for af in artifact_files],
+ },
+ )
+
+ result = {}
+ for edge in response["createArtifactFiles"]["files"]["edges"]:
+ node = edge["node"]
+ result[node["displayName"]] = node
+ return result
+
+ @normalize_exceptions
+ def notify_scriptable_run_alert(
+ self,
+ title: str,
+ text: str,
+ level: Optional[str] = None,
+ wait_duration: Optional["Number"] = None,
+ ) -> bool:
+ mutation = gql(
+ """
+ mutation NotifyScriptableRunAlert(
+ $entityName: String!,
+ $projectName: String!,
+ $runName: String!,
+ $title: String!,
+ $text: String!,
+ $severity: AlertSeverity = INFO,
+ $waitDuration: Duration
+ ) {
+ notifyScriptableRunAlert(input: {
+ entityName: $entityName,
+ projectName: $projectName,
+ runName: $runName,
+ title: $title,
+ text: $text,
+ severity: $severity,
+ waitDuration: $waitDuration
+ }) {
+ success
+ }
+ }
+ """
+ )
+
+ response = self.gql(
+ mutation,
+ variable_values={
+ "entityName": self.settings("entity"),
+ "projectName": self.settings("project"),
+ "runName": self.current_run_id,
+ "title": title,
+ "text": text,
+ "severity": level,
+ "waitDuration": wait_duration,
+ },
+ )
+ success: bool = response["notifyScriptableRunAlert"]["success"]
+ return success
+
+ def get_sweep_state(
+ self, sweep: str, entity: Optional[str] = None, project: Optional[str] = None
+ ) -> "SweepState":
+ state: SweepState = self.sweep(
+ sweep=sweep, entity=entity, project=project, specs="{}"
+ )["state"]
+ return state
+
+ def set_sweep_state(
+ self,
+ sweep: str,
+ state: "SweepState",
+ entity: Optional[str] = None,
+ project: Optional[str] = None,
+ ) -> None:
+ assert state in ("RUNNING", "PAUSED", "CANCELED", "FINISHED")
+ s = self.sweep(sweep=sweep, entity=entity, project=project, specs="{}")
+ curr_state = s["state"].upper()
+ if state == "PAUSED" and curr_state not in ("PAUSED", "RUNNING"):
+ raise Exception(f"Cannot pause {curr_state.lower()} sweep.")
+ elif state != "RUNNING" and curr_state not in ("RUNNING", "PAUSED", "PENDING"):
+ raise Exception(f"Sweep already {curr_state.lower()}.")
+ sweep_id = s["id"]
+ mutation = gql(
+ """
+ mutation UpsertSweep(
+ $id: ID,
+ $state: String,
+ $entityName: String,
+ $projectName: String
+ ) {
+ upsertSweep(input: {
+ id: $id,
+ state: $state,
+ entityName: $entityName,
+ projectName: $projectName
+ }){
+ sweep {
+ name
+ }
+ }
+ }
+ """
+ )
+ self.gql(
+ mutation,
+ variable_values={
+ "id": sweep_id,
+ "state": state,
+ "entityName": entity or self.settings("entity"),
+ "projectName": project or self.settings("project"),
+ },
+ )
+
+ def stop_sweep(
+ self,
+ sweep: str,
+ entity: Optional[str] = None,
+ project: Optional[str] = None,
+ ) -> None:
+ """Finish the sweep to stop running new runs and let currently running runs finish."""
+ self.set_sweep_state(
+ sweep=sweep, state="FINISHED", entity=entity, project=project
+ )
+
+ def cancel_sweep(
+ self,
+ sweep: str,
+ entity: Optional[str] = None,
+ project: Optional[str] = None,
+ ) -> None:
+ """Cancel the sweep to kill all running runs and stop running new runs."""
+ self.set_sweep_state(
+ sweep=sweep, state="CANCELED", entity=entity, project=project
+ )
+
+ def pause_sweep(
+ self,
+ sweep: str,
+ entity: Optional[str] = None,
+ project: Optional[str] = None,
+ ) -> None:
+ """Pause the sweep to temporarily stop running new runs."""
+ self.set_sweep_state(
+ sweep=sweep, state="PAUSED", entity=entity, project=project
+ )
+
+ def resume_sweep(
+ self,
+ sweep: str,
+ entity: Optional[str] = None,
+ project: Optional[str] = None,
+ ) -> None:
+ """Resume the sweep to continue running new runs."""
+ self.set_sweep_state(
+ sweep=sweep, state="RUNNING", entity=entity, project=project
+ )
+
+ def _status_request(self, url: str, length: int) -> requests.Response:
+ """Ask google how much we've uploaded."""
+ check_httpclient_logger_handler()
+ return requests.put(
+ url=url,
+ headers={"Content-Length": "0", "Content-Range": f"bytes */{length}"},
+ )
+
+ def _flatten_edges(self, response: "_Response") -> List[Dict]:
+ """Return an array from the nested graphql relay structure."""
+ return [node["node"] for node in response["edges"]]
+
+ @normalize_exceptions
+ def stop_run(
+ self,
+ run_id: str,
+ ) -> bool:
+ mutation = gql(
+ """
+ mutation stopRun($id: ID!) {
+ stopRun(input: {
+ id: $id
+ }) {
+ clientMutationId
+ success
+ }
+ }
+ """
+ )
+
+ response = self.gql(
+ mutation,
+ variable_values={
+ "id": run_id,
+ },
+ )
+
+ success: bool = response["stopRun"].get("success")
+
+ return success
+
+ @normalize_exceptions
+ def create_custom_chart(
+ self,
+ entity: str,
+ name: str,
+ display_name: str,
+ spec_type: str,
+ access: str,
+ spec: Union[str, Mapping[str, Any]],
+ ) -> Optional[Dict[str, Any]]:
+ if not isinstance(spec, str):
+ spec = json.dumps(spec)
+
+ mutation = gql(
+ """
+ mutation CreateCustomChart(
+ $entity: String!
+ $name: String!
+ $displayName: String!
+ $type: String!
+ $access: String!
+ $spec: JSONString!
+ ) {
+ createCustomChart(
+ input: {
+ entity: $entity
+ name: $name
+ displayName: $displayName
+ type: $type
+ access: $access
+ spec: $spec
+ }
+ ) {
+ chart { id }
+ }
+ }
+ """
+ )
+
+ variable_values = {
+ "entity": entity,
+ "name": name,
+ "displayName": display_name,
+ "type": spec_type,
+ "access": access,
+ "spec": spec,
+ }
+
+ result: Optional[Dict[str, Any]] = self.gql(mutation, variable_values)[
+ "createCustomChart"
+ ]
+ return result
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/job_builder.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/job_builder.py
new file mode 100644
index 0000000000000000000000000000000000000000..778e27c39d9372ea81b50592d584fe3b7a6b4579
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/job_builder.py
@@ -0,0 +1,656 @@
+"""job builder."""
+
+import json
+import logging
+import os
+import re
+import sys
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Dict,
+ List,
+ Literal,
+ Optional,
+ Tuple,
+ TypedDict,
+ Union,
+)
+
+import wandb
+from wandb.sdk.artifacts._internal_artifact import InternalArtifact
+from wandb.sdk.artifacts.artifact import Artifact
+from wandb.sdk.data_types._dtypes import TypeRegistry
+from wandb.sdk.internal.internal_api import Api
+from wandb.sdk.lib.filenames import DIFF_FNAME, METADATA_FNAME, REQUIREMENTS_FNAME
+from wandb.util import make_artifact_name_safe
+
+from .settings_static import SettingsStatic
+
+_logger = logging.getLogger(__name__)
+
+if TYPE_CHECKING:
+ from wandb.proto.wandb_internal_pb2 import ArtifactRecord
+
+FROZEN_REQUIREMENTS_FNAME = "requirements.frozen.txt"
+JOB_FNAME = "wandb-job.json"
+JOB_ARTIFACT_TYPE = "job"
+
+LOG_LEVEL = Literal["log", "warn", "error"]
+
+
+class Version:
+ def __init__(self, major: int, minor: int, patch: int):
+ self._major = major
+ self._minor = minor
+ self._patch = patch
+
+ def __repr__(self) -> str:
+ return f"{self._major}.{self._minor}.{self._patch}"
+
+ def __lt__(self, other: "Version") -> bool:
+ if self._major < other._major:
+ return True
+ elif self._major == other._major:
+ if self._minor < other._minor:
+ return True
+ elif self._minor == other._minor:
+ if self._patch < other._patch:
+ return True
+ return False
+
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, Version):
+ return NotImplemented
+ return (
+ self._major == other._major
+ and self._minor == other._minor
+ and self._patch == other._patch
+ )
+
+
+# Minimum supported wandb version for keys in the source dict of wandb-job.json
+SOURCE_KEYS_MIN_SUPPORTED_VERSION = {
+ "dockerfile": Version(0, 17, 0),
+ "build_context": Version(0, 17, 0),
+}
+
+
+class GitInfo(TypedDict):
+ remote: str
+ commit: str
+
+
+class GitSourceDict(TypedDict):
+ git: GitInfo
+ entrypoint: List[str]
+ notebook: bool
+ build_context: Optional[str]
+ dockerfile: Optional[str]
+
+
+class ArtifactSourceDict(TypedDict):
+ artifact: str
+ entrypoint: List[str]
+ notebook: bool
+ build_context: Optional[str]
+ dockerfile: Optional[str]
+
+
+class ImageSourceDict(TypedDict):
+ image: str
+
+
+class JobSourceDict(TypedDict, total=False):
+ _version: str
+ source_type: str
+ source: Union[GitSourceDict, ArtifactSourceDict, ImageSourceDict]
+ input_types: Dict[str, Any]
+ output_types: Dict[str, Any]
+ runtime: Optional[str]
+ services: Dict[str, str]
+
+
+class ArtifactInfoForJob(TypedDict):
+ id: str
+ name: str
+
+
+def get_min_supported_for_source_dict(
+ source: Union[GitSourceDict, ArtifactSourceDict, ImageSourceDict],
+) -> Optional[Version]:
+ """Get the minimum supported wandb version the source dict of wandb-job.json."""
+ min_seen = None
+ for key in source:
+ new_ver = SOURCE_KEYS_MIN_SUPPORTED_VERSION.get(key)
+ if new_ver:
+ if min_seen is None or new_ver < min_seen:
+ min_seen = new_ver
+ return min_seen
+
+
+class JobBuilder:
+ _settings: SettingsStatic
+ _files_dir: str
+ _metadatafile_path: Optional[str]
+ _requirements_path: Optional[str]
+ _config: Optional[Dict[str, Any]]
+ _summary: Optional[Dict[str, Any]]
+ _logged_code_artifact: Optional[ArtifactInfoForJob]
+ _disable: bool
+ _partial_source_id: Optional[str] # Partial job source artifact id.
+ _aliases: List[str]
+ _job_seq_id: Optional[str]
+ _job_version_alias: Optional[str]
+ _is_notebook_run: bool
+ _verbose: bool
+ _services: Dict[str, str]
+
+ def __init__(
+ self,
+ settings: SettingsStatic,
+ verbose: bool = False,
+ *,
+ files_dir: str,
+ ):
+ """Instantiate a JobBuilder.
+
+ Args:
+ settings: Parameters for the job builder.
+ In a run, this is the run's settings.
+ Otherwise, this is a set of undocumented parameters,
+ all of which should be made explicit like files_dir.
+ files_dir: The directory where to write files.
+ In a run, this should be the run's files directory.
+ """
+ self._settings = settings
+ self._files_dir = files_dir
+
+ self._metadatafile_path = None
+ self._requirements_path = None
+ self._config = None
+ self._summary = None
+ self._logged_code_artifact = None
+ self._job_seq_id = None
+ self._job_version_alias = None
+ self._disable = settings.disable_job_creation or settings.x_disable_machine_info
+ self._partial_source_id = None
+ self._aliases = []
+ self._source_type: Optional[Literal["repo", "artifact", "image"]] = (
+ settings.job_source # type: ignore[assignment]
+ )
+ self._is_notebook_run = self._get_is_notebook_run()
+ self._verbose = verbose
+ self._partial = False
+ self._services = {}
+
+ def set_config(self, config: Dict[str, Any]) -> None:
+ self._config = config
+
+ def set_summary(self, summary: Dict[str, Any]) -> None:
+ self._summary = summary
+
+ @property
+ def disable(self) -> bool:
+ return self._disable
+
+ @disable.setter
+ def disable(self, val: bool) -> None:
+ self._disable = val
+
+ @property
+ def input_types(self) -> Dict[str, Any]:
+ return TypeRegistry.type_of(self._config).to_json()
+
+ @property
+ def output_types(self) -> Dict[str, Any]:
+ return TypeRegistry.type_of(self._summary).to_json()
+
+ def set_partial_source_id(self, source_id: str) -> None:
+ self._partial_source_id = source_id
+
+ def _handle_server_artifact(
+ self, res: Optional[Dict], artifact: "ArtifactRecord"
+ ) -> None:
+ if artifact.type == "job" and res is not None:
+ try:
+ if res["artifactSequence"]["latestArtifact"] is None:
+ self._job_version_alias = "v0"
+ elif res["artifactSequence"]["latestArtifact"]["id"] == res["id"]:
+ self._job_version_alias = (
+ f"v{res['artifactSequence']['latestArtifact']['versionIndex']}"
+ )
+ else:
+ self._job_version_alias = f"v{res['artifactSequence']['latestArtifact']['versionIndex'] + 1}"
+ self._job_seq_id = res["artifactSequence"]["id"]
+ except KeyError as e:
+ _logger.info(f"Malformed response from ArtifactSaver.save {e}")
+ if artifact.type == "code" and res is not None:
+ self._logged_code_artifact = ArtifactInfoForJob(
+ {
+ "id": res["id"],
+ "name": artifact.name,
+ }
+ )
+
+ def _build_repo_job_source(
+ self,
+ program_relpath: str,
+ metadata: Dict[str, Any],
+ ) -> Tuple[Optional[GitSourceDict], Optional[str]]:
+ git_info: Dict[str, str] = metadata.get("git", {})
+ remote = git_info.get("remote")
+ commit = git_info.get("commit")
+ root = metadata.get("root")
+ assert remote is not None
+ assert commit is not None
+ if self._is_notebook_run:
+ if not os.path.exists(
+ os.path.join(os.getcwd(), os.path.basename(program_relpath))
+ ):
+ return None, None
+
+ if root is None or self._settings.x_jupyter_root is None:
+ _logger.info("target path does not exist, exiting")
+ return None, None
+ assert self._settings.x_jupyter_root is not None
+ # git notebooks set the root to the git root,
+ # jupyter_root contains the path where the jupyter notebook was started
+ # program_relpath contains the path from jupyter_root to the file
+ # full program path here is actually the relpath from the program to the git root
+ full_program_path = os.path.join(
+ os.path.relpath(str(self._settings.x_jupyter_root), root),
+ program_relpath,
+ )
+ full_program_path = os.path.normpath(full_program_path)
+ # if the notebook server is started above the git repo need to clear all the ..s
+ if full_program_path.startswith(".."):
+ split_path = full_program_path.split("/")
+ count_dots = 0
+ for p in split_path:
+ if p == "..":
+ count_dots += 1
+ full_program_path = "/".join(split_path[2 * count_dots :])
+ else:
+ full_program_path = program_relpath
+
+ entrypoint = self._get_entrypoint(full_program_path, metadata)
+ # TODO: update executable to a method that supports pex
+ source: GitSourceDict = {
+ "git": {"remote": remote, "commit": commit},
+ "entrypoint": entrypoint,
+ "notebook": self._is_notebook_run,
+ "build_context": metadata.get("build_context"),
+ "dockerfile": metadata.get("dockerfile"),
+ }
+ name = self._make_job_name(f"{remote}_{program_relpath}")
+
+ return source, name
+
+ def _log_if_verbose(self, message: str, level: LOG_LEVEL) -> None:
+ log_func: Optional[Union[Callable[[Any], None], Callable[[Any], None]]] = None
+ if level == "log":
+ _logger.info(message)
+ log_func = wandb.termlog
+ elif level == "warn":
+ _logger.warning(message)
+ log_func = wandb.termwarn
+ elif level == "error":
+ _logger.error(message)
+ log_func = wandb.termerror
+
+ if self._verbose and log_func is not None:
+ log_func(message)
+
+ def _build_artifact_job_source(
+ self,
+ program_relpath: str,
+ metadata: Dict[str, Any],
+ ) -> Tuple[Optional[ArtifactSourceDict], Optional[str]]:
+ assert isinstance(self._logged_code_artifact, dict)
+ # TODO: should we just always exit early if the path doesn't exist?
+ if self._is_notebook_run and not self._is_colab_run():
+ full_program_relpath = os.path.relpath(program_relpath, os.getcwd())
+ # if the resolved path doesn't exist, then we shouldn't make a job because it will fail
+ if not os.path.exists(full_program_relpath):
+ # when users call log code in a notebook the code artifact starts
+ # at the directory the notebook is in instead of the jupyter core
+ if not os.path.exists(os.path.basename(program_relpath)):
+ _logger.info("target path does not exist, exiting")
+ self._log_if_verbose(
+ "No program path found when generating artifact job source for a non-colab notebook run. See https://docs.wandb.ai/guides/launch/create-job",
+ "warn",
+ )
+ return None, None
+ full_program_relpath = os.path.basename(program_relpath)
+ else:
+ full_program_relpath = program_relpath
+
+ entrypoint = self._get_entrypoint(full_program_relpath, metadata)
+ # TODO: update executable to a method that supports pex
+ source: ArtifactSourceDict = {
+ "entrypoint": entrypoint,
+ "notebook": self._is_notebook_run,
+ "artifact": f"wandb-artifact://_id/{self._logged_code_artifact['id']}",
+ "build_context": metadata.get("build_context"),
+ "dockerfile": metadata.get("dockerfile"),
+ }
+ artifact_basename, *_ = self._logged_code_artifact["name"].split(":")
+ name = self._make_job_name(artifact_basename)
+
+ return source, name
+
+ def _build_image_job_source(
+ self, metadata: Dict[str, Any]
+ ) -> Tuple[ImageSourceDict, str]:
+ image_name = metadata.get("docker")
+ assert isinstance(image_name, str)
+
+ raw_image_name = image_name
+ if ":" in image_name:
+ tag = image_name.split(":")[-1]
+
+ # if tag looks properly formatted, assume its a tag
+ # regex: alphanumeric and "_" "-" "."
+ if re.fullmatch(r"([a-zA-Z0-9_\-\.]+)", tag):
+ raw_image_name = raw_image_name.replace(f":{tag}", "")
+ self._aliases += [tag]
+
+ source: ImageSourceDict = {
+ "image": image_name,
+ }
+ name = self._make_job_name(raw_image_name)
+
+ return source, name
+
+ def _make_job_name(self, input_str: str) -> str:
+ """Use job name from settings if provided, else use programmatic name."""
+ if self._settings.job_name:
+ return self._settings.job_name
+
+ return make_artifact_name_safe(f"job-{input_str}")
+
+ def _get_entrypoint(
+ self,
+ program_relpath: str,
+ metadata: Dict[str, Any],
+ ) -> List[str]:
+ # if building a partial job from CLI, overwrite entrypoint and notebook
+ # should already be in metadata from create_job
+ if self._partial:
+ if metadata.get("entrypoint"):
+ entrypoint: List[str] = metadata["entrypoint"]
+ return entrypoint
+ # job is being built from a run
+ entrypoint = [os.path.basename(sys.executable), program_relpath]
+
+ return entrypoint
+
+ def _get_is_notebook_run(self) -> bool:
+ return hasattr(self._settings, "_jupyter") and bool(self._settings._jupyter)
+
+ def _is_colab_run(self) -> bool:
+ return hasattr(self._settings, "_colab") and bool(self._settings._colab)
+
+ def _build_job_source(
+ self,
+ source_type: str,
+ program_relpath: Optional[str],
+ metadata: Dict[str, Any],
+ ) -> Tuple[
+ Union[GitSourceDict, ArtifactSourceDict, ImageSourceDict, None],
+ Optional[str],
+ ]:
+ """Construct a job source dict and name from the current run.
+
+ Args:
+ source_type (str): The type of source to build the job from. One of
+ "repo", "artifact", or "image".
+ """
+ source: Union[
+ GitSourceDict,
+ ArtifactSourceDict,
+ ImageSourceDict,
+ None,
+ ] = None
+
+ if source_type == "repo":
+ source, name = self._build_repo_job_source(
+ program_relpath or "",
+ metadata,
+ )
+ elif source_type == "artifact":
+ source, name = self._build_artifact_job_source(
+ program_relpath or "",
+ metadata,
+ )
+ elif source_type == "image" and self._has_image_job_ingredients(metadata):
+ source, name = self._build_image_job_source(metadata)
+ else:
+ source = None
+
+ if source is None:
+ if source_type:
+ self._log_if_verbose(
+ f"Source type is set to '{source_type}' but some required information is missing "
+ "from the environment. A job will not be created from this run. See "
+ "https://docs.wandb.ai/guides/launch/create-job",
+ "warn",
+ )
+ return None, None
+
+ return source, name
+
+ def build(
+ self,
+ api: Api,
+ build_context: Optional[str] = None,
+ dockerfile: Optional[str] = None,
+ base_image: Optional[str] = None,
+ ) -> Optional[Artifact]:
+ """Build a job artifact from the current run.
+
+ Args:
+ api (Api): The API object to use to create the job artifact.
+ build_context (Optional[str]): Path within the job source code to
+ the image build context. Saved as part of the job for future
+ builds.
+ dockerfile (Optional[str]): Path within the build context the
+ Dockerfile. Saved as part of the job for future builds.
+ base_image (Optional[str]): The base image used to run the job code.
+
+ Returns:
+ Optional[Artifact]: The job artifact if it was successfully built,
+ otherwise None.
+ """
+ _logger.info("Attempting to build job artifact")
+
+ # If a partial job was used, write the input/output types to the metadata
+ # rather than building a new job version.
+ if self._partial_source_id is not None:
+ new_metadata = {
+ "input_types": {"@wandb.config": self.input_types},
+ "output_types": self.output_types,
+ }
+ api.update_artifact_metadata(
+ self._partial_source_id,
+ new_metadata,
+ )
+ return None
+
+ if not os.path.exists(os.path.join(self._files_dir, REQUIREMENTS_FNAME)):
+ self._log_if_verbose(
+ "No requirements.txt found, not creating job artifact. See https://docs.wandb.ai/guides/launch/create-job",
+ "warn",
+ )
+ return None
+ metadata = self._handle_metadata_file()
+ if metadata is None:
+ self._log_if_verbose(
+ f"Ensure read and write access to run files dir: {self._files_dir}, control this via the WANDB_DIR env var. See https://docs.wandb.ai/guides/track/environment-variables",
+ "warn",
+ )
+ return None
+
+ runtime: Optional[str] = metadata.get("python")
+ # can't build a job without a python version
+ if runtime is None:
+ self._log_if_verbose(
+ "No python version found in metadata, not creating job artifact. "
+ "See https://docs.wandb.ai/guides/launch/create-job",
+ "warn",
+ )
+ return None
+
+ input_types = TypeRegistry.type_of(self._config).to_json()
+ output_types = TypeRegistry.type_of(self._summary).to_json()
+
+ name: Optional[str] = None
+ source_info: Optional[JobSourceDict] = None
+
+ # configure job from environment
+ source_type = self._get_source_type(metadata)
+ if not source_type:
+ # if source_type is None, then we don't have enough information to build a job
+ # if the user intended to create a job, warn.
+ if (
+ self._settings.job_name
+ or self._settings.job_source
+ or self._source_type
+ ):
+ self._log_if_verbose(
+ "No source type found, not creating job artifact", "warn"
+ )
+ return None
+
+ program_relpath = self._get_program_relpath(source_type, metadata)
+ if not self._partial and source_type != "image" and not program_relpath:
+ self._log_if_verbose(
+ "No program path found, not creating job artifact. "
+ "See https://docs.wandb.ai/guides/launch/create-job",
+ "warn",
+ )
+ return None
+
+ source, name = self._build_job_source(
+ source_type,
+ program_relpath,
+ metadata,
+ )
+ if source is None:
+ return None
+
+ if build_context:
+ source["build_context"] = build_context # type: ignore[typeddict-item]
+ if dockerfile:
+ source["dockerfile"] = dockerfile # type: ignore[typeddict-item]
+ if base_image:
+ source["base_image"] = base_image # type: ignore[typeddict-item]
+
+ # Pop any keys that are initialized to None. The current TypedDict
+ # system for source dicts requires all keys to be present, but we
+ # don't want to include keys that are None in the final dict.
+ for key in list(source.keys()):
+ if source[key] is None: # type: ignore[literal-required]
+ source.pop(key) # type: ignore[literal-require,misc]
+
+ source_info = {
+ "_version": str(get_min_supported_for_source_dict(source) or "v0"),
+ "source_type": source_type,
+ "source": source,
+ "input_types": input_types,
+ "output_types": output_types,
+ "runtime": runtime,
+ }
+
+ if self._services:
+ source_info["services"] = self._services
+
+ assert source_info is not None
+ assert name is not None
+
+ artifact = InternalArtifact(name, JOB_ARTIFACT_TYPE)
+
+ _logger.info("adding wandb-job metadata file")
+ with artifact.new_file("wandb-job.json") as f:
+ f.write(json.dumps(source_info, indent=4))
+
+ artifact.add_file(
+ os.path.join(self._files_dir, REQUIREMENTS_FNAME),
+ name=FROZEN_REQUIREMENTS_FNAME,
+ )
+
+ if source_type == "repo":
+ # add diff
+ if os.path.exists(os.path.join(self._files_dir, DIFF_FNAME)):
+ artifact.add_file(
+ os.path.join(self._files_dir, DIFF_FNAME),
+ name=DIFF_FNAME,
+ )
+
+ return artifact
+
+ def _get_source_type(self, metadata: Dict[str, Any]) -> Optional[str]:
+ if self._source_type:
+ return self._source_type
+
+ if self._has_git_job_ingredients(metadata):
+ _logger.info("is repo sourced job")
+ return "repo"
+
+ if self._has_artifact_job_ingredients():
+ _logger.info("is artifact sourced job")
+ return "artifact"
+
+ if self._has_image_job_ingredients(metadata):
+ _logger.info("is image sourced job")
+ return "image"
+
+ _logger.info("no source found")
+ return None
+
+ def _get_program_relpath(
+ self, source_type: str, metadata: Dict[str, Any]
+ ) -> Optional[str]:
+ if self._is_notebook_run:
+ _logger.info("run is notebook based run")
+ program = metadata.get("program")
+
+ if not program:
+ self._log_if_verbose(
+ "Notebook 'program' path not found in metadata. See https://docs.wandb.ai/guides/launch/create-job",
+ "warn",
+ )
+
+ return program
+
+ if source_type == "artifact" or self._settings.job_source == "artifact":
+ # if the job is set to be an artifact, use relpath guaranteed
+ # to be correct. 'codePath' uses the root path when in git repo
+ # fallback to codePath if strictly local relpath not present
+ return metadata.get("codePathLocal") or metadata.get("codePath")
+
+ return metadata.get("codePath")
+
+ def _handle_metadata_file(
+ self,
+ ) -> Optional[Dict]:
+ if os.path.exists(os.path.join(self._files_dir, METADATA_FNAME)):
+ with open(os.path.join(self._files_dir, METADATA_FNAME)) as f:
+ metadata: Dict = json.load(f)
+ return metadata
+
+ return None
+
+ def _has_git_job_ingredients(self, metadata: Dict[str, Any]) -> bool:
+ git_info: Dict[str, str] = metadata.get("git", {})
+ if self._is_notebook_run and metadata.get("root") is None:
+ return False
+ return git_info.get("remote") is not None and git_info.get("commit") is not None
+
+ def _has_artifact_job_ingredients(self) -> bool:
+ return self._logged_code_artifact is not None
+
+ def _has_image_job_ingredients(self, metadata: Dict[str, Any]) -> bool:
+ return metadata.get("docker") is not None
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/profiler.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/profiler.py
new file mode 100644
index 0000000000000000000000000000000000000000..9973e42984580a3fca6dc6706728a58ed22d4277
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/profiler.py
@@ -0,0 +1,79 @@
+"""Integration with pytorch profiler."""
+
+import os
+
+import wandb
+from wandb.errors import Error, UsageError
+from wandb.sdk.lib import telemetry
+
+PYTORCH_MODULE = "torch"
+PYTORCH_PROFILER_MODULE = "torch.profiler"
+
+
+def torch_trace_handler():
+ """Create a trace handler for traces generated by the profiler.
+
+ Provide as an argument to `torch.profiler.profile`:
+ ```python
+ torch.profiler.profile(..., on_trace_ready=wandb.profiler.torch_trace_handler())
+ ```
+
+ Calling this function ensures that profiler charts & tables can be viewed in
+ your run dashboard on wandb.ai.
+
+ Please note that `wandb.init()` must be called before this function is
+ invoked, and the reinit setting must not be set to "create_new". The PyTorch
+ (torch) version must also be at least 1.9, in order to ensure stability of
+ their Profiler API.
+
+ Args:
+ None
+
+ Returns:
+ None
+
+ Raises:
+ UsageError if wandb.init() hasn't been called before profiling.
+ Error if torch version is less than 1.9.0.
+
+ Examples:
+ ```python
+ run = wandb.init()
+ run.config.id = "profile_code"
+
+ with torch.profiler.profile(
+ schedule=torch.profiler.schedule(wait=1, warmup=1, active=3, repeat=1),
+ on_trace_ready=wandb.profiler.torch_trace_handler(),
+ record_shapes=True,
+ with_stack=True,
+ ) as prof:
+ for i, batch in enumerate(dataloader):
+ if step >= 5:
+ break
+ train(batch)
+ prof.step()
+ ```
+ """
+ from packaging.version import parse
+
+ torch = wandb.util.get_module(PYTORCH_MODULE, required=True)
+ torch_profiler = wandb.util.get_module(PYTORCH_PROFILER_MODULE, required=True)
+
+ if parse(torch.__version__) < parse("1.9.0"):
+ raise Error(
+ f"torch version must be at least 1.9 in order to use the PyTorch Profiler API.\
+ \nVersion of torch currently installed: {torch.__version__}"
+ )
+
+ try:
+ logdir = os.path.join(wandb.run.dir, "pytorch_traces") # type: ignore
+ os.mkdir(logdir)
+ except AttributeError:
+ raise UsageError(
+ "Please call `wandb.init()` before `wandb.profiler.torch_trace_handler()`"
+ ) from None
+
+ with telemetry.context() as tel:
+ tel.feature.torch_profiler_trace = True
+
+ return torch_profiler.tensorboard_trace_handler(logdir)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/progress.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/progress.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef145aefe2510f86010ee5377bd0a7d9ecf715b2
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/progress.py
@@ -0,0 +1,77 @@
+"""progress."""
+
+import os
+from typing import IO, TYPE_CHECKING, Optional
+
+from wandb.errors import CommError
+
+if TYPE_CHECKING:
+ from typing import Protocol
+
+ class ProgressFn(Protocol):
+ def __call__(self, new_bytes: int, total_bytes: int) -> None:
+ pass
+
+
+class Progress:
+ """A helper class for displaying progress."""
+
+ ITER_BYTES = 1024 * 1024
+
+ def __init__(
+ self, file: IO[bytes], callback: Optional["ProgressFn"] = None
+ ) -> None:
+ self.file = file
+ if callback is None:
+
+ def callback_(new_bytes: int, total_bytes: int) -> None:
+ pass
+
+ callback = callback_
+
+ self.callback: ProgressFn = callback
+ self.bytes_read = 0
+ self.len = os.fstat(file.fileno()).st_size
+
+ def read(self, size=-1):
+ """Read bytes and call the callback."""
+ bites = self.file.read(size)
+ self.bytes_read += len(bites)
+ if not bites and self.bytes_read < self.len:
+ # Files shrinking during uploads causes request timeouts. Maybe
+ # we could avoid those by updating the self.len in real-time, but
+ # files getting truncated while uploading seems like something
+ # that shouldn't really be happening anyway.
+ raise CommError(
+ f"File {self.file.name} size shrank from {self.len} to {self.bytes_read} while it was being uploaded."
+ )
+ # Growing files are also likely to be bad, but our code didn't break
+ # on those in the past, so it's riskier to make that an error now.
+ self.callback(len(bites), self.bytes_read)
+ return bites
+
+ def rewind(self) -> None:
+ self.callback(-self.bytes_read, 0)
+ self.bytes_read = 0
+ self.file.seek(0)
+
+ def __getattr__(self, name):
+ """Fallback to the file object for attrs not defined here."""
+ if hasattr(self.file, name):
+ return getattr(self.file, name)
+ else:
+ raise AttributeError
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ bites = self.read(self.ITER_BYTES)
+ if len(bites) == 0:
+ raise StopIteration
+ return bites
+
+ def __len__(self):
+ return self.len
+
+ next = __next__
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/run.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/run.py
new file mode 100644
index 0000000000000000000000000000000000000000..885729a8b0c27eb91f9b0ff006576186be491235
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/run.py
@@ -0,0 +1,27 @@
+#
+"""InternalRun - Internal-only run object.
+
+Semi-stubbed run for internal process use.
+
+"""
+
+from typing_extensions import override
+
+from wandb.sdk import wandb_run
+
+
+class InternalRun(wandb_run.Run):
+ def __init__(self, run_obj, settings, datatypes_cb):
+ super().__init__(settings=settings)
+ self._run_obj = run_obj
+ self._datatypes_cb = datatypes_cb
+
+ @override
+ def _set_backend(self, backend):
+ # This type of run object can't have a backend
+ # or do any writes.
+ pass
+
+ @override
+ def _publish_file(self, fname: str) -> None:
+ self._datatypes_cb(fname)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/sample.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/sample.py
new file mode 100644
index 0000000000000000000000000000000000000000..7bffe7562e4b28614bad3e4c1cbf5be5423532fe
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/sample.py
@@ -0,0 +1,70 @@
+"""sample."""
+
+import math
+
+
+class UniformSampleAccumulator:
+ def __init__(self, min_samples=None):
+ self._samples = min_samples or 64
+ # force power of 2 samples
+ self._samples = 2 ** int(math.ceil(math.log(self._samples, 2)))
+ # target oversample by factor of 2
+ self._samples2 = self._samples * 2
+ # max size of each buffer
+ self._max = self._samples2 // 2
+ self._shift = 0
+ self._mask = (1 << self._shift) - 1
+ self._buckets = int(math.log(self._samples2, 2))
+ self._buckets_bits = int(math.log(self._buckets, 2))
+ self._buckets_mask = (1 << self._buckets_bits + 1) - 1
+ self._buckets_index = 0
+ self._bucket = []
+ self._index = [0] * self._buckets
+ self._count = 0
+ self._log2 = [0]
+
+ # pre-allocate buckets
+ for _ in range(self._buckets):
+ self._bucket.append([0] * self._max)
+ # compute integer log2
+ self._log2 += [int(math.log(i, 2)) for i in range(1, 2**self._buckets + 1)]
+
+ def _show(self):
+ print("=" * 20) # noqa: T201
+ for b in range(self._buckets):
+ b = (b + self._buckets_index) % self._buckets
+ vals = [self._bucket[b][i] for i in range(self._index[b])]
+ print(f"{b}: {vals}") # noqa: T201
+
+ def add(self, val):
+ self._count += 1
+ cnt = self._count
+ if cnt & self._mask:
+ return
+ b = cnt >> self._shift
+ b = self._log2[b] # b = int(math.log(b, 2))
+ if b >= self._buckets:
+ self._index[self._buckets_index] = 0
+ self._buckets_index = (self._buckets_index + 1) % self._buckets
+ self._shift += 1
+ self._mask = (self._mask << 1) | 1
+ b += self._buckets - 1
+ b = (b + self._buckets_index) % self._buckets
+ self._bucket[b][self._index[b]] = val
+ self._index[b] += 1
+
+ def get(self):
+ full = []
+ sampled = []
+ # self._show()
+ for b in range(self._buckets):
+ max_num = 2**b
+ b = (b + self._buckets_index) % self._buckets
+ modb = self._index[b] // max_num
+ for i in range(self._index[b]):
+ if not modb or i % modb == 0:
+ sampled.append(self._bucket[b][i])
+ full.append(self._bucket[b][i])
+ if len(sampled) < self._samples:
+ return tuple(full)
+ return tuple(sampled)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/sender.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/sender.py
new file mode 100644
index 0000000000000000000000000000000000000000..d5cc76903a016f329bb98f35128f62229bae926a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/sender.py
@@ -0,0 +1,1695 @@
+"""sender."""
+
+import contextlib
+import glob
+import gzip
+import json
+import logging
+import os
+import queue
+import threading
+import time
+import traceback
+from collections import defaultdict
+from datetime import datetime
+from queue import Queue
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Dict,
+ Generator,
+ List,
+ Literal,
+ Optional,
+ Tuple,
+ Type,
+ Union,
+)
+
+import requests
+
+import wandb
+from wandb import util
+from wandb.errors import CommError, UsageError
+from wandb.errors.util import ProtobufErrorHandler
+from wandb.filesync.dir_watcher import DirWatcher
+from wandb.proto import wandb_internal_pb2
+from wandb.sdk.artifacts.artifact_saver import ArtifactSaver
+from wandb.sdk.interface import interface
+from wandb.sdk.interface.interface_queue import InterfaceQueue
+from wandb.sdk.internal import (
+ context,
+ datastore,
+ file_stream,
+ internal_api,
+ sender_config,
+)
+from wandb.sdk.internal.file_pusher import FilePusher
+from wandb.sdk.internal.job_builder import JobBuilder
+from wandb.sdk.internal.settings_static import SettingsStatic
+from wandb.sdk.lib import (
+ config_util,
+ filenames,
+ filesystem,
+ proto_util,
+ redirect,
+ retry,
+ telemetry,
+)
+from wandb.sdk.lib.proto_util import message_to_dict
+
+if TYPE_CHECKING:
+ from wandb.proto.wandb_internal_pb2 import (
+ ArtifactManifest,
+ ArtifactManifestEntry,
+ ArtifactRecord,
+ EnvironmentRecord,
+ HttpResponse,
+ LocalInfo,
+ Record,
+ Result,
+ RunExitResult,
+ RunRecord,
+ SummaryRecord,
+ )
+
+ StreamLiterals = Literal["stdout", "stderr"]
+
+
+logger = logging.getLogger(__name__)
+
+
+_OUTPUT_MIN_CALLBACK_INTERVAL = 2 # seconds
+
+
+def _framework_priority() -> Generator[Tuple[str, str], None, None]:
+ yield from [
+ ("lightgbm", "lightgbm"),
+ ("catboost", "catboost"),
+ ("xgboost", "xgboost"),
+ ("transformers_huggingface", "huggingface"), # backwards compatibility
+ ("transformers", "huggingface"),
+ ("pytorch_ignite", "ignite"), # backwards compatibility
+ ("ignite", "ignite"),
+ ("pytorch_lightning", "lightning"),
+ ("fastai", "fastai"),
+ ("torch", "torch"),
+ ("keras", "keras"),
+ ("tensorflow", "tensorflow"),
+ ("sklearn", "sklearn"),
+ ]
+
+
+def _manifest_json_from_proto(manifest: "ArtifactManifest") -> Dict:
+ if manifest.version == 1:
+ if manifest.manifest_file_path:
+ contents = {}
+ with gzip.open(manifest.manifest_file_path, "rt") as f:
+ for line in f:
+ entry_json = json.loads(line)
+ path = entry_json.pop("path")
+ contents[path] = entry_json
+ else:
+ contents = {
+ content.path: _manifest_entry_from_proto(content)
+ for content in manifest.contents
+ }
+ else:
+ raise ValueError(f"unknown artifact manifest version: {manifest.version}")
+
+ return {
+ "version": manifest.version,
+ "storagePolicy": manifest.storage_policy,
+ "storagePolicyConfig": {
+ config.key: json.loads(config.value_json)
+ for config in manifest.storage_policy_config
+ },
+ "contents": contents,
+ }
+
+
+def _manifest_entry_from_proto(entry: "ArtifactManifestEntry") -> Dict:
+ birth_artifact_id = entry.birth_artifact_id if entry.birth_artifact_id else None
+ return {
+ "digest": entry.digest,
+ "birthArtifactID": birth_artifact_id,
+ "ref": entry.ref if entry.ref else None,
+ "size": entry.size if entry.size is not None else None,
+ "local_path": entry.local_path if entry.local_path else None,
+ "skip_cache": entry.skip_cache,
+ "extra": {extra.key: json.loads(extra.value_json) for extra in entry.extra},
+ }
+
+
+class ResumeState:
+ resumed: bool
+ step: int
+ history: int
+ events: int
+ output: int
+ runtime: float
+ wandb_runtime: Optional[int]
+ summary: Optional[Dict[str, Any]]
+ config: Optional[Dict[str, Any]]
+ tags: Optional[List[str]]
+
+ def __init__(self) -> None:
+ self.resumed = False
+ self.step = 0
+ self.history = 0
+ self.events = 0
+ self.output = 0
+ self.runtime = 0
+ # wandb_runtime is the canonical runtime (stored in summary._wandb.runtime)
+ self.wandb_runtime = None
+ self.summary = None
+ self.config = None
+ self.tags = None
+
+ def __str__(self) -> str:
+ obj = ",".join(map(lambda it: f"{it[0]}={it[1]}", vars(self).items()))
+ return f"ResumeState({obj})"
+
+
+class _OutputRawStream:
+ _stopped: threading.Event
+ _queue: queue.Queue
+ _emulator: redirect.TerminalEmulator
+ _writer_thr: threading.Thread
+ _reader_thr: threading.Thread
+
+ def __init__(self, stream: str, sm: "SendManager"):
+ self._stopped = threading.Event()
+ self._queue = queue.Queue()
+ self._emulator = redirect.TerminalEmulator()
+ self._writer_thr = threading.Thread(
+ target=sm._output_raw_writer_thread,
+ kwargs=dict(stream=stream),
+ daemon=True,
+ name=f"OutRawWr-{stream}",
+ )
+ self._reader_thr = threading.Thread(
+ target=sm._output_raw_reader_thread,
+ kwargs=dict(stream=stream),
+ daemon=True,
+ name=f"OutRawRd-{stream}",
+ )
+
+ def start(self) -> None:
+ self._writer_thr.start()
+ self._reader_thr.start()
+
+
+class SendManager:
+ UPDATE_CONFIG_TIME: int = 30
+ UPDATE_STATUS_TIME: int = 5
+
+ _settings: SettingsStatic
+ _record_q: "Queue[Record]"
+ _result_q: "Queue[Result]"
+ _interface: InterfaceQueue
+ _api_settings: Dict[str, str]
+ _partial_output: Dict[str, str]
+ _context_keeper: context.ContextKeeper
+
+ _telemetry_obj: telemetry.TelemetryRecord
+ _environment_obj: "EnvironmentRecord"
+ _fs: Optional["file_stream.FileStreamApi"]
+ _run: Optional["RunRecord"]
+ _entity: Optional[str]
+ _project: Optional[str]
+ _dir_watcher: Optional["DirWatcher"]
+ _pusher: Optional["FilePusher"]
+ _record_exit: Optional["Record"]
+ _exit_result: Optional["RunExitResult"]
+ _resume_state: ResumeState
+ _rewind_response: Optional[Dict[str, Any]]
+ _cached_server_info: Dict[str, Any]
+ _cached_viewer: Dict[str, Any]
+ _server_messages: List[Dict[str, Any]]
+ _ds: Optional[datastore.DataStore]
+ _output_raw_streams: Dict["StreamLiterals", _OutputRawStream]
+ _output_raw_file: Optional[filesystem.CRDedupedFile]
+ _send_record_num: int
+ _send_end_offset: int
+ _debounce_config_time: float
+ _debounce_status_time: float
+
+ def __init__(
+ self,
+ settings: SettingsStatic,
+ record_q: "Queue[Record]",
+ result_q: "Queue[Result]",
+ interface: InterfaceQueue,
+ context_keeper: context.ContextKeeper,
+ ) -> None:
+ self._settings = settings
+ self._record_q = record_q
+ self._result_q = result_q
+ self._interface = interface
+ self._context_keeper = context_keeper
+
+ self._ds = None
+ self._send_record_num = 0
+ self._send_end_offset = 0
+
+ self._fs = None
+ self._pusher = None
+ self._dir_watcher = None
+
+ # State updated by login
+ self._entity = None
+ self._flags = None
+
+ # State updated by wandb.init
+ self._run = None
+ self._project = None
+
+ # keep track of config from key/val updates
+ self._consolidated_config = sender_config.ConfigState()
+
+ self._start_time: int = 0
+ self._telemetry_obj = telemetry.TelemetryRecord()
+ self._environment_obj = wandb_internal_pb2.EnvironmentRecord()
+ self._config_metric_pbdict_list: List[Dict[int, Any]] = []
+ self._metadata_summary: Dict[str, Any] = defaultdict()
+ self._cached_summary: Dict[str, Any] = dict()
+ self._config_metric_index_dict: Dict[str, int] = {}
+ self._config_metric_dict: Dict[str, wandb_internal_pb2.MetricRecord] = {}
+ self._consolidated_summary: Dict[str, Any] = dict()
+
+ self._cached_server_info = dict()
+ self._cached_viewer = dict()
+ self._server_messages = []
+
+ # State updated by resuming
+ self._resume_state = ResumeState()
+ self._rewind_response = None
+
+ # State added when run_exit is initiated and complete
+ self._record_exit = None
+ self._exit_result = None
+
+ self._api = internal_api.Api(
+ default_settings=settings, retry_callback=self.retry_callback
+ )
+ self._api_settings = dict()
+
+ # queue filled by retry_callback
+ self._retry_q: Queue[HttpResponse] = queue.Queue()
+
+ # do we need to debounce?
+ self._config_needs_debounce: bool = False
+
+ # TODO(jhr): do something better, why do we need to send full lines?
+ self._partial_output = dict()
+
+ self._exit_code = 0
+
+ # internal vars for handing raw console output
+ self._output_raw_streams = dict()
+ self._output_raw_file = None
+
+ # job builder
+ self._job_builder = JobBuilder(
+ settings,
+ files_dir=settings.files_dir,
+ )
+
+ time_now = time.monotonic()
+ self._debounce_config_time = time_now
+ self._debounce_status_time = time_now
+
+ @classmethod
+ def setup(
+ cls,
+ root_dir: str,
+ resume: Union[None, bool, str],
+ ) -> "SendManager":
+ """Set up a standalone SendManager.
+
+ Exclusively used in `sync.py`.
+ """
+ files_dir = os.path.join(root_dir, "files")
+ settings = wandb.Settings(
+ x_files_dir=files_dir,
+ root_dir=root_dir,
+ # _start_time=0,
+ resume=resume,
+ # ignore_globs=(),
+ x_sync=True,
+ disable_job_creation=False,
+ x_file_stream_timeout_seconds=0,
+ )
+ record_q: Queue[Record] = queue.Queue()
+ result_q: Queue[Result] = queue.Queue()
+ publish_interface = InterfaceQueue(record_q=record_q)
+ context_keeper = context.ContextKeeper()
+ return SendManager(
+ settings=SettingsStatic(dict(settings)),
+ record_q=record_q,
+ result_q=result_q,
+ interface=publish_interface,
+ context_keeper=context_keeper,
+ )
+
+ def __len__(self) -> int:
+ return self._record_q.qsize()
+
+ def __enter__(self) -> "SendManager":
+ return self
+
+ def __exit__(
+ self,
+ exc_type: Optional[Type[BaseException]],
+ exc_value: Optional[BaseException],
+ exc_traceback: Optional[traceback.TracebackException],
+ ) -> Literal[False]:
+ while self:
+ data = next(self)
+ self.send(data)
+ self.finish()
+ return False
+
+ def retry_callback(self, status: int, response_text: str) -> None:
+ response = wandb_internal_pb2.HttpResponse()
+ response.http_status_code = status
+ response.http_response_text = response_text
+ self._retry_q.put(response)
+
+ def send(self, record: "Record") -> None:
+ self._update_record_num(record.num)
+ self._update_end_offset(record.control.end_offset)
+
+ record_type = record.WhichOneof("record_type")
+ assert record_type
+ handler_str = "send_" + record_type
+ send_handler = getattr(self, handler_str, None)
+ # Don't log output to reduce log noise
+ if record_type not in {"output", "request", "output_raw"}:
+ logger.debug(f"send: {record_type}")
+ assert send_handler, f"unknown send handler: {handler_str}"
+
+ context_id = context.context_id_from_record(record)
+ api_context = self._context_keeper.get(context_id)
+ try:
+ self._api.set_local_context(api_context)
+ send_handler(record)
+ except retry.RetryCancelledError:
+ logger.debug(f"Record cancelled: {record_type}")
+ self._context_keeper.release(context_id)
+ finally:
+ self._api.clear_local_context()
+
+ def send_preempting(self, _: "Record") -> None:
+ if self._fs:
+ self._fs.enqueue_preempting()
+
+ def send_request_sender_mark(self, _: "Record") -> None:
+ self._maybe_report_status(always=True)
+
+ def send_request(self, record: "Record") -> None:
+ request_type = record.request.WhichOneof("request_type")
+ assert request_type
+ handler_str = "send_request_" + request_type
+ send_handler = getattr(self, handler_str, None)
+ if request_type != "network_status":
+ logger.debug(f"send_request: {request_type}")
+ assert send_handler, f"unknown handle: {handler_str}"
+ send_handler(record)
+
+ def _respond_result(self, result: "Result") -> None:
+ context_id = context.context_id_from_result(result)
+ self._context_keeper.release(context_id)
+ self._result_q.put(result)
+
+ def _flatten(self, dictionary: Dict) -> None:
+ if isinstance(dictionary, dict):
+ for k, v in list(dictionary.items()):
+ if isinstance(v, dict):
+ self._flatten(v)
+ dictionary.pop(k)
+ for k2, v2 in v.items():
+ dictionary[k + "." + k2] = v2
+
+ def _update_record_num(self, record_num: int) -> None:
+ if not record_num:
+ return
+ # Currently how we handle offline mode and syncing is not
+ # compatible with this assertion due to how the exit record
+ # is (mis)handled:
+ # - using "always_send" in offline mode to trigger defer
+ # state machine
+ # - skipping the exit record in `wandb sync` mode so that
+ # it is always executed as the last record
+ if not self._settings._offline and not self._settings.x_sync:
+ assert record_num == self._send_record_num + 1
+ self._send_record_num = record_num
+
+ def _update_end_offset(self, end_offset: int) -> None:
+ if not end_offset:
+ return
+ self._send_end_offset = end_offset
+
+ def send_request_sender_read(self, record: "Record") -> None:
+ if self._ds is None:
+ self._ds = datastore.DataStore()
+ self._ds.open_for_scan(self._settings.sync_file)
+
+ # TODO(cancel_paused): implement cancel_set logic
+ # The idea is that there is an active request to cancel a
+ # message that is being read from the transaction log below
+
+ start_offset = record.request.sender_read.start_offset
+ final_offset = record.request.sender_read.final_offset
+ self._ds.seek(start_offset)
+
+ current_end_offset = 0
+ while current_end_offset < final_offset:
+ data = self._ds.scan_data()
+ assert data
+ current_end_offset = self._ds.get_offset()
+
+ send_record = wandb_internal_pb2.Record()
+ send_record.ParseFromString(data)
+ self._update_end_offset(current_end_offset)
+ self.send(send_record)
+
+ # make sure we perform deferred operations
+ self.debounce()
+
+ # make sure that we always update writer for every sended read request
+ self._maybe_report_status(always=True)
+
+ def send_request_stop_status(self, record: "Record") -> None:
+ result = proto_util._result_from_record(record)
+ status_resp = result.response.stop_status_response
+ status_resp.run_should_stop = False
+ if self._entity and self._project and self._run and self._run.run_id:
+ try:
+ status_resp.run_should_stop = self._api.check_stop_requested(
+ self._project, self._entity, self._run.run_id
+ )
+ except Exception as e:
+ logger.warning("Failed to check stop requested status: %s", e)
+ self._respond_result(result)
+
+ def _maybe_update_config(self, always: bool = False) -> None:
+ time_now = time.monotonic()
+ if (
+ not always
+ and time_now < self._debounce_config_time + self.UPDATE_CONFIG_TIME
+ ):
+ return
+ if self._config_needs_debounce:
+ self._debounce_config()
+ self._debounce_config_time = time_now
+
+ def _maybe_report_status(self, always: bool = False) -> None:
+ time_now = time.monotonic()
+ if (
+ not always
+ and time_now < self._debounce_status_time + self.UPDATE_STATUS_TIME
+ ):
+ return
+ self._debounce_status_time = time_now
+
+ status_report = wandb_internal_pb2.StatusReportRequest(
+ record_num=self._send_record_num,
+ sent_offset=self._send_end_offset,
+ )
+ status_time = time.time()
+ status_report.sync_time.FromMicroseconds(int(status_time * 1e6))
+ record = self._interface._make_request(status_report=status_report)
+ self._interface._publish(record)
+
+ def debounce(self, final: bool = False) -> None:
+ self._maybe_report_status(always=final)
+ self._maybe_update_config(always=final)
+
+ def _debounce_config(self) -> None:
+ config_value_dict = self._config_backend_dict()
+ # TODO(jhr): check result of upsert_run?
+ if self._run:
+ self._api.upsert_run(
+ name=self._run.run_id,
+ config=config_value_dict,
+ **self._api_settings, # type: ignore
+ )
+ self._config_save(config_value_dict)
+ self._config_needs_debounce = False
+
+ def send_request_network_status(self, record: "Record") -> None:
+ result = proto_util._result_from_record(record)
+ status_resp = result.response.network_status_response
+ while True:
+ try:
+ status_resp.network_responses.append(self._retry_q.get_nowait())
+ except queue.Empty:
+ break
+ except Exception as e:
+ logger.warning(f"Error emptying retry queue: {e}")
+ self._respond_result(result)
+
+ def send_exit(self, record: "Record") -> None:
+ # track where the exit came from
+ self._record_exit = record
+
+ run_exit = record.exit
+ self._exit_code = run_exit.exit_code
+ logger.info("handling exit code: %s", run_exit.exit_code)
+ runtime = run_exit.runtime
+ logger.info("handling runtime: %s", run_exit.runtime)
+ self._metadata_summary["runtime"] = runtime
+ self._update_summary()
+
+ # We need to give the request queue a chance to empty between states
+ # so use handle_request_defer as a state machine.
+ logger.info("send defer")
+ self._interface.publish_defer()
+
+ def send_final(self, record: "Record") -> None:
+ pass
+
+ def _flush_run(self) -> None:
+ pass
+
+ def send_request_status_report(self, record: "Record") -> None:
+ # todo? this is just a noop to please wandb sync
+ pass
+
+ def send_request_defer(self, record: "Record") -> None: # noqa: C901
+ defer = record.request.defer
+ state = defer.state
+ logger.info(f"handle sender defer: {state}")
+
+ def transition_state() -> None:
+ state = defer.state + 1
+ logger.info(f"send defer: {state}")
+ self._interface.publish_defer(state)
+
+ done = False
+ if state == defer.BEGIN:
+ transition_state()
+ elif state == defer.FLUSH_RUN:
+ self._flush_run()
+ transition_state()
+ elif state == defer.FLUSH_STATS:
+ # NOTE: this is handled in handler.py:handle_request_defer()
+ transition_state()
+ elif state == defer.FLUSH_PARTIAL_HISTORY:
+ # NOTE: this is handled in handler.py:handle_request_defer()
+ transition_state()
+ elif state == defer.FLUSH_TB:
+ # NOTE: this is handled in handler.py:handle_request_defer()
+ transition_state()
+ elif state == defer.FLUSH_SUM:
+ # NOTE: this is handled in handler.py:handle_request_defer()
+ transition_state()
+ elif state == defer.FLUSH_DEBOUNCER:
+ self.debounce(final=True)
+ transition_state()
+ elif state == defer.FLUSH_OUTPUT:
+ self._output_raw_finish()
+ transition_state()
+ elif state == defer.FLUSH_JOB:
+ self._flush_job()
+ transition_state()
+ elif state == defer.FLUSH_DIR:
+ if self._dir_watcher:
+ self._dir_watcher.finish()
+ self._dir_watcher = None
+ transition_state()
+ elif state == defer.FLUSH_FP:
+ if self._pusher:
+ # FilePusher generates some events for FileStreamApi, so we
+ # need to wait for pusher to finish before going to the next
+ # state to ensure that filestream gets all the events that we
+ # want before telling it to finish up
+ self._pusher.finish(transition_state)
+ else:
+ transition_state()
+ elif state == defer.JOIN_FP:
+ if self._pusher:
+ self._pusher.join()
+ transition_state()
+ elif state == defer.FLUSH_FS:
+ if self._fs:
+ # TODO(jhr): now is a good time to output pending output lines
+ self._fs.finish(self._exit_code)
+ self._fs = None
+ transition_state()
+ elif state == defer.FLUSH_FINAL:
+ self._interface.publish_final()
+ self._interface.publish_footer()
+ transition_state()
+ elif state == defer.END:
+ done = True
+ else:
+ raise AssertionError("unknown state")
+
+ if not done:
+ return
+
+ exit_result = wandb_internal_pb2.RunExitResult()
+
+ # mark exit done in case we are polling on exit
+ self._exit_result = exit_result
+
+ # Report response to mailbox
+ if self._record_exit and self._record_exit.control.mailbox_slot:
+ result = proto_util._result_from_record(self._record_exit)
+ result.exit_result.CopyFrom(exit_result)
+ self._respond_result(result)
+
+ def send_request_poll_exit(self, record: "Record") -> None:
+ if not record.control.req_resp and not record.control.mailbox_slot:
+ return
+
+ result = proto_util._result_from_record(record)
+
+ if self._pusher:
+ _alive, status = self._pusher.get_status()
+ file_counts = self._pusher.file_counts_by_category()
+ resp = result.response.poll_exit_response
+ resp.pusher_stats.uploaded_bytes = status.uploaded_bytes
+ resp.pusher_stats.total_bytes = status.total_bytes
+ resp.pusher_stats.deduped_bytes = status.deduped_bytes
+ resp.file_counts.wandb_count = file_counts.wandb
+ resp.file_counts.media_count = file_counts.media
+ resp.file_counts.artifact_count = file_counts.artifact
+ resp.file_counts.other_count = file_counts.other
+
+ if self._exit_result:
+ result.response.poll_exit_response.done = True
+ result.response.poll_exit_response.exit_result.CopyFrom(self._exit_result)
+
+ self._respond_result(result)
+
+ def _setup_resume(
+ self, run: "RunRecord"
+ ) -> Optional["wandb_internal_pb2.ErrorInfo"]:
+ """Queries the backend for a run; fail if the settings are incompatible."""
+ if not self._settings.resume:
+ return None
+
+ # TODO: This causes a race, we need to make the upsert atomically
+ # only create or update depending on the resume config
+ # we use the runs entity if set, otherwise fallback to users entity
+ # todo: ensure entity is not None as self._entity is Optional[str]
+ entity = run.entity or self._entity
+ logger.info(
+ "checking resume status for %s/%s/%s", entity, run.project, run.run_id
+ )
+ resume_status = self._api.run_resume_status(
+ entity=entity, # type: ignore
+ project_name=run.project,
+ name=run.run_id,
+ )
+ # No resume status = run does not exist; No t key in wandbConfig = run exists but hasn't been inited
+ if not resume_status or '"t":' not in resume_status.get("wandbConfig", ""):
+ if self._settings.resume == "must":
+ error = wandb_internal_pb2.ErrorInfo()
+ error.code = wandb_internal_pb2.ErrorInfo.ErrorCode.USAGE
+ error.message = (
+ "You provided an invalid value for the `resume` argument."
+ f" The value 'must' is not a valid option for resuming a run ({run.run_id}) that has not been initialized."
+ " Please check your inputs and try again with a valid run ID."
+ " If you are trying to start a new run, please omit the `resume` argument or use `resume='allow'`."
+ )
+ return error
+ return None
+
+ #
+ # handle cases where we have resume_status
+ #
+ if self._settings.resume == "never":
+ error = wandb_internal_pb2.ErrorInfo()
+ error.code = wandb_internal_pb2.ErrorInfo.ErrorCode.USAGE
+ error.message = (
+ "You provided an invalid value for the `resume` argument."
+ f" The value 'never' is not a valid option for resuming a run ({run.run_id}) that already exists."
+ " Please check your inputs and try again with a valid value for the `resume` argument."
+ )
+ return error
+
+ history = {}
+ events = {}
+ config = {}
+ summary = {}
+ try:
+ events_rt = 0
+ history_rt = 0
+ history = json.loads(resume_status["historyTail"])
+ if history:
+ history = json.loads(history[-1])
+ history_rt = history.get("_runtime", 0)
+ events = json.loads(resume_status["eventsTail"])
+ if events:
+ events = json.loads(events[-1])
+ events_rt = events.get("_runtime", 0)
+ config = json.loads(resume_status["config"] or "{}")
+ summary = json.loads(resume_status["summaryMetrics"] or "{}")
+ new_runtime = summary.get("_wandb", {}).get("runtime", None)
+ if new_runtime is not None:
+ self._resume_state.wandb_runtime = new_runtime
+ tags = resume_status.get("tags") or []
+
+ except (IndexError, ValueError):
+ logger.exception("unable to load resume tails")
+ if self._settings.resume == "must":
+ error = wandb_internal_pb2.ErrorInfo()
+ error.code = wandb_internal_pb2.ErrorInfo.ErrorCode.USAGE
+ error.message = f"resume='must' but could not resume ({run.run_id}) "
+ return error
+
+ # TODO: Do we need to restore config / summary?
+ # System metrics runtime is usually greater than history
+ self._resume_state.runtime = max(events_rt, history_rt)
+ last_step = history.get("_step", 0)
+ history_line_count = resume_status["historyLineCount"]
+ self._resume_state.step = last_step + 1 if history_line_count > 0 else last_step
+ self._resume_state.history = history_line_count
+ self._resume_state.events = resume_status["eventsLineCount"]
+ self._resume_state.output = resume_status["logLineCount"]
+ self._resume_state.config = config
+ self._resume_state.summary = summary
+ self._resume_state.tags = tags
+ self._resume_state.resumed = True
+ logger.info(f"configured resuming with: {self._resume_state}")
+ return None
+
+ def _telemetry_get_framework(self) -> str:
+ """Get telemetry data for internal config structure."""
+ # detect framework by checking what is loaded
+ imports: telemetry.TelemetryImports
+ if self._telemetry_obj.HasField("imports_finish"):
+ imports = self._telemetry_obj.imports_finish
+ elif self._telemetry_obj.HasField("imports_init"):
+ imports = self._telemetry_obj.imports_init
+ else:
+ return ""
+ framework = next(
+ (n for f, n in _framework_priority() if getattr(imports, f, False)), ""
+ )
+ return framework
+
+ def _config_backend_dict(self) -> sender_config.BackendConfigDict:
+ config = self._consolidated_config or sender_config.ConfigState()
+ return config.to_backend_dict(
+ telemetry_record=self._telemetry_obj,
+ framework=self._telemetry_get_framework(),
+ start_time_millis=self._start_time,
+ metric_pbdicts=self._config_metric_pbdict_list,
+ environment_record=self._environment_obj,
+ )
+
+ def _config_save(
+ self,
+ config_value_dict: sender_config.BackendConfigDict,
+ ) -> None:
+ config_path = os.path.join(self._settings.files_dir, "config.yaml")
+ config_util.save_config_file_from_dict(config_path, config_value_dict)
+
+ def _sync_spell(self) -> None:
+ """Sync this run with spell."""
+ if not self._run:
+ return
+ try:
+ env = os.environ
+ self._interface.publish_config(
+ key=("_wandb", "spell_url"), val=env.get("SPELL_RUN_URL")
+ )
+ url = f"{self._api.app_url}/{self._run.entity}/{self._run.project}/runs/{self._run.run_id}"
+ requests.put(
+ env.get("SPELL_API_URL", "https://api.spell.run") + "/wandb_url",
+ json={"access_token": env.get("WANDB_ACCESS_TOKEN"), "url": url},
+ timeout=2,
+ )
+ except requests.RequestException:
+ pass
+ # TODO: do something if sync spell is not successful?
+
+ def _setup_fork(self, server_run: dict):
+ assert self._run
+ assert self._run.branch_point
+ first_step = int(self._run.branch_point.value) + 1
+ self._resume_state.step = first_step
+ self._resume_state.history = server_run.get("historyLineCount", 0)
+ self._run.forked = True
+ self._run.starting_step = first_step
+
+ def _load_rewind_state(self, run: "RunRecord"):
+ assert run.branch_point
+ self._rewind_response = self._api.rewind_run(
+ run_name=run.run_id,
+ entity=run.entity or None,
+ project=run.project or None,
+ metric_name=run.branch_point.metric,
+ metric_value=run.branch_point.value,
+ program_path=self._settings.program or None,
+ )
+ self._resume_state.history = self._rewind_response.get("historyLineCount", 0)
+ self._resume_state.config = json.loads(
+ self._rewind_response.get("config", "{}")
+ )
+
+ def _install_rewind_state(self):
+ assert self._run
+ assert self._run.branch_point
+ assert self._rewind_response
+
+ first_step = int(self._run.branch_point.value) + 1
+ self._resume_state.step = first_step
+
+ # We set the fork flag here because rewind uses the forking
+ # infrastructure under the hood. Setting `forked` here
+ # ensures that run._step is properly set in the user process.
+ self._run.forked = True
+ self._run.starting_step = first_step
+
+ def _handle_error(
+ self,
+ record: "Record",
+ error: "wandb_internal_pb2.ErrorInfo",
+ run: "RunRecord",
+ ) -> None:
+ if record.control.req_resp or record.control.mailbox_slot:
+ result = proto_util._result_from_record(record)
+ result.run_result.run.CopyFrom(run)
+ result.run_result.error.CopyFrom(error)
+ self._respond_result(result)
+ else:
+ logger.error("Got error in async mode: %s", error.message)
+
+ def send_run(self, record: "Record", file_dir: Optional[str] = None) -> None:
+ run = record.run
+ error = None
+ is_wandb_init = self._run is None
+
+ # save start time of a run
+ self._start_time = int(run.start_time.ToMicroseconds() // 1e6)
+
+ # update telemetry
+ if run.telemetry:
+ self._telemetry_obj.MergeFrom(run.telemetry)
+ if self._settings.x_sync:
+ self._telemetry_obj.feature.sync = True
+
+ # build config dict
+ config_value_dict: Optional[sender_config.BackendConfigDict] = None
+ if run.config:
+ self._consolidated_config.update_from_proto(run.config)
+ config_value_dict = self._config_backend_dict()
+ self._config_save(config_value_dict)
+
+ do_rewind = run.branch_point.run == run.run_id
+ do_fork = not do_rewind and run.branch_point.run != ""
+ do_resume = bool(self._settings.resume)
+
+ num_resume_options_set = sum([do_fork, do_rewind, do_resume])
+ if num_resume_options_set > 1:
+ error = wandb_internal_pb2.ErrorInfo()
+ error.code = wandb_internal_pb2.ErrorInfo.ErrorCode.USAGE
+ error.message = (
+ "Multiple resume options specified. "
+ "Please specify only one of `fork_from`, `resume`, or `resume_from`."
+ )
+ self._handle_error(record, error, run)
+
+ if is_wandb_init:
+ # Ensure we have a project to query for status
+ if run.project == "":
+ run.project = util.auto_project_name(self._settings.program)
+ # Only check resume status on `wandb.init`
+
+ if do_resume:
+ error = self._setup_resume(run)
+
+ elif do_rewind:
+ error = self._load_rewind_state(run)
+
+ if error is not None:
+ self._handle_error(record, error, run)
+ return
+
+ # Save the resumed config
+ if self._resume_state.config is not None:
+ self._consolidated_config.merge_resumed_config(
+ config_util.dict_strip_value_dict(self._resume_state.config)
+ )
+
+ config_value_dict = self._config_backend_dict()
+ self._config_save(config_value_dict)
+
+ # handle empty config
+ # TODO(jhr): consolidate the 4 ways config is built:
+ # (passed config, empty config, resume config, send_config)
+ if not config_value_dict:
+ config_value_dict = self._config_backend_dict()
+ self._config_save(config_value_dict)
+
+ try:
+ server_run = self._init_run(run, config_value_dict)
+ except (CommError, UsageError) as e:
+ logger.error(e, exc_info=True)
+ error = ProtobufErrorHandler.from_exception(e)
+ self._handle_error(record, error, run)
+ return
+
+ assert self._run # self._run is configured in _init_run()
+
+ if do_fork:
+ error = self._setup_fork(server_run)
+
+ if error is not None:
+ self._handle_error(record, error, run)
+ return
+
+ if record.control.req_resp or record.control.mailbox_slot:
+ result = proto_util._result_from_record(record)
+ # TODO: we could do self._interface.publish_defer(resp) to notify
+ # the handler not to actually perform server updates for this uuid
+ # because the user process will send a summary update when we resume
+ result.run_result.run.CopyFrom(self._run)
+ self._respond_result(result)
+
+ # Only spin up our threads on the first run message
+ if is_wandb_init:
+ self._start_run_threads(file_dir)
+ else:
+ logger.info("updated run: %s", self._run.run_id)
+
+ def _update_resume_state(self, is_rewinding: bool, inserted: bool):
+ assert self._run
+ if self._resume_state.resumed:
+ self._run.resumed = True
+ if self._resume_state.wandb_runtime is not None:
+ self._run.runtime = self._resume_state.wandb_runtime
+ elif is_rewinding:
+ # because is_rewinding is mutually exclusive with self._resume_state.resumed,
+ # this block will always execute if is_rewinding is set
+ self._install_rewind_state()
+ else:
+ # If the user is not resuming, and we didn't insert on upsert_run then
+ # it is likely that we are overwriting the run which we might want to
+ # prevent in the future. This could be a false signal since an upsert_run
+ # message which gets retried in the network could also show up as not
+ # inserted.
+ if not inserted:
+ # no need to flush this, it will get updated eventually
+ self._telemetry_obj.feature.maybe_run_overwrite = True
+
+ def _init_run(
+ self,
+ run: "RunRecord",
+ config_dict: Optional[sender_config.BackendConfigDict],
+ ) -> dict:
+ # We subtract the previous runs runtime when resuming
+ start_time = (
+ run.start_time.ToMicroseconds() / 1e6
+ ) - self._resume_state.runtime
+ # TODO: we don't check inserted currently, ultimately we should make
+ # the upsert know the resume state and fail transactionally
+
+ if self._resume_state and self._resume_state.tags and not run.tags:
+ run.tags.extend(self._resume_state.tags)
+
+ is_rewinding = bool(self._settings.resume_from)
+ if is_rewinding:
+ assert self._rewind_response
+ server_run = self._rewind_response
+ server_messages = None
+ inserted = True
+ else:
+ server_run, inserted, server_messages = self._api.upsert_run(
+ name=run.run_id,
+ entity=run.entity or None,
+ project=run.project or None,
+ group=run.run_group or None,
+ job_type=run.job_type or None,
+ display_name=run.display_name or None,
+ notes=run.notes or None,
+ tags=run.tags[:] or None,
+ config=config_dict or None,
+ sweep_name=run.sweep_id or None,
+ host=run.host or None,
+ program_path=self._settings.program or None,
+ repo=run.git.remote_url or None,
+ commit=run.git.commit or None,
+ )
+
+ # TODO: we don't want to create jobs in sweeps, since the
+ # executable doesn't appear to be consistent
+ if run.sweep_id:
+ self._job_builder.disable = True
+
+ self._server_messages = server_messages or []
+ self._run = run
+
+ if self._resume_state.resumed and is_rewinding:
+ # this should not ever be possible to hit, since we check for
+ # resumption above and raise an error if resumption is specified
+ # twice.
+ raise ValueError(
+ "Cannot attempt to rewind and resume a run - only one of "
+ "`resume` or `resume_from` can be specified."
+ )
+
+ self._update_resume_state(is_rewinding, inserted)
+ self._run.starting_step = self._resume_state.step
+ self._run.start_time.FromMicroseconds(int(start_time * 1e6))
+ self._run.config.CopyFrom(self._interface._make_config(config_dict))
+ if self._resume_state.summary is not None:
+ self._run.summary.CopyFrom(
+ self._interface._make_summary_from_dict(self._resume_state.summary)
+ )
+ storage_id = server_run.get("id")
+ if storage_id:
+ self._run.storage_id = storage_id
+ id = server_run.get("name")
+ if id:
+ self._api.set_current_run_id(id)
+ display_name = server_run.get("displayName")
+ if display_name:
+ self._run.display_name = display_name
+ project = server_run.get("project")
+ # TODO: remove self._api.set_settings, and make self._project a property?
+ if project:
+ project_name = project.get("name")
+ if project_name:
+ self._run.project = project_name
+ self._project = project_name
+ self._api_settings["project"] = project_name
+ self._api.set_setting("project", project_name)
+ entity = project.get("entity")
+ if entity:
+ entity_name = entity.get("name")
+ if entity_name:
+ self._run.entity = entity_name
+ self._entity = entity_name
+ self._api_settings["entity"] = entity_name
+ self._api.set_setting("entity", entity_name)
+ sweep_id = server_run.get("sweepName")
+ if sweep_id:
+ self._run.sweep_id = sweep_id
+ if os.getenv("SPELL_RUN_URL"):
+ self._sync_spell()
+ return server_run
+
+ def _start_run_threads(self, file_dir: Optional[str] = None) -> None:
+ assert self._run # self._run is configured by caller
+ self._fs = file_stream.FileStreamApi(
+ self._api,
+ self._run.run_id,
+ self._run.start_time.ToMicroseconds() / 1e6,
+ timeout=self._settings.x_file_stream_timeout_seconds or 0,
+ settings=self._api_settings,
+ )
+ # Ensure the streaming polices have the proper offsets
+ self._fs.set_file_policy("wandb-summary.json", file_stream.SummaryFilePolicy())
+ self._fs.set_file_policy(
+ "wandb-history.jsonl",
+ file_stream.JsonlFilePolicy(start_chunk_id=self._resume_state.history),
+ )
+ self._fs.set_file_policy(
+ "wandb-events.jsonl",
+ file_stream.JsonlFilePolicy(start_chunk_id=self._resume_state.events),
+ )
+ self._fs.set_file_policy(
+ "output.log",
+ file_stream.CRDedupeFilePolicy(start_chunk_id=self._resume_state.output),
+ )
+
+ # hack to merge run_settings and self._settings object together
+ # so that fields like entity or project are available to be attached to Sentry events.
+ run_settings = message_to_dict(self._run)
+ _settings = dict(self._settings)
+ _settings.update(run_settings)
+ wandb._sentry.configure_scope(tags=_settings, process_context="internal")
+
+ self._fs.start()
+ self._pusher = FilePusher(self._api, self._fs, settings=self._settings)
+ self._dir_watcher = DirWatcher(self._settings, self._pusher, file_dir)
+ logger.info(
+ "run started: %s with start time %s",
+ self._run.run_id,
+ self._run.start_time.ToMicroseconds() / 1e6,
+ )
+
+ def _save_history(self, history_dict: Dict[str, Any]) -> None:
+ if self._fs:
+ self._fs.push(filenames.HISTORY_FNAME, json.dumps(history_dict))
+
+ def send_history(self, record: "Record") -> None:
+ history = record.history
+ history_dict = proto_util.dict_from_proto_list(history.item)
+ self._save_history(history_dict)
+
+ def _update_summary_record(self, summary: "SummaryRecord") -> None:
+ summary_dict = proto_util.dict_from_proto_list(summary.update)
+ self._cached_summary = summary_dict
+ self._update_summary()
+
+ def send_summary(self, record: "Record") -> None:
+ self._update_summary_record(record.summary)
+
+ def send_request_summary_record(self, record: "Record") -> None:
+ self._update_summary_record(record.request.summary_record.summary)
+
+ def _update_summary(self) -> None:
+ summary_dict = self._cached_summary.copy()
+ summary_dict.pop("_wandb", None)
+ if self._metadata_summary:
+ summary_dict["_wandb"] = self._metadata_summary
+ # merge with consolidated summary
+ self._consolidated_summary.update(summary_dict)
+ json_summary = json.dumps(self._consolidated_summary)
+ if self._fs:
+ self._fs.push(filenames.SUMMARY_FNAME, json_summary)
+ # TODO(jhr): we should only write this at the end of the script
+ summary_path = os.path.join(self._settings.files_dir, filenames.SUMMARY_FNAME)
+ with open(summary_path, "w") as f:
+ f.write(json_summary)
+ self._save_file(interface.GlobStr(filenames.SUMMARY_FNAME))
+
+ def send_stats(self, record: "Record") -> None:
+ stats = record.stats
+ if stats.stats_type != wandb_internal_pb2.StatsRecord.StatsType.SYSTEM:
+ return
+ if not self._fs:
+ return
+ if not self._run:
+ return
+ now_us = stats.timestamp.ToMicroseconds()
+ start_us = self._run.start_time.ToMicroseconds()
+ d = dict()
+ for item in stats.item:
+ try:
+ d[item.key] = json.loads(item.value_json)
+ except json.JSONDecodeError:
+ logger.exception("error decoding stats json: %s", item.value_json)
+ row: Dict[str, Any] = dict(system=d)
+ self._flatten(row)
+ row["_wandb"] = True
+ row["_timestamp"] = now_us / 1e6
+ row["_runtime"] = (now_us - start_us) / 1e6
+ self._fs.push(filenames.EVENTS_FNAME, json.dumps(row))
+ # TODO(jhr): check fs.push results?
+
+ def _output_raw_finish(self) -> None:
+ for stream, output_raw in self._output_raw_streams.items():
+ output_raw._stopped.set()
+
+ # shut down threads
+ output_raw._writer_thr.join(timeout=5)
+ if output_raw._writer_thr.is_alive():
+ logger.info("processing output...")
+ output_raw._writer_thr.join()
+ output_raw._reader_thr.join()
+
+ # flush output buffers and files
+ self._output_raw_flush(stream)
+ self._output_raw_streams = {}
+ if self._output_raw_file:
+ self._output_raw_file.close()
+ self._output_raw_file = None
+
+ def _output_raw_writer_thread(self, stream: "StreamLiterals") -> None:
+ while True:
+ output_raw = self._output_raw_streams[stream]
+ if output_raw._queue.empty():
+ if output_raw._stopped.is_set():
+ return
+ time.sleep(0.5)
+ continue
+ data = []
+ while not output_raw._queue.empty():
+ data.append(output_raw._queue.get())
+ if output_raw._stopped.is_set() and sum(map(len, data)) > 100000:
+ logger.warning("Terminal output too large. Logging without processing.")
+ self._output_raw_flush(stream)
+ for line in data:
+ self._output_raw_flush(stream, line)
+ # TODO: lets mark that this happened in telemetry
+ return
+ try:
+ output_raw._emulator.write("".join(data))
+ except Exception as e:
+ logger.warning(f"problem writing to output_raw emulator: {e}")
+
+ def _output_raw_reader_thread(self, stream: "StreamLiterals") -> None:
+ output_raw = self._output_raw_streams[stream]
+ while not (output_raw._stopped.is_set() and output_raw._queue.empty()):
+ self._output_raw_flush(stream)
+ time.sleep(_OUTPUT_MIN_CALLBACK_INTERVAL)
+
+ def _output_raw_flush(
+ self, stream: "StreamLiterals", data: Optional[str] = None
+ ) -> None:
+ if data is None:
+ output_raw = self._output_raw_streams[stream]
+ try:
+ data = output_raw._emulator.read()
+ except Exception as e:
+ logger.warning(f"problem reading from output_raw emulator: {e}")
+ if data:
+ self._send_output_line(stream, data)
+ if self._output_raw_file:
+ self._output_raw_file.write(data.encode("utf-8"))
+
+ def send_request_python_packages(self, record: "Record") -> None:
+ import os
+
+ from wandb.sdk.lib.filenames import REQUIREMENTS_FNAME
+
+ installed_packages_list = sorted(
+ f"{r.name}=={r.version}" for r in record.request.python_packages.package
+ )
+ with open(os.path.join(self._settings.files_dir, REQUIREMENTS_FNAME), "w") as f:
+ f.write("\n".join(installed_packages_list))
+
+ def send_output(self, record: "Record") -> None:
+ if not self._fs:
+ return
+ out = record.output
+ stream: StreamLiterals = "stdout"
+ if out.output_type == wandb_internal_pb2.OutputRecord.OutputType.STDERR:
+ stream = "stderr"
+ line = out.line
+ self._send_output_line(stream, line)
+
+ def send_output_raw(self, record: "Record") -> None:
+ if not self._fs:
+ return
+ out = record.output_raw
+ stream: StreamLiterals = "stdout"
+ if out.output_type == wandb_internal_pb2.OutputRawRecord.OutputType.STDERR:
+ stream = "stderr"
+ line = out.line
+
+ output_raw = self._output_raw_streams.get(stream)
+ if not output_raw:
+ output_raw = _OutputRawStream(stream=stream, sm=self)
+ self._output_raw_streams[stream] = output_raw
+
+ # open the console output file shared between both streams
+ if not self._output_raw_file:
+ output_log_path = os.path.join(
+ self._settings.files_dir, filenames.OUTPUT_FNAME
+ )
+ output_raw_file = None
+ try:
+ output_raw_file = filesystem.CRDedupedFile(
+ open(output_log_path, "wb")
+ )
+ except OSError as e:
+ logger.warning(f"could not open output_raw_file: {e}")
+ if output_raw_file:
+ self._output_raw_file = output_raw_file
+ output_raw.start()
+
+ output_raw._queue.put(line)
+
+ def _send_output_line(self, stream: "StreamLiterals", line: str) -> None:
+ """Combined writer for raw and non raw output lines.
+
+ This is combined because they are both post emulator.
+ """
+ prepend = ""
+ if stream == "stderr":
+ prepend = "ERROR "
+ if not line.endswith("\n"):
+ self._partial_output.setdefault(stream, "")
+ if line.startswith("\r"):
+ # TODO: maybe we shouldn't just drop this, what if there was some \ns in the partial
+ # that should probably be the check instead of not line.endswith(\n")
+ # logger.info(f"Dropping data {self._partial_output[stream]}")
+ self._partial_output[stream] = ""
+ self._partial_output[stream] += line
+ # TODO(jhr): how do we make sure this gets flushed?
+ # we might need this for other stuff like telemetry
+ else:
+ # TODO(jhr): use time from timestamp proto
+ # TODO(jhr): do we need to make sure we write full lines?
+ # seems to be some issues with line breaks
+ cur_time = time.time()
+ timestamp = datetime.utcfromtimestamp(cur_time).isoformat() + " "
+ prev_str = self._partial_output.get(stream, "")
+ line = f"{prepend}{timestamp}{prev_str}{line}"
+ if self._fs:
+ self._fs.push(filenames.OUTPUT_FNAME, line)
+ self._partial_output[stream] = ""
+
+ def _update_config(self) -> None:
+ self._config_needs_debounce = True
+
+ def send_config(self, record: "Record") -> None:
+ self._consolidated_config.update_from_proto(record.config)
+ self._update_config()
+
+ def send_metric(self, record: "Record") -> None:
+ metric = record.metric
+ if metric.glob_name:
+ logger.warning("Seen metric with glob (shouldn't happen)")
+ return
+
+ # merge or overwrite
+ old_metric = self._config_metric_dict.get(
+ metric.name, wandb_internal_pb2.MetricRecord()
+ )
+ if metric._control.overwrite:
+ old_metric.CopyFrom(metric)
+ else:
+ old_metric.MergeFrom(metric)
+ self._config_metric_dict[metric.name] = old_metric
+ metric = old_metric
+
+ # convert step_metric to index
+ if metric.step_metric:
+ find_step_idx = self._config_metric_index_dict.get(metric.step_metric)
+ if find_step_idx is not None:
+ # make a copy of this metric as we will be modifying it
+ rec = wandb_internal_pb2.Record()
+ rec.metric.CopyFrom(metric)
+ metric = rec.metric
+
+ metric.ClearField("step_metric")
+ metric.step_metric_index = find_step_idx + 1
+
+ md: Dict[int, Any] = proto_util.proto_encode_to_dict(metric)
+ find_idx = self._config_metric_index_dict.get(metric.name)
+ if find_idx is not None:
+ self._config_metric_pbdict_list[find_idx] = md
+ else:
+ next_idx = len(self._config_metric_pbdict_list)
+ self._config_metric_pbdict_list.append(md)
+ self._config_metric_index_dict[metric.name] = next_idx
+ self._debounce_config()
+
+ def _update_telemetry_record(self, telemetry: telemetry.TelemetryRecord) -> None:
+ self._telemetry_obj.MergeFrom(telemetry)
+ self._debounce_config()
+
+ def send_telemetry(self, record: "Record") -> None:
+ self._update_telemetry_record(record.telemetry)
+
+ def send_request_telemetry_record(self, record: "Record") -> None:
+ self._update_telemetry_record(record.request.telemetry_record.telemetry)
+
+ def _save_file(
+ self, fname: interface.GlobStr, policy: "interface.PolicyName" = "end"
+ ) -> None:
+ logger.info("saving file %s with policy %s", fname, policy)
+ if self._dir_watcher:
+ self._dir_watcher.update_policy(fname, policy)
+
+ def send_files(self, record: "Record") -> None:
+ files = record.files
+ for k in files.files:
+ # TODO(jhr): fix paths with directories
+ self._save_file(
+ interface.GlobStr(glob.escape(k.path)),
+ interface.file_enum_to_policy(k.policy),
+ )
+
+ def send_header(self, record: "Record") -> None:
+ pass
+
+ def send_footer(self, record: "Record") -> None:
+ pass
+
+ def send_tbrecord(self, record: "Record") -> None:
+ # tbrecord watching threads are handled by handler.py
+ pass
+
+ def _update_environment_record(self, environment: "EnvironmentRecord") -> None:
+ self._environment_obj.MergeFrom(environment)
+ self._debounce_config()
+
+ def send_environment(self, record: "Record") -> None:
+ """Inject environment info into config and upload as a JSON file."""
+ self._update_environment_record(record.environment)
+
+ environment_json = json.dumps(proto_util.message_to_dict(self._environment_obj))
+
+ with open(
+ os.path.join(self._settings.files_dir, filenames.METADATA_FNAME), "w"
+ ) as f:
+ f.write(environment_json)
+
+ self._save_file(interface.GlobStr(filenames.METADATA_FNAME), policy="now")
+
+ def send_request_link_artifact(self, record: "Record") -> None:
+ if not (record.control.req_resp or record.control.mailbox_slot):
+ raise ValueError(
+ f"Expected either `req_resp` or `mailbox_slot`, got: {record.control!r}"
+ )
+ result = proto_util._result_from_record(record)
+ link = record.request.link_artifact
+ client_id = link.client_id
+ server_id = link.server_id
+ portfolio_name = link.portfolio_name
+ entity = link.portfolio_entity
+ project = link.portfolio_project
+ aliases = link.portfolio_aliases
+ organization = link.portfolio_organization
+ logger.debug(
+ f"link_artifact params - client_id={client_id}, server_id={server_id}, "
+ f"portfolio_name={portfolio_name}, entity={entity}, project={project}, "
+ f"organization={organization}"
+ )
+ if (client_id or server_id) and portfolio_name and entity and project:
+ try:
+ response = self._api.link_artifact(
+ client_id,
+ server_id,
+ portfolio_name,
+ entity,
+ project,
+ aliases,
+ organization,
+ )
+ result.response.link_artifact_response.version_index = response[
+ "versionIndex"
+ ]
+ except Exception as e:
+ org_or_entity = organization or entity
+ result.response.link_artifact_response.error_message = (
+ f"error linking artifact to "
+ f'"{org_or_entity}/{project}/{portfolio_name}"; error: {e}'
+ )
+ logger.warning("Failed to link artifact to portfolio: %s", e)
+ self._respond_result(result)
+
+ def send_use_artifact(self, record: "Record") -> None:
+ """Pretend to send a used artifact.
+
+ This function doesn't actually send anything, it is just used internally.
+ """
+ use = record.use_artifact
+
+ if use.type == "job" and not use.partial.job_name:
+ self._job_builder.disable = True
+ elif use.partial.job_name:
+ # job is partial, let job builder rebuild job, set job source dict
+ self._job_builder.set_partial_source_id(use.id)
+
+ def send_request_log_artifact(self, record: "Record") -> None:
+ result = proto_util._result_from_record(record)
+ artifact = record.request.log_artifact.artifact
+ history_step = record.request.log_artifact.history_step
+
+ try:
+ res = self._send_artifact(artifact, history_step)
+ assert res, "Unable to send artifact"
+ result.response.log_artifact_response.artifact_id = res["id"]
+ logger.info(f"logged artifact {artifact.name} - {res}")
+ except Exception as e:
+ result.response.log_artifact_response.error_message = (
+ f'error logging artifact "{artifact.type}/{artifact.name}": {e}'
+ )
+
+ self._respond_result(result)
+
+ def send_artifact(self, record: "Record") -> None:
+ artifact = record.artifact
+ try:
+ res = self._send_artifact(artifact)
+ logger.info(f"sent artifact {artifact.name} - {res}")
+ except Exception:
+ logger.exception(
+ f'send_artifact: failed for artifact "{artifact.type}/{artifact.name}"'
+ )
+
+ def _send_artifact(
+ self, artifact: "ArtifactRecord", history_step: Optional[int] = None
+ ) -> Optional[Dict]:
+ from packaging.version import parse
+
+ assert self._pusher
+ saver = ArtifactSaver(
+ api=self._api,
+ digest=artifact.digest,
+ manifest_json=_manifest_json_from_proto(artifact.manifest),
+ file_pusher=self._pusher,
+ is_user_created=artifact.user_created,
+ )
+
+ if artifact.distributed_id:
+ max_cli_version = self._max_cli_version()
+ if max_cli_version is None or parse(max_cli_version) < parse("0.10.16"):
+ logger.warning(
+ "This W&B Server doesn't support distributed artifacts, "
+ "have your administrator install wandb/local >= 0.9.37"
+ )
+ return None
+
+ metadata = json.loads(artifact.metadata) if artifact.metadata else None
+ res = saver.save(
+ entity=artifact.entity,
+ project=artifact.project,
+ type=artifact.type,
+ name=artifact.name,
+ client_id=artifact.client_id,
+ sequence_client_id=artifact.sequence_client_id,
+ metadata=metadata,
+ ttl_duration_seconds=artifact.ttl_duration_seconds or None,
+ description=artifact.description or None,
+ aliases=artifact.aliases,
+ tags=artifact.tags,
+ use_after_commit=artifact.use_after_commit,
+ distributed_id=artifact.distributed_id,
+ finalize=artifact.finalize,
+ incremental=artifact.incremental_beta1,
+ history_step=history_step,
+ base_id=artifact.base_id or None,
+ )
+
+ self._job_builder._handle_server_artifact(res, artifact)
+
+ if artifact.manifest.manifest_file_path:
+ with contextlib.suppress(FileNotFoundError):
+ os.remove(artifact.manifest.manifest_file_path)
+ return res
+
+ def send_alert(self, record: "Record") -> None:
+ from packaging.version import parse
+
+ alert = record.alert
+ max_cli_version = self._max_cli_version()
+ if max_cli_version is None or parse(max_cli_version) < parse("0.10.9"):
+ logger.warning(
+ "This W&B server doesn't support alerts, "
+ "have your administrator install wandb/local >= 0.9.31"
+ )
+ else:
+ try:
+ self._api.notify_scriptable_run_alert(
+ title=alert.title,
+ text=alert.text,
+ level=alert.level,
+ wait_duration=alert.wait_duration,
+ )
+ except Exception:
+ logger.exception(f"send_alert: failed for alert {alert.title!r}")
+
+ def finish(self) -> None:
+ logger.info("shutting down sender")
+ # if self._tb_watcher:
+ # self._tb_watcher.finish()
+ self._output_raw_finish()
+ if self._dir_watcher:
+ self._dir_watcher.finish()
+ self._dir_watcher = None
+ if self._pusher:
+ self._pusher.finish()
+ self._pusher.join()
+ self._pusher = None
+ if self._fs:
+ self._fs.finish(self._exit_code)
+ self._fs = None
+ wandb._sentry.end_session()
+
+ def _max_cli_version(self) -> Optional[str]:
+ server_info = self.get_server_info()
+ max_cli_version = server_info.get("cliVersionInfo", {}).get(
+ "max_cli_version", None
+ )
+ if not isinstance(max_cli_version, str):
+ return None
+ return max_cli_version
+
+ def get_viewer_server_info(self) -> None:
+ if self._cached_server_info and self._cached_viewer:
+ return
+ self._cached_viewer, self._cached_server_info = self._api.viewer_server_info()
+
+ def get_viewer_info(self) -> Dict[str, Any]:
+ if not self._cached_viewer:
+ self.get_viewer_server_info()
+ return self._cached_viewer
+
+ def get_server_info(self) -> Dict[str, Any]:
+ if not self._cached_server_info:
+ self.get_viewer_server_info()
+ return self._cached_server_info
+
+ def get_local_info(self) -> "LocalInfo":
+ """Queries the server to get the local version information.
+
+ First, we perform an introspection, if it returns empty we deduce that the
+ docker image is out-of-date. Otherwise, we use the returned values to deduce the
+ state of the local server.
+ """
+ local_info = wandb_internal_pb2.LocalInfo()
+ if self._settings._offline:
+ local_info.out_of_date = False
+ return local_info
+
+ latest_local_version = "latest"
+
+ # Assuming the query is successful if the result is empty it indicates that
+ # the backend is out of date since it doesn't have the desired field
+ server_info = self.get_server_info()
+ latest_local_version_info = server_info.get("latestLocalVersionInfo", {})
+ if latest_local_version_info is None:
+ local_info.out_of_date = False
+ else:
+ local_info.out_of_date = latest_local_version_info.get("outOfDate", True)
+ local_info.version = latest_local_version_info.get(
+ "latestVersionString", latest_local_version
+ )
+ return local_info
+
+ def _flush_job(self) -> None:
+ if self._job_builder.disable or self._settings._offline:
+ return
+ self._job_builder.set_config(self._consolidated_config.non_internal_config())
+ summary_dict = self._cached_summary.copy()
+ summary_dict.pop("_wandb", None)
+ self._job_builder.set_summary(summary_dict)
+
+ artifact = self._job_builder.build(api=self._api)
+ if artifact is not None and self._run is not None:
+ proto_artifact = self._interface._make_artifact(artifact)
+ proto_artifact.run_id = self._run.run_id
+ proto_artifact.project = self._run.project
+ proto_artifact.entity = self._run.entity
+ # TODO: this should be removed when the latest tag is handled
+ # by the backend (WB-12116)
+ proto_artifact.aliases.append("latest")
+ # add docker image tag
+ for alias in self._job_builder._aliases:
+ proto_artifact.aliases.append(alias)
+
+ proto_artifact.user_created = True
+ proto_artifact.use_after_commit = True
+ proto_artifact.finalize = True
+
+ self._interface._publish_artifact(proto_artifact)
+
+ def __next__(self) -> "Record":
+ return self._record_q.get(block=True)
+
+ next = __next__
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/sender_config.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/sender_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..0cc478958173637fefba1c620977af1d52faad0d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/sender_config.py
@@ -0,0 +1,203 @@
+import json
+from typing import Any, Dict, NewType, Optional, Sequence
+
+from wandb.proto import wandb_internal_pb2
+from wandb.sdk.lib import proto_util, telemetry
+
+BackendConfigDict = NewType("BackendConfigDict", Dict[str, Any])
+"""Run config dictionary in the format used by the backend."""
+
+_WANDB_INTERNAL_KEY = "_wandb"
+
+
+class ConfigState:
+ """The configuration of a run."""
+
+ def __init__(self, tree: Optional[Dict[str, Any]] = None) -> None:
+ self._tree: Dict[str, Any] = tree or {}
+ """A tree with string-valued nodes and JSON leaves.
+
+ Leaves are Python objects that are valid JSON values:
+
+ * Primitives like strings and numbers
+ * Dictionaries from strings to JSON objects
+ * Lists of JSON objects
+ """
+
+ def non_internal_config(self) -> Dict[str, Any]:
+ """Returns the config settings minus "_wandb"."""
+ return {k: v for k, v in self._tree.items() if k != _WANDB_INTERNAL_KEY}
+
+ def update_from_proto(
+ self,
+ config_record: wandb_internal_pb2.ConfigRecord,
+ ) -> None:
+ """Applies update and remove commands."""
+ for config_item in config_record.update:
+ self._update_at_path(
+ _key_path(config_item),
+ json.loads(config_item.value_json),
+ )
+
+ for config_item in config_record.remove:
+ self._delete_at_path(_key_path(config_item))
+
+ def merge_resumed_config(self, old_config_tree: Dict[str, Any]) -> None:
+ """Merges the config from a run that's being resumed."""
+ # Add any top-level keys that aren't already set.
+ self._add_unset_keys_from_subtree(old_config_tree, [])
+
+ # When resuming a run, we want to ensure the some of the old configs keys
+ # are maintained. So we have this logic here to add back
+ # any keys that were in the old config but not in the new config
+ for key in ["viz", "visualize", "mask/class_labels"]:
+ self._add_unset_keys_from_subtree(
+ old_config_tree,
+ [_WANDB_INTERNAL_KEY, key],
+ )
+
+ def _add_unset_keys_from_subtree(
+ self,
+ old_config_tree: Dict[str, Any],
+ path: Sequence[str],
+ ) -> None:
+ """Uses the given subtree for keys that aren't already set."""
+ old_subtree = _subtree(old_config_tree, path, create=False)
+ if not old_subtree:
+ return
+
+ new_subtree = _subtree(self._tree, path, create=True)
+ assert new_subtree is not None
+
+ for key, value in old_subtree.items():
+ if key not in new_subtree:
+ new_subtree[key] = value
+
+ def to_backend_dict(
+ self,
+ telemetry_record: telemetry.TelemetryRecord,
+ framework: Optional[str],
+ start_time_millis: int,
+ metric_pbdicts: Sequence[Dict[int, Any]],
+ environment_record: wandb_internal_pb2.EnvironmentRecord,
+ ) -> BackendConfigDict:
+ """Returns a dictionary representation expected by the backend.
+
+ The backend expects the configuration in a specific format, and the
+ config is also used to store additional metadata about the run.
+
+ Args:
+ telemetry_record: Telemetry information to insert.
+ framework: The detected framework used in the run (e.g. TensorFlow).
+ start_time_millis: The run's start time in Unix milliseconds.
+ metric_pbdicts: List of dict representations of metric protobuffers.
+ """
+ backend_dict = self._tree.copy()
+ wandb_internal = backend_dict.setdefault(_WANDB_INTERNAL_KEY, {})
+
+ ###################################################
+ # Telemetry information
+ ###################################################
+ py_version = telemetry_record.python_version
+ if py_version:
+ wandb_internal["python_version"] = py_version
+
+ cli_version = telemetry_record.cli_version
+ if cli_version:
+ wandb_internal["cli_version"] = cli_version
+
+ if framework:
+ wandb_internal["framework"] = framework
+
+ huggingface_version = telemetry_record.huggingface_version
+ if huggingface_version:
+ wandb_internal["huggingface_version"] = huggingface_version
+
+ wandb_internal["is_jupyter_run"] = telemetry_record.env.jupyter
+ wandb_internal["is_kaggle_kernel"] = telemetry_record.env.kaggle
+ wandb_internal["start_time"] = start_time_millis
+
+ # The full telemetry record.
+ wandb_internal["t"] = proto_util.proto_encode_to_dict(telemetry_record)
+
+ ###################################################
+ # Metrics
+ ###################################################
+ if metric_pbdicts:
+ wandb_internal["m"] = metric_pbdicts
+
+ ###################################################
+ # Environment
+ ###################################################
+ writer_id = environment_record.writer_id
+ if writer_id:
+ environment_dict = proto_util.message_to_dict(environment_record)
+ wandb_internal["e"] = {writer_id: environment_dict}
+
+ return BackendConfigDict(
+ {
+ key: {
+ # Configurations can be stored in a hand-written YAML file,
+ # and users can add descriptions to their hyperparameters
+ # there. However, we don't support a way to set descriptions
+ # via code, so this is always None.
+ "desc": None,
+ "value": value,
+ }
+ for key, value in self._tree.items()
+ }
+ )
+
+ def _update_at_path(
+ self,
+ key_path: Sequence[str],
+ value: Any,
+ ) -> None:
+ """Sets the value at the path in the config tree."""
+ subtree = _subtree(self._tree, key_path[:-1], create=True)
+ assert subtree is not None
+
+ subtree[key_path[-1]] = value
+
+ def _delete_at_path(
+ self,
+ key_path: Sequence[str],
+ ) -> None:
+ """Removes the subtree at the path in the config tree."""
+ subtree = _subtree(self._tree, key_path[:-1], create=False)
+ if subtree:
+ del subtree[key_path[-1]]
+
+
+def _key_path(config_item: wandb_internal_pb2.ConfigItem) -> Sequence[str]:
+ """Returns the key path referenced by the config item."""
+ if config_item.nested_key:
+ return config_item.nested_key
+ elif config_item.key:
+ return [config_item.key]
+ else:
+ raise AssertionError(
+ "Invalid ConfigItem: either key or nested_key must be set",
+ )
+
+
+def _subtree(
+ tree: Dict[str, Any],
+ key_path: Sequence[str],
+ *,
+ create: bool = False,
+) -> Optional[Dict[str, Any]]:
+ """Returns a subtree at the given path."""
+ for key in key_path:
+ subtree = tree.get(key)
+
+ if not subtree:
+ if create:
+ subtree = {}
+ tree[key] = subtree
+ else:
+ return None
+
+ tree = subtree
+
+ return tree
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/settings_static.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/settings_static.py
new file mode 100644
index 0000000000000000000000000000000000000000..009f6db1d552170b8740112965b55101f8b1109d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/settings_static.py
@@ -0,0 +1,40 @@
+from __future__ import annotations
+
+from typing import Any, Iterable
+
+from wandb.sdk.wandb_settings import Settings
+
+
+class SettingsStatic(Settings):
+ """A readonly object that wraps a protobuf Settings message.
+
+ Implements the mapping protocol, so you can access settings as
+ attributes or items.
+ """
+
+ def __init__(self, data: dict[str, Any]) -> None:
+ super().__init__(**data)
+
+ def __setattr__(self, name: str, value: object) -> None:
+ raise AttributeError("Error: SettingsStatic is a readonly object")
+
+ def __setitem__(self, key: str, val: object) -> None:
+ raise AttributeError("Error: SettingsStatic is a readonly object")
+
+ def keys(self) -> Iterable[str]:
+ return self.__dict__.keys()
+
+ def __getitem__(self, key: str) -> Any:
+ return self.__dict__[key]
+
+ def __getattr__(self, name: str) -> Any:
+ try:
+ return self.__dict__[name]
+ except KeyError:
+ raise AttributeError(f"SettingsStatic has no attribute {name}")
+
+ def __str__(self) -> str:
+ return str(self.__dict__)
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.__dict__
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/tb_watcher.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/tb_watcher.py
new file mode 100644
index 0000000000000000000000000000000000000000..67cd1b5e6aac85cdd7a93bf1d393fa55c09aefcc
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/tb_watcher.py
@@ -0,0 +1,519 @@
+"""tensorboard watcher."""
+
+import glob
+import logging
+import os
+import queue
+import socket
+import sys
+import threading
+import time
+from typing import TYPE_CHECKING, Any, Dict, List, Optional
+
+import wandb
+from wandb import util
+from wandb.plot import CustomChart
+from wandb.sdk.interface.interface import GlobStr
+from wandb.sdk.lib import filesystem
+
+from . import run as internal_run
+
+if TYPE_CHECKING:
+ from queue import PriorityQueue
+
+ from tensorboard.backend.event_processing.event_file_loader import EventFileLoader
+ from tensorboard.compat.proto.event_pb2 import ProtoEvent
+
+ from wandb.proto.wandb_internal_pb2 import RunRecord
+ from wandb.sdk.interface.interface import FilesDict
+
+ from ..interface.interface_queue import InterfaceQueue
+ from .settings_static import SettingsStatic
+
+ HistoryDict = Dict[str, Any]
+
+# Give some time for tensorboard data to be flushed
+SHUTDOWN_DELAY = 5
+ERROR_DELAY = 5
+REMOTE_FILE_TOKEN = "://"
+logger = logging.getLogger(__name__)
+
+
+def _link_and_save_file(
+ path: str, base_path: str, interface: "InterfaceQueue", settings: "SettingsStatic"
+) -> None:
+ # TODO(jhr): should this logic be merged with Run.save()
+ files_dir = settings.files_dir
+ file_name = os.path.relpath(path, base_path)
+ abs_path = os.path.abspath(path)
+ wandb_path = os.path.join(files_dir, file_name)
+ filesystem.mkdir_exists_ok(os.path.dirname(wandb_path))
+ # We overwrite existing symlinks because namespaces can change in Tensorboard
+ if os.path.islink(wandb_path) and abs_path != os.readlink(wandb_path):
+ os.remove(wandb_path)
+ os.symlink(abs_path, wandb_path)
+ elif not os.path.exists(wandb_path):
+ os.symlink(abs_path, wandb_path)
+ # TODO(jhr): need to figure out policy, live/throttled?
+ interface.publish_files(dict(files=[(GlobStr(glob.escape(file_name)), "live")]))
+
+
+def is_tfevents_file_created_by(
+ path: str, hostname: Optional[str], start_time: Optional[float]
+) -> bool:
+ """Check if a path is a tfevents file.
+
+ Optionally checks that it was created by [hostname] after [start_time].
+
+ tensorboard tfevents filename format:
+ https://github.com/tensorflow/tensorboard/blob/f3f26b46981da5bd46a5bb93fcf02d9eb7608bc1/tensorboard/summary/writer/event_file_writer.py#L81
+ tensorflow tfevents filename format:
+ https://github.com/tensorflow/tensorflow/blob/8f597046dc30c14b5413813d02c0e0aed399c177/tensorflow/core/util/events_writer.cc#L68
+ """
+ if not path:
+ raise ValueError("Path must be a nonempty string")
+ basename = os.path.basename(path)
+ if basename.endswith((".profile-empty", ".sagemaker-uploaded")):
+ return False
+ fname_components = basename.split(".")
+ try:
+ tfevents_idx = fname_components.index("tfevents")
+ except ValueError:
+ return False
+ # check the hostname, which may have dots
+ if hostname is not None:
+ for i, part in enumerate(hostname.split(".")):
+ try:
+ fname_component_part = fname_components[tfevents_idx + 2 + i]
+ except IndexError:
+ return False
+ if part != fname_component_part:
+ return False
+ if start_time is not None:
+ try:
+ created_time = int(fname_components[tfevents_idx + 1])
+ except (ValueError, IndexError):
+ return False
+ # Ensure that the file is newer then our start time, and that it was
+ # created from the same hostname.
+ # TODO: we should also check the PID (also contained in the tfevents
+ # filename). Can we assume that our parent pid is the user process
+ # that wrote these files?
+ if created_time < int(start_time):
+ return False
+ return True
+
+
+class TBWatcher:
+ _logdirs: "Dict[str, TBDirWatcher]"
+ _watcher_queue: "PriorityQueue"
+
+ def __init__(
+ self,
+ settings: "SettingsStatic",
+ run_proto: "RunRecord",
+ interface: "InterfaceQueue",
+ force: bool = False,
+ ) -> None:
+ self._logdirs = {}
+ self._consumer: Optional[TBEventConsumer] = None
+ self._settings = settings
+ self._interface = interface
+ self._run_proto = run_proto
+ self._force = force
+ # TODO(jhr): do we need locking in this queue?
+ self._watcher_queue = queue.PriorityQueue()
+ wandb.tensorboard.reset_state() # type: ignore
+
+ def _calculate_namespace(self, logdir: str, rootdir: str) -> Optional[str]:
+ namespace: Optional[str]
+ dirs = list(self._logdirs) + [logdir]
+
+ if os.path.isfile(logdir):
+ filename = os.path.basename(logdir)
+ else:
+ filename = ""
+
+ if rootdir == "":
+ rootdir = util.to_forward_slash_path(
+ os.path.dirname(os.path.commonprefix(dirs))
+ )
+ # Tensorboard loads all tfevents files in a directory and prepends
+ # their values with the path. Passing namespace to log allows us
+ # to nest the values in wandb
+ # Note that we strip '/' instead of os.sep, because elsewhere we've
+ # converted paths to forward slash.
+ namespace = logdir.replace(filename, "").replace(rootdir, "").strip("/")
+
+ # TODO: revisit this heuristic, it exists because we don't know the
+ # root log directory until more than one tfevents file is written to
+ if len(dirs) == 1 and namespace not in ["train", "validation"]:
+ namespace = None
+ else:
+ namespace = logdir.replace(filename, "").replace(rootdir, "").strip("/")
+
+ return namespace
+
+ def add(self, logdir: str, save: bool, root_dir: str) -> None:
+ logdir = util.to_forward_slash_path(logdir)
+ root_dir = util.to_forward_slash_path(root_dir)
+ if logdir in self._logdirs:
+ return
+ namespace = self._calculate_namespace(logdir, root_dir)
+ # TODO(jhr): implement the deferred tbdirwatcher to find namespace
+
+ if not self._consumer:
+ self._consumer = TBEventConsumer(
+ self, self._watcher_queue, self._run_proto, self._settings
+ )
+ self._consumer.start()
+
+ tbdir_watcher = TBDirWatcher(
+ self, logdir, save, namespace, self._watcher_queue, self._force
+ )
+ self._logdirs[logdir] = tbdir_watcher
+ tbdir_watcher.start()
+
+ def finish(self) -> None:
+ for tbdirwatcher in self._logdirs.values():
+ tbdirwatcher.shutdown()
+ for tbdirwatcher in self._logdirs.values():
+ tbdirwatcher.finish()
+ if self._consumer:
+ self._consumer.finish()
+
+
+class TBDirWatcher:
+ def __init__(
+ self,
+ tbwatcher: "TBWatcher",
+ logdir: str,
+ save: bool,
+ namespace: Optional[str],
+ queue: "PriorityQueue",
+ force: bool = False,
+ ) -> None:
+ self.directory_watcher = util.get_module(
+ "tensorboard.backend.event_processing.directory_watcher",
+ required="Please install tensorboard package",
+ )
+ # self.event_file_loader = util.get_module(
+ # "tensorboard.backend.event_processing.event_file_loader",
+ # required="Please install tensorboard package",
+ # )
+ self.tf_compat = util.get_module(
+ "tensorboard.compat", required="Please install tensorboard package"
+ )
+ self._tbwatcher = tbwatcher
+ self._generator = self.directory_watcher.DirectoryWatcher(
+ logdir, self._loader(save, namespace), self._is_our_tfevents_file
+ )
+ self._thread = threading.Thread(target=self._thread_except_body)
+ self._first_event_timestamp = None
+ self._shutdown = threading.Event()
+ self._queue = queue
+ self._file_version = None
+ self._namespace = namespace
+ self._logdir = logdir
+ self._hostname = socket.gethostname()
+ self._force = force
+ self._process_events_lock = threading.Lock()
+
+ def start(self) -> None:
+ self._thread.start()
+
+ def _is_our_tfevents_file(self, path: str) -> bool:
+ """Check if a path has been modified since launch and contains tfevents."""
+ if not path:
+ raise ValueError("Path must be a nonempty string")
+ path = self.tf_compat.tf.compat.as_str_any(path)
+ if self._force:
+ return is_tfevents_file_created_by(path, None, None)
+ else:
+ return is_tfevents_file_created_by(
+ path, self._hostname, self._tbwatcher._settings.x_start_time
+ )
+
+ def _loader(
+ self, save: bool = True, namespace: Optional[str] = None
+ ) -> "EventFileLoader":
+ """Incredibly hacky class generator to optionally save / prefix tfevent files."""
+ _loader_interface = self._tbwatcher._interface
+ _loader_settings = self._tbwatcher._settings
+ try:
+ from tensorboard.backend.event_processing import event_file_loader
+ except ImportError:
+ raise Exception("Please install tensorboard package")
+
+ class EventFileLoader(event_file_loader.EventFileLoader):
+ def __init__(self, file_path: str) -> None:
+ super().__init__(file_path)
+ if save:
+ if REMOTE_FILE_TOKEN in file_path:
+ logger.warning(
+ "Not persisting remote tfevent file: %s", file_path
+ )
+ else:
+ # TODO: save plugins?
+ logdir = os.path.dirname(file_path)
+ parts = list(os.path.split(logdir))
+ if namespace and parts[-1] == namespace:
+ parts.pop()
+ logdir = os.path.join(*parts)
+ _link_and_save_file(
+ path=file_path,
+ base_path=logdir,
+ interface=_loader_interface,
+ settings=_loader_settings,
+ )
+
+ return EventFileLoader
+
+ def _process_events(self, shutdown_call: bool = False) -> None:
+ try:
+ with self._process_events_lock:
+ for event in self._generator.Load():
+ self.process_event(event)
+ except (
+ self.directory_watcher.DirectoryDeletedError,
+ StopIteration,
+ RuntimeError,
+ OSError,
+ ) as e:
+ # When listing s3 the directory may not yet exist, or could be empty
+ logger.debug("Encountered tensorboard directory watcher error: %s", e)
+ if not self._shutdown.is_set() and not shutdown_call:
+ time.sleep(ERROR_DELAY)
+
+ def _thread_except_body(self) -> None:
+ try:
+ self._thread_body()
+ except Exception:
+ logger.exception("generic exception in TBDirWatcher thread")
+ raise
+
+ def _thread_body(self) -> None:
+ """Check for new events every second."""
+ shutdown_time: Optional[float] = None
+ while True:
+ self._process_events()
+ if self._shutdown.is_set():
+ now = time.time()
+ if not shutdown_time:
+ shutdown_time = now + SHUTDOWN_DELAY
+ elif now > shutdown_time:
+ break
+ time.sleep(1)
+
+ def process_event(self, event: "ProtoEvent") -> None:
+ # print("\nEVENT:::", self._logdir, self._namespace, event, "\n")
+ if self._first_event_timestamp is None:
+ self._first_event_timestamp = event.wall_time
+
+ if event.HasField("file_version"):
+ self._file_version = event.file_version
+
+ if event.HasField("summary"):
+ self._queue.put(Event(event, self._namespace))
+
+ def shutdown(self) -> None:
+ self._process_events(shutdown_call=True)
+ self._shutdown.set()
+
+ def finish(self) -> None:
+ self.shutdown()
+ self._thread.join()
+
+
+class Event:
+ """An event wrapper to enable priority queueing."""
+
+ def __init__(self, event: "ProtoEvent", namespace: Optional[str]):
+ self.event = event
+ self.namespace = namespace
+ self.created_at = time.time()
+
+ def __lt__(self, other: "Event") -> bool:
+ if self.event.wall_time < other.event.wall_time:
+ return True
+ return False
+
+
+class TBEventConsumer:
+ """Consume tfevents from a priority queue.
+
+ There should always only be one of these per run_manager. We wait for 10 seconds of
+ queued events to reduce the chance of multiple tfevent files triggering out of order
+ steps.
+ """
+
+ def __init__(
+ self,
+ tbwatcher: TBWatcher,
+ queue: "PriorityQueue",
+ run_proto: "RunRecord",
+ settings: "SettingsStatic",
+ delay: int = 10,
+ ) -> None:
+ self._tbwatcher = tbwatcher
+ self._queue = queue
+ self._thread = threading.Thread(target=self._thread_except_body)
+ self._shutdown = threading.Event()
+ self.tb_history = TBHistory()
+ self._delay = delay
+
+ # This is a bit of a hack to get file saving to work as it does in the user
+ # process. Since we don't have a real run object, we have to define the
+ # datatypes callback ourselves.
+ def datatypes_cb(fname: GlobStr) -> None:
+ files: FilesDict = dict(files=[(fname, "now")])
+ self._tbwatcher._interface.publish_files(files)
+
+ # this is only used for logging artifacts
+ self._internal_run = internal_run.InternalRun(run_proto, settings, datatypes_cb)
+ self._internal_run._set_internal_run_interface(self._tbwatcher._interface)
+
+ def start(self) -> None:
+ self._start_time = time.time()
+ self._thread.start()
+
+ def finish(self) -> None:
+ self._delay = 0
+ self._shutdown.set()
+ self._thread.join()
+ while not self._queue.empty():
+ event = self._queue.get(True, 1)
+ if event:
+ self._handle_event(event, history=self.tb_history)
+ items = self.tb_history._get_and_reset()
+ for item in items:
+ self._save_row(
+ item,
+ )
+
+ def _thread_except_body(self) -> None:
+ try:
+ self._thread_body()
+ except Exception:
+ logger.exception("generic exception in TBEventConsumer thread")
+ raise
+
+ def _thread_body(self) -> None:
+ while True:
+ try:
+ event = self._queue.get(True, 1)
+ # Wait self._delay seconds from consumer start before logging events
+ if (
+ time.time() < self._start_time + self._delay
+ and not self._shutdown.is_set()
+ ):
+ self._queue.put(event)
+ time.sleep(0.1)
+ continue
+ except queue.Empty:
+ event = None
+ if self._shutdown.is_set():
+ break
+ if event:
+ self._handle_event(event, history=self.tb_history)
+ items = self.tb_history._get_and_reset()
+ for item in items:
+ self._save_row(
+ item,
+ )
+ # flush uncommitted data
+ self.tb_history._flush()
+ items = self.tb_history._get_and_reset()
+ for item in items:
+ self._save_row(item)
+
+ def _handle_event(
+ self, event: "ProtoEvent", history: Optional["TBHistory"] = None
+ ) -> None:
+ wandb.tensorboard._log( # type: ignore
+ event.event,
+ step=event.event.step,
+ namespace=event.namespace,
+ history=history,
+ )
+
+ def _save_row(self, row: "HistoryDict") -> None:
+ chart_keys = set()
+ for k, v in row.items():
+ if isinstance(v, CustomChart):
+ chart_keys.add(k)
+ v.set_key(k)
+ self._tbwatcher._interface.publish_config(
+ key=v.spec.config_key,
+ val=v.spec.config_value,
+ )
+
+ for k in chart_keys:
+ chart = row.pop(k)
+ if isinstance(chart, CustomChart):
+ row[chart.spec.table_key] = chart.table
+
+ self._tbwatcher._interface.publish_history(
+ self._internal_run,
+ row,
+ publish_step=False,
+ )
+
+
+class TBHistory:
+ _data: "HistoryDict"
+ _added: "List[HistoryDict]"
+
+ def __init__(self) -> None:
+ self._step = 0
+ self._step_size = 0
+ self._data = dict()
+ self._added = []
+
+ def _flush(self) -> None:
+ if not self._data:
+ return
+ # A single tensorboard step may have too much data
+ # we just drop the largest keys in the step if it does.
+ # TODO: we could flush the data across multiple steps
+ if self._step_size > util.MAX_LINE_BYTES:
+ metrics = [(k, sys.getsizeof(v)) for k, v in self._data.items()]
+ metrics.sort(key=lambda t: t[1], reverse=True)
+ bad = 0
+ dropped_keys = []
+ for k, v in metrics:
+ # TODO: (cvp) Added a buffer of 100KiB, this feels rather brittle.
+ if self._step_size - bad < util.MAX_LINE_BYTES - 100000:
+ break
+ else:
+ bad += v
+ dropped_keys.append(k)
+ del self._data[k]
+ wandb.termwarn(
+ f"Step {self._step} exceeds max data limit, dropping {len(dropped_keys)} of the largest keys:"
+ )
+ print("\t" + ("\n\t".join(dropped_keys))) # noqa: T201
+ self._data["_step"] = self._step
+ self._added.append(self._data)
+ self._step += 1
+ self._step_size = 0
+
+ def add(self, d: "HistoryDict") -> None:
+ self._flush()
+ self._data = dict()
+ self._data.update(self._track_history_dict(d))
+
+ def _track_history_dict(self, d: "HistoryDict") -> "HistoryDict":
+ e = {}
+ for k in d.keys():
+ e[k] = d[k]
+ self._step_size += sys.getsizeof(e[k])
+ return e
+
+ def _row_update(self, d: "HistoryDict") -> None:
+ self._data.update(self._track_history_dict(d))
+
+ def _get_and_reset(self) -> "List[HistoryDict]":
+ added = self._added[:]
+ self._added = []
+ return added
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/thread_local_settings.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/thread_local_settings.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ee0e74cc44151617cb90e7eb45996e0d1a3859d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/internal/thread_local_settings.py
@@ -0,0 +1,18 @@
+import threading
+from typing import Dict, Optional
+
+
+# Context variable for setting API settings (api keys, etc.) for internal and public apis thread-locally
+# TODO: move this into actual settings
+class _ThreadLocalApiSettings(threading.local):
+ api_key: Optional[str]
+ cookies: Optional[Dict]
+ headers: Optional[Dict]
+
+ def __init__(self) -> None:
+ self.api_key = None
+ self.cookies = None
+ self.headers = None
+
+
+_thread_local_api_settings: _ThreadLocalApiSettings = _ThreadLocalApiSettings()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e904eff616c9977433debc96586b56665825708
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/__init__.py
@@ -0,0 +1,15 @@
+from ._launch import create_and_run_agent, launch
+from ._launch_add import launch_add
+from .agent.agent import LaunchAgent
+from .inputs.manage import manage_config_file, manage_wandb_config
+from .utils import load_wandb_config
+
+__all__ = [
+ "create_and_run_agent",
+ "LaunchAgent",
+ "launch",
+ "launch_add",
+ "load_wandb_config",
+ "manage_config_file",
+ "manage_wandb_config",
+]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/_launch.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/_launch.py
new file mode 100644
index 0000000000000000000000000000000000000000..a52e7efc95a40a23e1ba8556b81f1192da12c50d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/_launch.py
@@ -0,0 +1,331 @@
+import asyncio
+import logging
+import os
+import sys
+from typing import Any, Dict, List, Optional, Tuple
+
+import yaml
+
+import wandb
+from wandb.apis.internal import Api
+
+from . import loader
+from ._project_spec import LaunchProject
+from .agent import LaunchAgent
+from .agent.agent import construct_agent_configs
+from .environment.local_environment import LocalEnvironment
+from .errors import ExecutionError, LaunchError
+from .runner.abstract import AbstractRun
+from .utils import (
+ LAUNCH_CONFIG_FILE,
+ PROJECT_SYNCHRONOUS,
+ construct_launch_spec,
+ validate_launch_spec_source,
+)
+
+_logger = logging.getLogger(__name__)
+
+
+def set_launch_logfile(logfile: str) -> None:
+ """Set the logfile for the launch agent."""
+ # Get logger of parent module
+ _launch_logger = logging.getLogger("wandb.sdk.launch")
+ if logfile == "-":
+ logfile_stream = sys.stdout
+ else:
+ try:
+ logfile_stream = open(logfile, "w")
+ # check if file is writable
+ except Exception as e:
+ wandb.termerror(
+ f"Could not open {logfile} for writing logs. Please check "
+ f"the path and permissions.\nError: {e}"
+ )
+ return
+
+ wandb.termlog(
+ f"Internal agent logs printing to {'stdout' if logfile == '-' else logfile}. "
+ )
+ handler = logging.StreamHandler(logfile_stream)
+ handler.formatter = logging.Formatter(
+ "%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d "
+ "[%(filename)s:%(funcName)s():%(lineno)s] %(message)s"
+ )
+ _launch_logger.addHandler(handler)
+ _launch_logger.log(logging.INFO, "Internal agent logs printing to %s", logfile)
+
+
+def resolve_agent_config(
+ entity: Optional[str],
+ max_jobs: Optional[int],
+ queues: Optional[Tuple[str]],
+ config: Optional[str],
+ verbosity: Optional[int],
+) -> Tuple[Dict[str, Any], Api]:
+ """Resolve the agent config.
+
+ Arguments:
+ api (Api): The api.
+ entity (str): The entity.
+ max_jobs (int): The max number of jobs.
+ queues (Tuple[str]): The queues.
+ config (str): The config.
+ verbosity (int): How verbose to print, 0 or None = default, 1 = print status every 20 seconds, 2 = also print debugging information
+
+ Returns:
+ Tuple[Dict[str, Any], Api]: The resolved config and api.
+ """
+ defaults = {
+ "max_jobs": 1,
+ "max_schedulers": 1,
+ "queues": [],
+ "registry": {},
+ "builder": {},
+ "verbosity": 0,
+ }
+ resolved_config: Dict[str, Any] = defaults
+ config_path = config or os.path.expanduser(LAUNCH_CONFIG_FILE)
+ if os.path.isfile(config_path):
+ launch_config = {}
+ with open(config_path) as f:
+ try:
+ launch_config = yaml.safe_load(f)
+ # This is considered unreachable by mypy, but it's not.
+ if launch_config is None:
+ launch_config = {} # type: ignore
+ except yaml.YAMLError as e:
+ raise LaunchError(f"Invalid launch agent config: {e}")
+ resolved_config.update(launch_config.items())
+ elif config is not None:
+ raise LaunchError(
+ f"Could not find use specified launch config file: {config_path}"
+ )
+ if os.environ.get("WANDB_ENTITY") is not None:
+ resolved_config.update({"entity": os.environ.get("WANDB_ENTITY")})
+ if os.environ.get("WANDB_LAUNCH_MAX_JOBS") is not None:
+ resolved_config.update(
+ {"max_jobs": int(os.environ.get("WANDB_LAUNCH_MAX_JOBS", 1))}
+ )
+
+ if entity is not None:
+ resolved_config.update({"entity": entity})
+ if max_jobs is not None:
+ resolved_config.update({"max_jobs": int(max_jobs)})
+ if queues:
+ resolved_config.update({"queues": list(queues)})
+ if verbosity:
+ resolved_config.update({"verbosity": int(verbosity)})
+ # queue -> queues
+ if resolved_config.get("queue"):
+ if isinstance(resolved_config.get("queue"), str):
+ resolved_config["queues"].append(resolved_config["queue"])
+ else:
+ msg = (
+ "Invalid launch agent config for key 'queue' with type: {type(resolved_config.get('queue'))} "
+ "(expected str). Specify multiple queues with the 'queues' key"
+ )
+ raise LaunchError(msg)
+
+ keys = ["entity"]
+ settings = {
+ k: resolved_config.get(k) for k in keys if resolved_config.get(k) is not None
+ }
+
+ api = Api(default_settings=settings)
+
+ if resolved_config.get("entity") is None:
+ resolved_config.update({"entity": api.default_entity})
+
+ return resolved_config, api
+
+
+def create_and_run_agent(
+ api: Api,
+ config: Dict[str, Any],
+) -> None:
+ try:
+ from wandb.sdk.launch.agent import config as agent_config
+ except ModuleNotFoundError:
+ raise LaunchError(
+ "wandb launch-agent requires pydantic to be installed. "
+ "Please install with `pip install wandb[launch]`"
+ )
+ try:
+ agent_config.AgentConfig(**config)
+ except agent_config.ValidationError as e:
+ errors = e.errors()
+ for error in errors:
+ loc = ".".join([str(x) for x in error.get("loc", [])])
+ msg = f"Agent config error in field {loc}"
+ value = error.get("input")
+ if not isinstance(value, dict):
+ msg += f" (value: {value})"
+ msg += f": {error['msg']}"
+ wandb.termerror(msg)
+ raise LaunchError("Invalid launch agent config")
+ agent = LaunchAgent(api, config)
+ try:
+ asyncio.run(agent.loop())
+ except asyncio.CancelledError:
+ pass
+
+
+async def _launch(
+ api: Api,
+ job: Optional[str] = None,
+ name: Optional[str] = None,
+ project: Optional[str] = None,
+ entity: Optional[str] = None,
+ docker_image: Optional[str] = None,
+ entry_point: Optional[List[str]] = None,
+ version: Optional[str] = None,
+ resource: Optional[str] = None,
+ resource_args: Optional[Dict[str, Any]] = None,
+ launch_config: Optional[Dict[str, Any]] = None,
+ synchronous: Optional[bool] = None,
+ run_id: Optional[str] = None,
+ repository: Optional[str] = None,
+) -> AbstractRun:
+ """Helper that delegates to the project-running method corresponding to the passed-in backend."""
+ if launch_config is None:
+ launch_config = {}
+ if resource is None:
+ resource = "local-container"
+ launch_spec = construct_launch_spec(
+ None,
+ job,
+ api,
+ name,
+ project,
+ entity,
+ docker_image,
+ resource,
+ entry_point,
+ version,
+ resource_args,
+ launch_config,
+ run_id,
+ repository,
+ author=None,
+ )
+ validate_launch_spec_source(launch_spec)
+ launch_project = LaunchProject.from_spec(launch_spec, api)
+ launch_project.fetch_and_validate_project()
+ entrypoint = launch_project.get_job_entry_point()
+ image_uri = (
+ launch_project.docker_image or launch_project.job_base_image
+ ) # Either set by user or None.
+
+ # construct runner config.
+ runner_config: Dict[str, Any] = {}
+ runner_config[PROJECT_SYNCHRONOUS] = synchronous
+
+ config = launch_config or {}
+ environment_config, build_config, registry_config = construct_agent_configs(config)
+ environment = loader.environment_from_config(environment_config)
+ if environment is not None and not isinstance(environment, LocalEnvironment):
+ await environment.verify()
+ registry = loader.registry_from_config(registry_config, environment)
+ builder = loader.builder_from_config(build_config, environment, registry)
+ if not (launch_project.docker_image or launch_project.job_base_image):
+ assert entrypoint
+ image_uri = await builder.build_image(launch_project, entrypoint, None)
+ backend = loader.runner_from_config(
+ resource, api, runner_config, environment, registry
+ )
+ if backend:
+ assert image_uri
+ submitted_run = await backend.run(launch_project, image_uri)
+ # this check will always pass, run is only optional in the agent case where
+ # a run queue id is present on the backend config
+ assert submitted_run
+ return submitted_run
+ else:
+ raise ExecutionError(
+ f"Unavailable backend {resource}, available backends: {', '.join(loader.WANDB_RUNNERS)}"
+ )
+
+
+def launch(
+ api: Api,
+ job: Optional[str] = None,
+ entry_point: Optional[List[str]] = None,
+ version: Optional[str] = None,
+ name: Optional[str] = None,
+ resource: Optional[str] = None,
+ resource_args: Optional[Dict[str, Any]] = None,
+ project: Optional[str] = None,
+ entity: Optional[str] = None,
+ docker_image: Optional[str] = None,
+ config: Optional[Dict[str, Any]] = None,
+ synchronous: Optional[bool] = True,
+ run_id: Optional[str] = None,
+ repository: Optional[str] = None,
+) -> AbstractRun:
+ """Launch a W&B launch experiment.
+
+ Arguments:
+ job: string reference to a wandb.Job eg: wandb/test/my-job:latest
+ api: An instance of a wandb Api from wandb.apis.internal.
+ entry_point: Entry point to run within the project. Defaults to using the entry point used
+ in the original run for wandb URIs, or main.py for git repository URIs.
+ version: For Git-based projects, either a commit hash or a branch name.
+ name: Name run under which to launch the run.
+ resource: Execution backend for the run.
+ resource_args: Resource related arguments for launching runs onto a remote backend.
+ Will be stored on the constructed launch config under ``resource_args``.
+ project: Target project to send launched run to
+ entity: Target entity to send launched run to
+ config: A dictionary containing the configuration for the run. May also contain
+ resource specific arguments under the key "resource_args".
+ synchronous: Whether to block while waiting for a run to complete. Defaults to True.
+ Note that if ``synchronous`` is False and ``backend`` is "local-container", this
+ method will return, but the current process will block when exiting until
+ the local run completes. If the current process is interrupted, any
+ asynchronous runs launched via this method will be terminated. If
+ ``synchronous`` is True and the run fails, the current process will
+ error out as well.
+ run_id: ID for the run (To ultimately replace the :name: field)
+ repository: string name of repository path for remote registry
+
+ Example:
+ ```python
+ from wandb.sdk.launch import launch
+
+ job = "wandb/jobs/Hello World:latest"
+ params = {"epochs": 5}
+ # Run W&B project and create a reproducible docker environment
+ # on a local host
+ api = wandb.apis.internal.Api()
+ launch(api, job, parameters=params)
+ ```
+
+
+ Returns:
+ an instance of`wandb.launch.SubmittedRun` exposing information (e.g. run ID)
+ about the launched run.
+
+ Raises:
+ `wandb.exceptions.ExecutionError` If a run launched in blocking mode
+ is unsuccessful.
+ """
+ submitted_run_obj = asyncio.run(
+ _launch(
+ job=job,
+ name=name,
+ project=project,
+ entity=entity,
+ docker_image=docker_image,
+ entry_point=entry_point,
+ version=version,
+ resource=resource,
+ resource_args=resource_args,
+ launch_config=config,
+ synchronous=synchronous,
+ api=api,
+ run_id=run_id,
+ repository=repository,
+ )
+ )
+
+ return submitted_run_obj
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/_launch_add.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/_launch_add.py
new file mode 100644
index 0000000000000000000000000000000000000000..d65a638cd81b0f6ad3f456a23c648bd025d99f98
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/_launch_add.py
@@ -0,0 +1,255 @@
+import asyncio
+import pprint
+from typing import Any, Dict, List, Optional, Union
+
+import wandb
+import wandb.apis.public as public
+from wandb.apis.internal import Api
+from wandb.errors import CommError
+from wandb.sdk.launch.builder.build import build_image_from_project
+from wandb.sdk.launch.errors import LaunchError
+from wandb.sdk.launch.utils import (
+ LAUNCH_DEFAULT_PROJECT,
+ LOG_PREFIX,
+ construct_launch_spec,
+ validate_launch_spec_source,
+)
+
+from ._project_spec import LaunchProject
+
+
+def push_to_queue(
+ api: Api,
+ queue_name: str,
+ launch_spec: Dict[str, Any],
+ template_variables: Optional[dict],
+ project_queue: str,
+ priority: Optional[int] = None,
+) -> Any:
+ return api.push_to_run_queue(
+ queue_name, launch_spec, template_variables, project_queue, priority
+ )
+
+
+def launch_add(
+ uri: Optional[str] = None,
+ job: Optional[str] = None,
+ config: Optional[Dict[str, Any]] = None,
+ template_variables: Optional[Dict[str, Union[float, int, str]]] = None,
+ project: Optional[str] = None,
+ entity: Optional[str] = None,
+ queue_name: Optional[str] = None,
+ resource: Optional[str] = None,
+ entry_point: Optional[List[str]] = None,
+ name: Optional[str] = None,
+ version: Optional[str] = None,
+ docker_image: Optional[str] = None,
+ project_queue: Optional[str] = None,
+ resource_args: Optional[Dict[str, Any]] = None,
+ run_id: Optional[str] = None,
+ build: Optional[bool] = False,
+ repository: Optional[str] = None,
+ sweep_id: Optional[str] = None,
+ author: Optional[str] = None,
+ priority: Optional[int] = None,
+) -> "public.QueuedRun":
+ """Enqueue a W&B launch experiment. With either a source uri, job or docker_image.
+
+ Arguments:
+ uri: URI of experiment to run. A wandb run uri or a Git repository URI.
+ job: string reference to a wandb.Job eg: wandb/test/my-job:latest
+ config: A dictionary containing the configuration for the run. May also contain
+ resource specific arguments under the key "resource_args"
+ template_variables: A dictionary containing values of template variables for a run queue.
+ Expected format of `{"VAR_NAME": VAR_VALUE}`
+ project: Target project to send launched run to
+ entity: Target entity to send launched run to
+ queue: the name of the queue to enqueue the run to
+ priority: the priority level of the job, where 1 is the highest priority
+ resource: Execution backend for the run: W&B provides built-in support for "local-container" backend
+ entry_point: Entry point to run within the project. Defaults to using the entry point used
+ in the original run for wandb URIs, or main.py for git repository URIs.
+ name: Name run under which to launch the run.
+ version: For Git-based projects, either a commit hash or a branch name.
+ docker_image: The name of the docker image to use for the run.
+ resource_args: Resource related arguments for launching runs onto a remote backend.
+ Will be stored on the constructed launch config under ``resource_args``.
+ run_id: optional string indicating the id of the launched run
+ build: optional flag defaulting to false, requires queue to be set
+ if build, an image is created, creates a job artifact, pushes a reference
+ to that job artifact to queue
+ repository: optional string to control the name of the remote repository, used when
+ pushing images to a registry
+ project_queue: optional string to control the name of the project for the queue. Primarily used
+ for back compatibility with project scoped queues
+
+
+ Example:
+ ```python
+ from wandb.sdk.launch import launch_add
+
+ project_uri = "https://github.com/wandb/examples"
+ params = {"alpha": 0.5, "l1_ratio": 0.01}
+ # Run W&B project and create a reproducible docker environment
+ # on a local host
+ api = wandb.apis.internal.Api()
+ launch_add(uri=project_uri, parameters=params)
+ ```
+
+
+ Returns:
+ an instance of`wandb.api.public.QueuedRun` which gives information about the
+ queued run, or if `wait_until_started` or `wait_until_finished` are called, gives access
+ to the underlying Run information.
+
+ Raises:
+ `wandb.exceptions.LaunchError` if unsuccessful
+ """
+ api = Api()
+
+ return _launch_add(
+ api,
+ job,
+ config,
+ template_variables,
+ project,
+ entity,
+ queue_name,
+ resource,
+ entry_point,
+ name,
+ version,
+ docker_image,
+ project_queue,
+ resource_args,
+ run_id=run_id,
+ build=build,
+ repository=repository,
+ sweep_id=sweep_id,
+ author=author,
+ priority=priority,
+ )
+
+
+def _launch_add(
+ api: Api,
+ job: Optional[str],
+ config: Optional[Dict[str, Any]],
+ template_variables: Optional[dict],
+ project: Optional[str],
+ entity: Optional[str],
+ queue_name: Optional[str],
+ resource: Optional[str],
+ entry_point: Optional[List[str]],
+ name: Optional[str],
+ version: Optional[str],
+ docker_image: Optional[str],
+ project_queue: Optional[str],
+ resource_args: Optional[Dict[str, Any]] = None,
+ run_id: Optional[str] = None,
+ build: Optional[bool] = False,
+ repository: Optional[str] = None,
+ sweep_id: Optional[str] = None,
+ author: Optional[str] = None,
+ priority: Optional[int] = None,
+) -> "public.QueuedRun":
+ launch_spec = construct_launch_spec(
+ None,
+ job,
+ api,
+ name,
+ project,
+ entity,
+ docker_image,
+ resource,
+ entry_point,
+ version,
+ resource_args,
+ config,
+ run_id,
+ repository,
+ author,
+ sweep_id,
+ )
+
+ if build:
+ if resource == "local-process":
+ raise LaunchError(
+ "Cannot build a docker image for the resource: local-process"
+ )
+
+ if launch_spec.get("job") is not None:
+ wandb.termwarn("Build doesn't support setting a job. Overwriting job.")
+ launch_spec["job"] = None
+
+ launch_project = LaunchProject.from_spec(launch_spec, api)
+ docker_image_uri = asyncio.run(
+ build_image_from_project(launch_project, api, config or {})
+ )
+ run = wandb.run or wandb.init(
+ project=launch_spec["project"],
+ entity=launch_spec["entity"],
+ job_type="launch_job",
+ )
+
+ job_artifact = run._log_job_artifact_with_image( # type: ignore
+ docker_image_uri, launch_project.override_args
+ )
+ job_name = job_artifact.wait().name
+
+ job = f"{launch_spec['entity']}/{launch_spec['project']}/{job_name}"
+ launch_spec["job"] = job
+ launch_spec["uri"] = None # Remove given URI --> now in job
+
+ if queue_name is None:
+ queue_name = "default"
+ if project_queue is None:
+ project_queue = LAUNCH_DEFAULT_PROJECT
+ spec_template_vars = launch_spec.get("template_variables")
+ if isinstance(spec_template_vars, dict):
+ launch_spec.pop("template_variables")
+ if template_variables is None:
+ template_variables = spec_template_vars
+ else:
+ template_variables = {
+ **spec_template_vars,
+ **template_variables,
+ }
+
+ validate_launch_spec_source(launch_spec)
+ res = push_to_queue(
+ api, queue_name, launch_spec, template_variables, project_queue, priority
+ )
+
+ if res is None or "runQueueItemId" not in res:
+ raise LaunchError("Error adding run to queue")
+
+ updated_spec = res.get("runSpec")
+ if updated_spec:
+ if updated_spec.get("resource_args"):
+ launch_spec["resource_args"] = updated_spec.get("resource_args")
+ if updated_spec.get("resource"):
+ launch_spec["resource"] = updated_spec.get("resource")
+
+ if project_queue == LAUNCH_DEFAULT_PROJECT:
+ wandb.termlog(f"{LOG_PREFIX}Added run to queue {queue_name}.")
+ else:
+ wandb.termlog(f"{LOG_PREFIX}Added run to queue {project_queue}/{queue_name}.")
+ wandb.termlog(f"{LOG_PREFIX}Launch spec:\n{pprint.pformat(launch_spec)}\n")
+
+ public_api = public.Api()
+ if job is not None:
+ try:
+ public_api._artifact(job, type="job")
+ except (ValueError, CommError) as e:
+ raise LaunchError(f"Unable to fetch job with name {job}: {e}")
+
+ queued_run = public_api.queued_run(
+ launch_spec["entity"],
+ launch_spec["project"],
+ queue_name,
+ res["runQueueItemId"],
+ project_queue,
+ priority,
+ )
+ return queued_run # type: ignore
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/_project_spec.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/_project_spec.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d7bb079bdb4a924172a2481a3cd44329865847b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/_project_spec.py
@@ -0,0 +1,565 @@
+"""Convert launch arguments into a runnable wandb launch script.
+
+Arguments can come from a launch spec or call to wandb launch.
+"""
+
+import enum
+import json
+import logging
+import os
+import shlex
+import shutil
+import tempfile
+from copy import deepcopy
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, cast
+
+import wandb
+from wandb.apis.internal import Api
+from wandb.errors import CommError
+from wandb.sdk.launch.utils import get_entrypoint_file
+from wandb.sdk.lib.runid import generate_id
+
+from .errors import LaunchError
+from .utils import LOG_PREFIX, recursive_macro_sub
+
+if TYPE_CHECKING:
+ from wandb.sdk.artifacts.artifact import Artifact
+
+_logger = logging.getLogger(__name__)
+
+
+# need to make user root for sagemaker, so users have access to /opt/ml directories
+# that let users create artifacts and access input data
+RESOURCE_UID_MAP = {"local": 1000, "sagemaker": 0}
+IMAGE_TAG_MAX_LENGTH = 32
+
+
+class LaunchSource(enum.IntEnum):
+ """Enumeration of possible sources for a launch project.
+
+ Attributes:
+ DOCKER: Source is a Docker image. This can happen if a user runs
+ `wandb launch -d `.
+ JOB: Source is a job. This is standard case.
+ SCHEDULER: Source is a wandb sweep scheduler command.
+ """
+
+ DOCKER = 1
+ JOB = 2
+ SCHEDULER = 3
+
+
+class LaunchProject:
+ """A launch project specification.
+
+ The LaunchProject is initialized from a raw launch spec an internal API
+ object. The project encapsulates logic for taking a launch spec and converting
+ it into the executable code.
+
+ The LaunchProject needs to ultimately produce a full container spec for
+ execution in docker, k8s, sagemaker, or vertex. This container spec includes:
+ - container image uri
+ - environment variables for configuring wandb etc.
+ - entrypoint command and arguments
+ - additional arguments specific to the target resource (e.g. instance type, node selector)
+
+ This class is stateful and certain methods can only be called after
+ `LaunchProject.fetch_and_validate_project()` has been called.
+
+ Notes on the entrypoint:
+ - The entrypoint is the command that will be run inside the container.
+ - The LaunchProject stores two entrypoints
+ - The job entrypoint is the entrypoint specified in the job's config.
+ - The override entrypoint is the entrypoint specified in the launch spec.
+ - The override entrypoint takes precedence over the job entrypoint.
+ """
+
+ # This init is way to long, and there are too many attributes on this sucker.
+ def __init__(
+ self,
+ uri: Optional[str],
+ job: Optional[str],
+ api: Api,
+ launch_spec: Dict[str, Any],
+ target_entity: str,
+ target_project: str,
+ name: Optional[str],
+ docker_config: Dict[str, Any],
+ git_info: Dict[str, str],
+ overrides: Dict[str, Any],
+ resource: str,
+ resource_args: Dict[str, Any],
+ run_id: Optional[str],
+ sweep_id: Optional[str] = None,
+ ):
+ self.uri = uri
+ self.job = job
+ if job is not None:
+ wandb.termlog(f"{LOG_PREFIX}Launching job: {job}")
+ self._job_artifact: Optional[Artifact] = None
+ self.api = api
+ self.launch_spec = launch_spec
+ self.target_entity = target_entity
+ self.target_project = target_project.lower()
+ self.name = name # TODO: replace with run_id
+ # the builder key can be passed in through the resource args
+ # but these resource_args are then passed to the appropriate
+ # runner, so we need to pop the builder key out
+ resource_args_copy = deepcopy(resource_args)
+ resource_args_build = resource_args_copy.get(resource, {}).pop("builder", {})
+ self.resource = resource
+ self.resource_args = resource_args_copy
+ self.sweep_id = sweep_id
+ self.author = launch_spec.get("author")
+ self.python_version: Optional[str] = launch_spec.get("python_version")
+ self._job_dockerfile: Optional[str] = None
+ self._job_build_context: Optional[str] = None
+ self._job_base_image: Optional[str] = None
+ self.accelerator_base_image: Optional[str] = resource_args_build.get(
+ "accelerator", {}
+ ).get("base_image") or resource_args_build.get("cuda", {}).get("base_image")
+ self.docker_image: Optional[str] = docker_config.get(
+ "docker_image"
+ ) or launch_spec.get("image_uri") # type: ignore [assignment]
+ self.docker_user_id = docker_config.get("user_id", 1000)
+ self._entry_point: Optional[EntryPoint] = (
+ None # todo: keep multiple entrypoint support?
+ )
+ self.init_overrides(overrides)
+ self.init_source()
+ self.init_git(git_info)
+ self.deps_type: Optional[str] = None
+ self._runtime: Optional[str] = None
+ self.run_id = run_id or generate_id()
+ self._queue_name: Optional[str] = None
+ self._queue_entity: Optional[str] = None
+ self._run_queue_item_id: Optional[str] = None
+
+ def init_source(self) -> None:
+ if self.docker_image is not None:
+ self.source = LaunchSource.DOCKER
+ self.project_dir = None
+ elif self.job is not None:
+ self.source = LaunchSource.JOB
+ self.project_dir = tempfile.mkdtemp()
+ elif self.uri and self.uri.startswith("placeholder"):
+ self.source = LaunchSource.SCHEDULER
+ self.project_dir = os.getcwd()
+ self._entry_point = self.override_entrypoint
+
+ def change_project_dir(self, new_dir: str) -> None:
+ """Change the project directory to a new directory."""
+ # Copy the contents of the old project dir to the new project dir.
+ old_dir = self.project_dir
+ if old_dir is not None:
+ shutil.copytree(
+ old_dir,
+ new_dir,
+ symlinks=True,
+ dirs_exist_ok=True,
+ ignore=shutil.ignore_patterns("fsmonitor--daemon.ipc", ".git"),
+ )
+ shutil.rmtree(old_dir)
+ self.project_dir = new_dir
+
+ def init_git(self, git_info: Dict[str, str]) -> None:
+ self.git_version = git_info.get("version")
+ self.git_repo = git_info.get("repo")
+
+ def init_overrides(self, overrides: Dict[str, Any]) -> None:
+ """Initialize override attributes for a launch project."""
+ self.overrides = overrides
+ self.override_args: List[str] = overrides.get("args", [])
+ self.override_config: Dict[str, Any] = overrides.get("run_config", {})
+ self.override_artifacts: Dict[str, Any] = overrides.get("artifacts", {})
+ self.override_files: Dict[str, Any] = overrides.get("files", {})
+ self.override_entrypoint: Optional[EntryPoint] = None
+ self.override_dockerfile: Optional[str] = overrides.get("dockerfile")
+ override_entrypoint = overrides.get("entry_point")
+ if override_entrypoint:
+ _logger.info("Adding override entry point")
+ self.override_entrypoint = EntryPoint(
+ name=get_entrypoint_file(override_entrypoint),
+ command=override_entrypoint,
+ )
+
+ def __repr__(self) -> str:
+ """String representation of LaunchProject."""
+ if self.source == LaunchSource.JOB:
+ return f"{self.job}"
+ return f"{self.uri}"
+
+ @classmethod
+ def from_spec(cls, launch_spec: Dict[str, Any], api: Api) -> "LaunchProject":
+ """Constructs a LaunchProject instance using a launch spec.
+
+ Arguments:
+ launch_spec: Dictionary representation of launch spec
+ api: Instance of wandb.apis.internal Api
+
+ Returns:
+ An initialized `LaunchProject` object
+ """
+ name: Optional[str] = None
+ if launch_spec.get("name"):
+ name = launch_spec["name"]
+ return LaunchProject(
+ launch_spec.get("uri"),
+ launch_spec.get("job"),
+ api,
+ launch_spec,
+ launch_spec["entity"],
+ launch_spec["project"],
+ name,
+ launch_spec.get("docker", {}),
+ launch_spec.get("git", {}),
+ launch_spec.get("overrides", {}),
+ launch_spec.get("resource", None), # type: ignore [arg-type]
+ launch_spec.get("resource_args", {}),
+ launch_spec.get("run_id", None),
+ launch_spec.get("sweep_id", {}),
+ )
+
+ @property
+ def job_dockerfile(self) -> Optional[str]:
+ return self._job_dockerfile
+
+ @property
+ def job_build_context(self) -> Optional[str]:
+ return self._job_build_context
+
+ @property
+ def job_base_image(self) -> Optional[str]:
+ return self._job_base_image
+
+ def set_job_dockerfile(self, dockerfile: str) -> None:
+ self._job_dockerfile = dockerfile
+
+ def set_job_build_context(self, build_context: str) -> None:
+ self._job_build_context = build_context
+
+ def set_job_base_image(self, base_image: str) -> None:
+ self._job_base_image = base_image
+
+ @property
+ def image_name(self) -> str:
+ if self.job_base_image is not None:
+ return self.job_base_image
+ if self.docker_image is not None:
+ return self.docker_image
+ elif self.uri is not None:
+ cleaned_uri = self.uri.replace("https://", "/")
+ first_sep = cleaned_uri.find("/")
+ shortened_uri = cleaned_uri[first_sep:]
+ return wandb.util.make_docker_image_name_safe(shortened_uri)
+ else:
+ # this will always pass since one of these 3 is required
+ assert self.job is not None
+ return wandb.util.make_docker_image_name_safe(self.job.split(":")[0])
+
+ @property
+ def queue_name(self) -> Optional[str]:
+ return self._queue_name
+
+ @queue_name.setter
+ def queue_name(self, value: str) -> None:
+ self._queue_name = value
+
+ @property
+ def queue_entity(self) -> Optional[str]:
+ return self._queue_entity
+
+ @queue_entity.setter
+ def queue_entity(self, value: str) -> None:
+ self._queue_entity = value
+
+ @property
+ def run_queue_item_id(self) -> Optional[str]:
+ return self._run_queue_item_id
+
+ @run_queue_item_id.setter
+ def run_queue_item_id(self, value: str) -> None:
+ self._run_queue_item_id = value
+
+ def fill_macros(self, image: str) -> Dict[str, Any]:
+ """Substitute values for macros in resource arguments.
+
+ Certain macros can be used in resource args. These macros allow the
+ user to set resource args dynamically in the context of the
+ run being launched. The macros are given in the ${macro} format. The
+ following macros are currently supported:
+
+ ${project_name} - the name of the project the run is being launched to.
+ ${entity_name} - the owner of the project the run being launched to.
+ ${run_id} - the id of the run being launched.
+ ${run_name} - the name of the run that is launching.
+ ${image_uri} - the URI of the container image for this run.
+
+ Additionally, you may use ${} to refer to the value of any
+ environment variables that you plan to set in the environment of any
+ agents that will receive these resource args.
+
+ Calling this method will overwrite the contents of self.resource_args
+ with the substituted values.
+
+ Args:
+ image (str): The image name to fill in for ${wandb-image}.
+
+ Returns:
+ Dict[str, Any]: The resource args with all macros filled in.
+ """
+ update_dict = {
+ "project_name": self.target_project,
+ "entity_name": self.target_entity,
+ "run_id": self.run_id,
+ "run_name": self.name,
+ "image_uri": image,
+ "author": self.author,
+ }
+ update_dict.update(os.environ)
+ result = recursive_macro_sub(self.resource_args, update_dict)
+ # recursive_macro_sub given a dict returns a dict with the same keys
+ # but with other input types behaves differently. The cast is for mypy.
+ return cast(Dict[str, Any], result)
+
+ def build_required(self) -> bool:
+ """Checks the source to see if a build is required."""
+ if self.job_base_image is not None:
+ return False
+ if self.source != LaunchSource.JOB:
+ return True
+ return False
+
+ @property
+ def docker_image(self) -> Optional[str]:
+ """Returns the Docker image associated with this LaunchProject.
+
+ This will only be set if an image_uri is being run outside a job.
+
+ Returns:
+ Optional[str]: The Docker image or None if not specified.
+ """
+ if self._docker_image:
+ return self._docker_image
+ return None
+
+ @docker_image.setter
+ def docker_image(self, value: str) -> None:
+ """Sets the Docker image for the project.
+
+ Args:
+ value (str): The Docker image to set.
+
+ Returns:
+ None
+ """
+ self._docker_image = value
+ self._ensure_not_docker_image_and_local_process()
+
+ def get_job_entry_point(self) -> Optional["EntryPoint"]:
+ """Returns the job entrypoint for the project."""
+ # assuming project only has 1 entry point, pull that out
+ # tmp fn until we figure out if we want to support multiple entry points or not
+ if not self._entry_point:
+ if not self.docker_image and not self.job_base_image:
+ raise LaunchError(
+ "Project must have at least one entry point unless docker image is specified."
+ )
+ return None
+ return self._entry_point
+
+ def set_job_entry_point(self, command: List[str]) -> "EntryPoint":
+ """Set job entrypoint for the project."""
+ assert self._entry_point is None, (
+ "Cannot set entry point twice. Use LaunchProject.override_entrypoint"
+ )
+ new_entrypoint = EntryPoint(name=command[-1], command=command)
+ self._entry_point = new_entrypoint
+ return new_entrypoint
+
+ def fetch_and_validate_project(self) -> None:
+ """Fetches a project into a local directory, adds the config values to the directory, and validates the first entrypoint for the project.
+
+ Arguments:
+ launch_project: LaunchProject to fetch and validate.
+ api: Instance of wandb.apis.internal Api
+
+ Returns:
+ A validated `LaunchProject` object.
+
+ """
+ if self.source == LaunchSource.DOCKER:
+ return
+ elif self.source == LaunchSource.JOB:
+ self._fetch_job()
+ assert self.project_dir is not None
+
+ # Let's make sure we document this very clearly.
+ def get_image_source_string(self) -> str:
+ """Returns a unique string identifying the source of an image."""
+ if self.source == LaunchSource.JOB:
+ assert self._job_artifact is not None
+ return f"{self._job_artifact.name}:v{self._job_artifact.version}"
+ elif self.source == LaunchSource.DOCKER:
+ assert isinstance(self.docker_image, str)
+ return self.docker_image
+ else:
+ raise LaunchError(
+ "Unknown source type when determining image source string"
+ )
+
+ def _ensure_not_docker_image_and_local_process(self) -> None:
+ """Ensure that docker image is not specified with local-process resource runner.
+
+ Raises:
+ LaunchError: If docker image is specified with local-process resource runner.
+ """
+ if self.docker_image is not None and self.resource == "local-process":
+ raise LaunchError(
+ "Cannot specify docker image with local-process resource runner"
+ )
+
+ def _fetch_job(self) -> None:
+ """Fetches the job details from the public API and configures the launch project.
+
+ Raises:
+ LaunchError: If there is an error accessing the job.
+ """
+ public_api = wandb.apis.public.Api()
+ job_dir = tempfile.mkdtemp()
+ try:
+ job = public_api.job(self.job, path=job_dir)
+ except CommError as e:
+ msg = e.message
+ raise LaunchError(
+ f"Error accessing job {self.job}: {msg} on {public_api.settings.get('base_url')}"
+ )
+ job.configure_launch_project(self) # Why is this a method of the job?
+ self._job_artifact = job._job_artifact
+
+ def get_env_vars_dict(self, api: Api, max_env_length: int) -> Dict[str, str]:
+ """Generate environment variables for the project.
+
+ Arguments:
+ launch_project: LaunchProject to generate environment variables for.
+
+ Returns:
+ Dictionary of environment variables.
+ """
+ env_vars = {}
+ env_vars["WANDB_BASE_URL"] = api.settings("base_url")
+ override_api_key = self.launch_spec.get("_wandb_api_key")
+ env_vars["WANDB_API_KEY"] = override_api_key or api.api_key
+ if self.target_project:
+ env_vars["WANDB_PROJECT"] = self.target_project
+ env_vars["WANDB_ENTITY"] = self.target_entity
+ env_vars["WANDB_LAUNCH"] = "True"
+ env_vars["WANDB_RUN_ID"] = self.run_id
+ if self.docker_image:
+ env_vars["WANDB_DOCKER"] = self.docker_image
+ if self.name is not None:
+ env_vars["WANDB_NAME"] = self.name
+ if "author" in self.launch_spec and not override_api_key:
+ env_vars["WANDB_USERNAME"] = self.launch_spec["author"]
+ if self.sweep_id:
+ env_vars["WANDB_SWEEP_ID"] = self.sweep_id
+ if self.launch_spec.get("_resume_count", 0) > 0:
+ env_vars["WANDB_RESUME"] = "allow"
+ if self.queue_name:
+ env_vars[wandb.env.LAUNCH_QUEUE_NAME] = self.queue_name
+ if self.queue_entity:
+ env_vars[wandb.env.LAUNCH_QUEUE_ENTITY] = self.queue_entity
+ if self.run_queue_item_id:
+ env_vars[wandb.env.LAUNCH_TRACE_ID] = self.run_queue_item_id
+
+ _inject_wandb_config_env_vars(self.override_config, env_vars, max_env_length)
+ _inject_file_overrides_env_vars(self.override_files, env_vars, max_env_length)
+
+ artifacts = {}
+ # if we're spinning up a launch process from a job
+ # we should tell the run to use that artifact
+ if self.job:
+ artifacts = {wandb.util.LAUNCH_JOB_ARTIFACT_SLOT_NAME: self.job}
+ env_vars["WANDB_ARTIFACTS"] = json.dumps(
+ {**artifacts, **self.override_artifacts}
+ )
+ return env_vars
+
+ def parse_existing_requirements(self) -> str:
+ from packaging.requirements import InvalidRequirement, Requirement
+
+ requirements_line = ""
+ assert self.project_dir is not None
+ base_requirements = os.path.join(self.project_dir, "requirements.txt")
+ if os.path.exists(base_requirements):
+ include_only = set()
+ with open(base_requirements) as f2:
+ for line in f2:
+ if line.strip() == "":
+ continue
+
+ try:
+ req = Requirement(line)
+ name = req.name.lower()
+ include_only.add(shlex.quote(name))
+ except InvalidRequirement:
+ _logger.warning(
+ "Unable to parse line %s in requirements.txt",
+ line,
+ exc_info=True,
+ )
+ continue
+
+ requirements_line += "WANDB_ONLY_INCLUDE={} ".format(",".join(include_only))
+ if "wandb" not in requirements_line:
+ wandb.termwarn(f"{LOG_PREFIX}wandb is not present in requirements.txt.")
+ return requirements_line
+
+
+class EntryPoint:
+ """An entry point into a wandb launch specification."""
+
+ def __init__(self, name: Optional[str], command: List[str]):
+ self.name = name
+ self.command = command
+
+ def update_entrypoint_path(self, new_path: str) -> None:
+ """Updates the entrypoint path to a new path."""
+ if len(self.command) == 2 and (
+ self.command[0].startswith("python") or self.command[0] == "bash"
+ ):
+ self.command[1] = new_path
+
+
+def _inject_wandb_config_env_vars(
+ config: Dict[str, Any], env_dict: Dict[str, Any], maximum_env_length: int
+) -> None:
+ str_config = json.dumps(config)
+ if len(str_config) <= maximum_env_length:
+ env_dict["WANDB_CONFIG"] = str_config
+ return
+
+ chunks = [
+ str_config[i : i + maximum_env_length]
+ for i in range(0, len(str_config), maximum_env_length)
+ ]
+ config_chunks_dict = {f"WANDB_CONFIG_{i}": chunk for i, chunk in enumerate(chunks)}
+ env_dict.update(config_chunks_dict)
+
+
+def _inject_file_overrides_env_vars(
+ overrides: Dict[str, Any], env_dict: Dict[str, Any], maximum_env_length: int
+) -> None:
+ str_overrides = json.dumps(overrides)
+ if len(str_overrides) <= maximum_env_length:
+ env_dict["WANDB_LAUNCH_FILE_OVERRIDES"] = str_overrides
+ return
+
+ chunks = [
+ str_overrides[i : i + maximum_env_length]
+ for i in range(0, len(str_overrides), maximum_env_length)
+ ]
+ overrides_chunks_dict = {
+ f"WANDB_LAUNCH_FILE_OVERRIDES_{i}": chunk for i, chunk in enumerate(chunks)
+ }
+ env_dict.update(overrides_chunks_dict)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/agent/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/agent/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..838a7886c290fced892b06b8fee5137cbcb278af
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/agent/__init__.py
@@ -0,0 +1,5 @@
+from .agent import LaunchAgent
+
+LaunchAgent = LaunchAgent
+
+__all__ = ["LaunchAgent"]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/agent/agent.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/agent/agent.py
new file mode 100644
index 0000000000000000000000000000000000000000..e02e035c651ae6a892f115169ba9b597ac873eaf
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/agent/agent.py
@@ -0,0 +1,931 @@
+"""Implementation of launch agent."""
+
+import asyncio
+import copy
+import logging
+import os
+import pprint
+import threading
+import time
+import traceback
+from dataclasses import dataclass
+from multiprocessing import Event
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import yaml
+
+import wandb
+from wandb.apis.internal import Api
+from wandb.errors import CommError
+from wandb.sdk.launch._launch_add import launch_add
+from wandb.sdk.launch.runner.local_container import LocalSubmittedRun
+from wandb.sdk.launch.runner.local_process import LocalProcessRunner
+from wandb.sdk.launch.sweeps.scheduler import Scheduler
+from wandb.sdk.launch.utils import LAUNCH_CONFIG_FILE, resolve_build_and_registry_config
+from wandb.sdk.lib import runid
+
+from .. import loader
+from .._project_spec import LaunchProject
+from ..errors import LaunchDockerError, LaunchError
+from ..utils import (
+ LAUNCH_DEFAULT_PROJECT,
+ LOG_PREFIX,
+ PROJECT_SYNCHRONOUS,
+ event_loop_thread_exec,
+)
+from .job_status_tracker import JobAndRunStatusTracker
+from .run_queue_item_file_saver import RunQueueItemFileSaver
+
+AGENT_POLLING_INTERVAL = 10
+RECEIVED_JOB_POLLING_INTERVAL = 0.0 # more frequent when we know we have jobs
+
+AGENT_POLLING = "POLLING"
+AGENT_RUNNING = "RUNNING"
+AGENT_KILLED = "KILLED"
+
+HIDDEN_AGENT_RUN_TYPE = "sweep-controller"
+
+MAX_RESUME_COUNT = 5
+
+RUN_INFO_GRACE_PERIOD = 60
+
+DEFAULT_STOPPED_RUN_TIMEOUT = 60
+
+DEFAULT_PRINT_INTERVAL = 5 * 60
+VERBOSE_PRINT_INTERVAL = 20
+
+_env_timeout = os.environ.get("WANDB_LAUNCH_START_TIMEOUT")
+if _env_timeout:
+ try:
+ RUN_START_TIMEOUT = float(_env_timeout)
+ except ValueError:
+ raise LaunchError(
+ f"Invalid value for WANDB_LAUNCH_START_TIMEOUT: {_env_timeout}"
+ )
+else:
+ RUN_START_TIMEOUT = 60 * 30 # default 30 minutes
+
+_logger = logging.getLogger(__name__)
+
+
+@dataclass
+class JobSpecAndQueue:
+ job: Dict[str, Any]
+ queue: str
+
+
+def _convert_access(access: str) -> str:
+ """Convert access string to a value accepted by wandb."""
+ access = access.upper()
+ assert access == "PROJECT" or access == "USER", (
+ "Queue access must be either project or user"
+ )
+ return access
+
+
+def _max_from_config(
+ config: Dict[str, Any], key: str, default: int = 1
+) -> Union[int, float]:
+ """Get an integer from the config, or float.inf if -1.
+
+ Utility for parsing integers from the agent config with a default, infinity
+ handling, and integer parsing. Raises more informative error if parse error.
+ """
+ try:
+ val = config.get(key)
+ if val is None:
+ val = default
+ max_from_config = int(val)
+ except ValueError as e:
+ raise LaunchError(
+ f"Error when parsing LaunchAgent config key: ['{key}': "
+ f"{config.get(key)}]. Error: {str(e)}"
+ )
+ if max_from_config == -1:
+ return float("inf")
+
+ if max_from_config < 0:
+ raise LaunchError(
+ f"Error when parsing LaunchAgent config key: ['{key}': "
+ f"{config.get(key)}]. Error: negative value."
+ )
+ return max_from_config
+
+
+class InternalAgentLogger:
+ def __init__(self, verbosity=0):
+ self._print_to_terminal = verbosity >= 2
+
+ def error(self, message: str):
+ if self._print_to_terminal:
+ wandb.termerror(f"{LOG_PREFIX}{message}")
+ _logger.error(f"{LOG_PREFIX}{message}")
+
+ def warn(self, message: str):
+ if self._print_to_terminal:
+ wandb.termwarn(f"{LOG_PREFIX}{message}")
+ _logger.warning(f"{LOG_PREFIX}{message}")
+
+ def info(self, message: str):
+ if self._print_to_terminal:
+ wandb.termlog(f"{LOG_PREFIX}{message}")
+ _logger.info(f"{LOG_PREFIX}{message}")
+
+ def debug(self, message: str):
+ if self._print_to_terminal:
+ wandb.termlog(f"{LOG_PREFIX}{message}")
+ _logger.debug(f"{LOG_PREFIX}{message}")
+
+
+def construct_agent_configs(
+ launch_config: Optional[Dict] = None,
+ build_config: Optional[Dict] = None,
+) -> Tuple[Optional[Dict[str, Any]], Dict[str, Any], Dict[str, Any]]:
+ registry_config = None
+ environment_config = None
+ if launch_config is not None:
+ build_config = launch_config.get("builder")
+ registry_config = launch_config.get("registry")
+
+ default_launch_config = None
+ if os.path.exists(os.path.expanduser(LAUNCH_CONFIG_FILE)):
+ with open(os.path.expanduser(LAUNCH_CONFIG_FILE)) as f:
+ default_launch_config = (
+ yaml.safe_load(f) or {}
+ ) # In case the config is empty, we want it to be {} instead of None.
+ environment_config = default_launch_config.get("environment")
+
+ build_config, registry_config = resolve_build_and_registry_config(
+ default_launch_config, build_config, registry_config
+ )
+
+ return environment_config, build_config, registry_config
+
+
+class LaunchAgent:
+ """Launch agent class which polls run given run queues and launches runs for wandb launch."""
+
+ _instance = None
+
+ def __new__(cls, *args: Any, **kwargs: Any) -> "LaunchAgent":
+ """Create a new instance of the LaunchAgent.
+
+ This method ensures that only one instance of the LaunchAgent is created.
+ This is done so that information about the agent can be accessed from
+ elsewhere in the library.
+ """
+ if cls._instance is None:
+ cls._instance = super().__new__(cls)
+ return cls._instance
+
+ @classmethod
+ def name(cls) -> str:
+ """Return the name of the agent."""
+ if cls._instance is None:
+ raise LaunchError("LaunchAgent has not been initialized")
+ name = cls._instance._name
+ if isinstance(name, str):
+ return name
+ raise LaunchError(f"Found invalid name for agent {name}")
+
+ @classmethod
+ def initialized(cls) -> bool:
+ """Return whether the agent is initialized."""
+ return cls._instance is not None
+
+ def __init__(self, api: Api, config: Dict[str, Any]):
+ """Initialize a launch agent.
+
+ Arguments:
+ api: Api object to use for making requests to the backend.
+ config: Config dictionary for the agent.
+ """
+ self._entity = config["entity"]
+ self._project = LAUNCH_DEFAULT_PROJECT
+ self._api = api
+ self._base_url = self._api.settings().get("base_url")
+ self._ticks = 0
+ self._jobs: Dict[int, JobAndRunStatusTracker] = {}
+ self._jobs_lock = threading.Lock()
+ self._jobs_event = Event()
+ self._jobs_event.set()
+ self._cwd = os.getcwd()
+ self._namespace = runid.generate_id()
+ self._access = _convert_access("project")
+ self._max_jobs = _max_from_config(config, "max_jobs")
+ self._max_schedulers = _max_from_config(config, "max_schedulers")
+ self._secure_mode = config.get("secure_mode", False)
+ self._verbosity = config.get("verbosity", 0)
+ self._internal_logger = InternalAgentLogger(verbosity=self._verbosity)
+ self._last_status_print_time = 0.0
+ self.default_config: Dict[str, Any] = config
+ self._stopped_run_timeout = config.get(
+ "stopped_run_timeout", DEFAULT_STOPPED_RUN_TIMEOUT
+ )
+ self._known_warnings: List[str] = []
+
+ # Get agent version from env var if present, otherwise wandb version
+ self.version: str = "wandb@" + wandb.__version__
+ env_agent_version = os.environ.get("WANDB_AGENT_VERSION")
+ if env_agent_version and env_agent_version != "wandb-launch-agent":
+ self.version = env_agent_version
+
+ # serverside creation
+ self.gorilla_supports_agents = (
+ self._api.launch_agent_introspection() is not None
+ )
+ self._gorilla_supports_fail_run_queue_items = (
+ self._api.fail_run_queue_item_introspection()
+ )
+
+ self._queues: List[str] = config.get("queues", ["default"])
+
+ # remove project field from agent config before sending to back end
+ # because otherwise it shows up in the config in the UI and confuses users
+ sent_config = config.copy()
+ if "project" in sent_config:
+ del sent_config["project"]
+
+ create_response = self._api.create_launch_agent(
+ self._entity,
+ self._project,
+ self._queues,
+ sent_config,
+ self.version,
+ self.gorilla_supports_agents,
+ )
+ self._id = create_response["launchAgentId"]
+ if self._api.entity_is_team(self._entity):
+ wandb.termwarn(
+ f"{LOG_PREFIX}Agent is running on team entity ({self._entity}). Members of this team will be able to run code on this device."
+ )
+
+ agent_response = self._api.get_launch_agent(
+ self._id, self.gorilla_supports_agents
+ )
+ self._name = agent_response["name"]
+ self._init_agent_run()
+
+ def _is_scheduler_job(self, run_spec: Dict[str, Any]) -> bool:
+ """Determine whether a job/runSpec is a sweep scheduler."""
+ if not run_spec:
+ self._internal_logger.debug(
+ "Received runSpec in _is_scheduler_job that was empty"
+ )
+
+ if run_spec.get("uri") != Scheduler.PLACEHOLDER_URI:
+ return False
+
+ if run_spec.get("resource") == "local-process":
+ # Any job pushed to a run queue that has a scheduler uri is
+ # allowed to use local-process
+ if run_spec.get("job"):
+ return True
+
+ # If a scheduler is local-process and run through CLI, also
+ # confirm command is in format: [wandb scheduler ]
+ cmd = run_spec.get("overrides", {}).get("entry_point", [])
+ if len(cmd) < 3:
+ return False
+
+ if cmd[:2] != ["wandb", "scheduler"]:
+ return False
+
+ return True
+
+ async def fail_run_queue_item(
+ self,
+ run_queue_item_id: str,
+ message: str,
+ phase: str,
+ files: Optional[List[str]] = None,
+ ) -> None:
+ if self._gorilla_supports_fail_run_queue_items:
+ fail_rqi = event_loop_thread_exec(self._api.fail_run_queue_item)
+ await fail_rqi(run_queue_item_id, message, phase, files)
+
+ def _init_agent_run(self) -> None:
+ # TODO: has it been long enough that all backends support agents?
+ self._wandb_run = None
+
+ if self.gorilla_supports_agents:
+ settings = wandb.Settings(
+ silent=True, disable_git=True, disable_job_creation=True
+ )
+ self._wandb_run = wandb.init(
+ project=self._project,
+ entity=self._entity,
+ settings=settings,
+ id=self._name,
+ job_type=HIDDEN_AGENT_RUN_TYPE,
+ )
+
+ @property
+ def thread_ids(self) -> List[int]:
+ """Returns a list of keys running thread ids for the agent."""
+ with self._jobs_lock:
+ return list(self._jobs.keys())
+
+ @property
+ def num_running_schedulers(self) -> int:
+ """Return just the number of schedulers."""
+ with self._jobs_lock:
+ return len([x for x in self._jobs if self._jobs[x].is_scheduler])
+
+ @property
+ def num_running_jobs(self) -> int:
+ """Return the number of jobs not including schedulers."""
+ with self._jobs_lock:
+ return len([x for x in self._jobs if not self._jobs[x].is_scheduler])
+
+ async def pop_from_queue(self, queue: str) -> Any:
+ """Pops an item off the runqueue to run as a job.
+
+ Arguments:
+ queue: Queue to pop from.
+
+ Returns:
+ Item popped off the queue.
+
+ Raises:
+ Exception: if there is an error popping from the queue.
+ """
+ try:
+ pop = event_loop_thread_exec(self._api.pop_from_run_queue)
+ ups = await pop(
+ queue,
+ entity=self._entity,
+ project=self._project,
+ agent_id=self._id,
+ )
+ return ups
+ except Exception as e:
+ print("Exception:", e)
+ return None
+
+ def print_status(self) -> None:
+ """Prints the current status of the agent."""
+ self._last_status_print_time = time.time()
+ output_str = "agent "
+ if self._name:
+ output_str += f"{self._name} "
+ if self.num_running_jobs < self._max_jobs:
+ output_str += f"polling on queues {','.join(self._queues)}, "
+ output_str += (
+ f"running {self.num_running_jobs} out of a maximum of {self._max_jobs} jobs"
+ )
+
+ wandb.termlog(f"{LOG_PREFIX}{output_str}")
+ if self.num_running_jobs > 0:
+ output_str += f": {','.join(str(job_id) for job_id in self.thread_ids)}"
+
+ _logger.info(output_str)
+
+ async def update_status(self, status: str) -> None:
+ """Update the status of the agent.
+
+ Arguments:
+ status: Status to update the agent to.
+ """
+ _update_status = event_loop_thread_exec(self._api.update_launch_agent_status)
+ update_ret = await _update_status(
+ self._id, status, self.gorilla_supports_agents
+ )
+ if not update_ret["success"]:
+ wandb.termerror(f"{LOG_PREFIX}Failed to update agent status to {status}")
+
+ def _check_run_exists_and_inited(
+ self, entity: str, project: str, run_id: str, rqi_id: str
+ ) -> bool:
+ """Checks the stateof the run to ensure it has been inited. Note this will not behave well with resuming."""
+ # Checks the _wandb key in the run config for the run queue item id. If it exists, the
+ # submitted run definitely called init. Falls back to checking state of run.
+ # TODO: handle resuming runs
+
+ # Sweep runs exist but are in pending state, normal launch runs won't exist
+ # so will raise a CommError.
+ try:
+ run_state = self._api.get_run_state(entity, project, run_id)
+ if run_state.lower() != "pending":
+ return True
+ except CommError:
+ self._internal_logger.info(
+ f"Run {entity}/{project}/{run_id} with rqi id: {rqi_id} did not have associated run",
+ )
+ return False
+
+ async def finish_thread_id(
+ self,
+ thread_id: int,
+ exception: Optional[Union[Exception, LaunchDockerError]] = None,
+ ) -> None:
+ """Removes the job from our list for now."""
+ with self._jobs_lock:
+ job_and_run_status = self._jobs[thread_id]
+
+ if (
+ job_and_run_status.entity is not None
+ and job_and_run_status.entity != self._entity
+ ):
+ self._internal_logger.info(
+ "Skipping check for completed run status because run is on a different entity than agent",
+ )
+ elif exception is not None:
+ tb_str = traceback.format_exception(
+ type(exception), value=exception, tb=exception.__traceback__
+ )
+ fnames = job_and_run_status.saver.save_contents(
+ "".join(tb_str), "error.log", "error"
+ )
+ await self.fail_run_queue_item(
+ job_and_run_status.run_queue_item_id,
+ str(exception),
+ job_and_run_status.err_stage,
+ fnames,
+ )
+ elif job_and_run_status.project is None or job_and_run_status.run_id is None:
+ self._internal_logger.info(
+ f"called finish_thread_id on thread whose tracker has no project or run id. RunQueueItemID: {job_and_run_status.run_queue_item_id}",
+ )
+ wandb.termerror(
+ "Missing project or run id on thread called finish thread id"
+ )
+ await self.fail_run_queue_item(
+ job_and_run_status.run_queue_item_id,
+ "submitted job was finished without assigned project or run id",
+ "agent",
+ )
+ elif job_and_run_status.run is not None:
+ called_init = False
+ # We do some weird stuff here getting run info to check for a
+ # created in run in W&B.
+ #
+ # We retry for 60 seconds with an exponential backoff in case
+ # upsert run is taking a while.
+ logs = None
+ interval = 1
+ while True:
+ called_init = self._check_run_exists_and_inited(
+ self._entity,
+ job_and_run_status.project,
+ job_and_run_status.run_id,
+ job_and_run_status.run_queue_item_id,
+ )
+ if called_init or interval > RUN_INFO_GRACE_PERIOD:
+ break
+ if not called_init:
+ # Fetch the logs now if we don't get run info on the
+ # first try, in case the logs are cleaned from the runner
+ # environment (e.g. k8s) during the run info grace period.
+ if interval == 1:
+ logs = await job_and_run_status.run.get_logs()
+ await asyncio.sleep(interval)
+ interval *= 2
+ if not called_init:
+ fnames = None
+ if job_and_run_status.completed_status == "finished":
+ _msg = "The submitted job exited successfully but failed to call wandb.init"
+ else:
+ _msg = "The submitted run was not successfully started"
+ if logs:
+ fnames = job_and_run_status.saver.save_contents(
+ logs, "error.log", "error"
+ )
+ await self.fail_run_queue_item(
+ job_and_run_status.run_queue_item_id, _msg, "run", fnames
+ )
+ else:
+ self._internal_logger.info(
+ f"Finish thread id {thread_id} had no exception and no run"
+ )
+ wandb._sentry.exception(
+ "launch agent called finish thread id on thread without run or exception"
+ )
+
+ # TODO: keep logs or something for the finished jobs
+ with self._jobs_lock:
+ del self._jobs[thread_id]
+
+ # update status back to polling if no jobs are running
+ if len(self.thread_ids) == 0:
+ await self.update_status(AGENT_POLLING)
+
+ async def run_job(
+ self, job: Dict[str, Any], queue: str, file_saver: RunQueueItemFileSaver
+ ) -> None:
+ """Set up project and run the job.
+
+ Arguments:
+ job: Job to run.
+ """
+ job_copy = copy.deepcopy(job)
+ if "runSpec" in job_copy and "_wandb_api_key" in job_copy["runSpec"]:
+ job_copy["runSpec"]["_wandb_api_key"] = ""
+
+ _msg = f"{LOG_PREFIX}Launch agent received job:\n{pprint.pformat(job_copy)}\n"
+ wandb.termlog(_msg)
+ _logger.info(_msg)
+ # update agent status
+ await self.update_status(AGENT_RUNNING)
+
+ # parse job
+ self._internal_logger.info("Parsing launch spec")
+ launch_spec = job["runSpec"]
+
+ # Abort if this job attempts to override secure mode
+ self._assert_secure(launch_spec)
+ job_tracker = JobAndRunStatusTracker(job["runQueueItemId"], queue, file_saver)
+
+ asyncio.create_task(
+ self.task_run_job(
+ launch_spec,
+ job,
+ self.default_config,
+ self._api,
+ job_tracker,
+ )
+ )
+
+ def _assert_secure(self, launch_spec: Dict[str, Any]) -> None:
+ """If secure mode is set, make sure no vulnerable keys are overridden."""
+ if not self._secure_mode:
+ return
+ k8s_config = launch_spec.get("resource_args", {}).get("kubernetes", {})
+
+ pod_secure_keys = ["hostPID", "hostIPC", "hostNetwork", "initContainers"]
+ pod_spec = k8s_config.get("spec", {}).get("template", {}).get("spec", {})
+ for key in pod_secure_keys:
+ if key in pod_spec:
+ raise ValueError(
+ f'This agent is configured to lock "{key}" in pod spec '
+ "but the job specification attempts to override it."
+ )
+
+ container_specs = pod_spec.get("containers", [])
+ for container_spec in container_specs:
+ if "command" in container_spec:
+ raise ValueError(
+ 'This agent is configured to lock "command" in container spec '
+ "but the job specification attempts to override it."
+ )
+
+ if launch_spec.get("overrides", {}).get("entry_point"):
+ raise ValueError(
+ 'This agent is configured to lock the "entrypoint" override '
+ "but the job specification attempts to override it."
+ )
+
+ async def loop(self) -> None:
+ """Loop infinitely to poll for jobs and run them.
+
+ Raises:
+ KeyboardInterrupt: if the agent is requested to stop.
+ """
+ self.print_status()
+ if self._verbosity == 0:
+ print_interval = DEFAULT_PRINT_INTERVAL
+ else:
+ print_interval = VERBOSE_PRINT_INTERVAL
+ try:
+ while True:
+ job = None
+ self._ticks += 1
+ agent_response = self._api.get_launch_agent(
+ self._id, self.gorilla_supports_agents
+ )
+ if agent_response["stopPolling"]:
+ # shutdown process and all jobs if requested from ui
+ raise KeyboardInterrupt # noqa: TRY301
+ if self.num_running_jobs < self._max_jobs:
+ # only check for new jobs if we're not at max
+ job_and_queue = await self.get_job_and_queue()
+ # these will either both be None, or neither will be None
+ if job_and_queue is not None:
+ job = job_and_queue.job
+ queue = job_and_queue.queue
+ try:
+ file_saver = RunQueueItemFileSaver(
+ self._wandb_run, job["runQueueItemId"]
+ )
+ if self._is_scheduler_job(job.get("runSpec", {})):
+ # If job is a scheduler, and we are already at the cap, ignore,
+ # don't ack, and it will be pushed back onto the queue in 1 min
+ if self.num_running_schedulers >= self._max_schedulers:
+ wandb.termwarn(
+ f"{LOG_PREFIX}Agent already running the maximum number "
+ f"of sweep schedulers: {self._max_schedulers}. To set "
+ "this value use `max_schedulers` key in the agent config"
+ )
+ continue
+ await self.run_job(job, queue, file_saver)
+ except Exception as e:
+ wandb.termerror(
+ f"{LOG_PREFIX}Error running job: {traceback.format_exc()}"
+ )
+ wandb._sentry.exception(e)
+
+ # always the first phase, because we only enter phase 2 within the thread
+ files = file_saver.save_contents(
+ contents=traceback.format_exc(),
+ fname="error.log",
+ file_sub_type="error",
+ )
+ await self.fail_run_queue_item(
+ run_queue_item_id=job["runQueueItemId"],
+ message=str(e),
+ phase="agent",
+ files=files,
+ )
+
+ if self._ticks % 2 == 0:
+ if len(self.thread_ids) == 0:
+ await self.update_status(AGENT_POLLING)
+ else:
+ await self.update_status(AGENT_RUNNING)
+ if time.time() - self._last_status_print_time > print_interval:
+ self.print_status()
+
+ if self.num_running_jobs == self._max_jobs or job is None:
+ # all threads busy or did not receive job
+ await asyncio.sleep(AGENT_POLLING_INTERVAL)
+ else:
+ await asyncio.sleep(RECEIVED_JOB_POLLING_INTERVAL)
+
+ except KeyboardInterrupt:
+ await self.update_status(AGENT_KILLED)
+ wandb.termlog(f"{LOG_PREFIX}Shutting down, active jobs:")
+ self.print_status()
+ finally:
+ self._jobs_event.clear()
+
+ # Threaded functions
+ async def task_run_job(
+ self,
+ launch_spec: Dict[str, Any],
+ job: Dict[str, Any],
+ default_config: Dict[str, Any],
+ api: Api,
+ job_tracker: JobAndRunStatusTracker,
+ ) -> None:
+ rqi_id = job["runQueueItemId"]
+ assert rqi_id
+ exception: Optional[Union[LaunchDockerError, Exception]] = None
+ try:
+ with self._jobs_lock:
+ self._jobs[rqi_id] = job_tracker
+ await self._task_run_job(
+ launch_spec, job, default_config, api, rqi_id, job_tracker
+ )
+ except LaunchDockerError as e:
+ wandb.termerror(
+ f"{LOG_PREFIX}agent {self._name} encountered an issue while starting Docker, see above output for details."
+ )
+ exception = e
+ wandb._sentry.exception(e)
+ except LaunchError as e:
+ wandb.termerror(f"{LOG_PREFIX}Error running job: {e}")
+ exception = e
+ wandb._sentry.exception(e)
+ except Exception as e:
+ wandb.termerror(f"{LOG_PREFIX}Error running job: {traceback.format_exc()}")
+ exception = e
+ wandb._sentry.exception(e)
+ finally:
+ await self.finish_thread_id(rqi_id, exception)
+
+ async def _task_run_job(
+ self,
+ launch_spec: Dict[str, Any],
+ job: Dict[str, Any],
+ default_config: Dict[str, Any],
+ api: Api,
+ thread_id: int,
+ job_tracker: JobAndRunStatusTracker,
+ ) -> None:
+ project = LaunchProject.from_spec(launch_spec, api)
+ self._set_queue_and_rqi_in_project(project, job, job_tracker.queue)
+ ack = event_loop_thread_exec(api.ack_run_queue_item)
+ await ack(job["runQueueItemId"], project.run_id)
+ # don't launch sweep runs if the sweep isn't healthy
+ await self.check_sweep_state(launch_spec, api)
+
+ job_tracker.update_run_info(project)
+ self._internal_logger.info("Fetching and validating project...")
+ project.fetch_and_validate_project()
+ self._internal_logger.info("Fetching resource...")
+ resource = launch_spec.get("resource") or "local-container"
+ backend_config: Dict[str, Any] = {
+ PROJECT_SYNCHRONOUS: False, # agent always runs async
+ }
+ self._internal_logger.info("Loading backend")
+ override_build_config = launch_spec.get("builder")
+
+ _, build_config, registry_config = construct_agent_configs(
+ default_config, override_build_config
+ )
+ image_uri = project.docker_image or project.job_base_image
+ entrypoint = project.get_job_entry_point()
+ environment = loader.environment_from_config(
+ default_config.get("environment", {})
+ )
+ registry = loader.registry_from_config(registry_config, environment)
+ builder = loader.builder_from_config(build_config, environment, registry)
+ backend = loader.runner_from_config(
+ resource, api, backend_config, environment, registry
+ )
+
+ if not (
+ project.docker_image
+ or project.job_base_image
+ or isinstance(backend, LocalProcessRunner)
+ ):
+ assert entrypoint is not None
+ image_uri = await builder.build_image(project, entrypoint, job_tracker)
+
+ self._internal_logger.info("Backend loaded...")
+ if isinstance(backend, LocalProcessRunner):
+ run = await backend.run(project, image_uri)
+ else:
+ assert image_uri
+ run = await backend.run(project, image_uri)
+ if self._is_scheduler_job(launch_spec):
+ with self._jobs_lock:
+ self._jobs[thread_id].is_scheduler = True
+ wandb.termlog(
+ f"{LOG_PREFIX}Preparing to run sweep scheduler "
+ f"({self.num_running_schedulers}/{self._max_schedulers})"
+ )
+
+ if not run:
+ with self._jobs_lock:
+ job_tracker.failed_to_start = True
+ return
+ with self._jobs_lock:
+ job_tracker.run = run
+ start_time = time.time()
+ stopped_time: Optional[float] = None
+ while self._jobs_event.is_set():
+ # If run has failed to start before timeout, kill it
+ state = (await run.get_status()).state
+ if state == "starting" and RUN_START_TIMEOUT > 0:
+ if time.time() - start_time > RUN_START_TIMEOUT:
+ await run.cancel()
+ raise LaunchError(
+ f"Run failed to start within {RUN_START_TIMEOUT} seconds. "
+ "If you want to increase this timeout, set WANDB_LAUNCH_START_TIMEOUT "
+ "to a larger value."
+ )
+ if await self._check_run_finished(job_tracker, launch_spec):
+ return
+ if await job_tracker.check_wandb_run_stopped(self._api):
+ if stopped_time is None:
+ stopped_time = time.time()
+ else:
+ if time.time() - stopped_time > self._stopped_run_timeout:
+ await run.cancel()
+ await asyncio.sleep(AGENT_POLLING_INTERVAL)
+
+ # temp: for local, kill all jobs. we don't yet have good handling for different
+ # types of runners in general
+ if isinstance(run, LocalSubmittedRun) and run._command_proc is not None:
+ run._command_proc.kill()
+
+ async def check_sweep_state(self, launch_spec: Dict[str, Any], api: Api) -> None:
+ """Check the state of a sweep before launching a run for the sweep."""
+ if launch_spec.get("sweep_id"):
+ try:
+ get_sweep_state = event_loop_thread_exec(api.get_sweep_state)
+ state = await get_sweep_state(
+ sweep=launch_spec["sweep_id"],
+ entity=launch_spec["entity"],
+ project=launch_spec["project"],
+ )
+ except Exception as e:
+ self._internal_logger.debug(f"Fetch sweep state error: {e}")
+ state = None
+
+ if state != "RUNNING" and state != "PAUSED":
+ raise LaunchError(
+ f"Launch agent picked up sweep job, but sweep ({launch_spec['sweep_id']}) was in a terminal state ({state})"
+ )
+
+ async def _check_run_finished(
+ self, job_tracker: JobAndRunStatusTracker, launch_spec: Dict[str, Any]
+ ) -> bool:
+ if job_tracker.completed_status:
+ return True
+
+ # the run can be done before the run has started
+ # but can also be none if the run failed to start
+ # so if there is no run, either the run hasn't started yet
+ # or it has failed
+ if job_tracker.run is None:
+ if job_tracker.failed_to_start:
+ return True
+ return False
+
+ known_error = False
+ try:
+ run = job_tracker.run
+ status = await run.get_status()
+ state = status.state
+
+ for warning in status.messages:
+ if warning not in self._known_warnings:
+ self._known_warnings.append(warning)
+ success = self._api.update_run_queue_item_warning(
+ job_tracker.run_queue_item_id,
+ warning,
+ "Kubernetes",
+ [],
+ )
+ if not success:
+ _logger.warning(
+ f"Error adding warning {warning} to run queue item {job_tracker.run_queue_item_id}"
+ )
+ self._known_warnings.remove(warning)
+
+ if state == "preempted" and job_tracker.entity == self._entity:
+ config = launch_spec.copy()
+ config["run_id"] = job_tracker.run_id
+ config["_resume_count"] = config.get("_resume_count", 0) + 1
+ with self._jobs_lock:
+ job_tracker.completed_status = state
+ if config["_resume_count"] > MAX_RESUME_COUNT:
+ wandb.termlog(
+ f"{LOG_PREFIX}Run {job_tracker.run_id} has already resumed {MAX_RESUME_COUNT} times."
+ )
+ return True
+ wandb.termlog(
+ f"{LOG_PREFIX}Run {job_tracker.run_id} was preempted, requeuing..."
+ )
+
+ if "sweep_id" in config:
+ # allow resumed runs from sweeps that have already completed by removing
+ # the sweep id before pushing to queue
+ del config["sweep_id"]
+
+ launch_add(
+ config=config,
+ project_queue=self._project,
+ queue_name=job_tracker.queue,
+ )
+ return True
+ # TODO change these statuses to an enum
+ if state in ["stopped", "failed", "finished", "preempted"]:
+ if job_tracker.is_scheduler:
+ wandb.termlog(f"{LOG_PREFIX}Scheduler finished with ID: {run.id}")
+ if state == "failed":
+ # on fail, update sweep state. scheduler run_id should == sweep_id
+ try:
+ self._api.set_sweep_state(
+ sweep=job_tracker.run_id,
+ entity=job_tracker.entity,
+ project=job_tracker.project,
+ state="CANCELED",
+ )
+ except Exception as e:
+ raise LaunchError(f"Failed to update sweep state: {e}")
+ else:
+ wandb.termlog(f"{LOG_PREFIX}Job finished with ID: {run.id}")
+ with self._jobs_lock:
+ job_tracker.completed_status = state
+ return True
+
+ return False
+ except LaunchError as e:
+ wandb.termerror(
+ f"{LOG_PREFIX}Terminating job {run.id} because it failed to start: {str(e)}"
+ )
+ known_error = True
+ with self._jobs_lock:
+ job_tracker.failed_to_start = True
+ # TODO: make get_status robust to errors for each runner, and handle them
+ except Exception as e:
+ wandb.termerror(f"{LOG_PREFIX}Error getting status for job {run.id}")
+ wandb.termerror(traceback.format_exc())
+ _logger.info("---")
+ _logger.info("Caught exception while getting status.")
+ _logger.info(f"Job ID: {run.id}")
+ _logger.info(traceback.format_exc())
+ _logger.info("---")
+ wandb._sentry.exception(e)
+ return known_error
+
+ async def get_job_and_queue(self) -> Optional[JobSpecAndQueue]:
+ for queue in self._queues:
+ job = await self.pop_from_queue(queue)
+ if job is not None:
+ self._queues.remove(queue)
+ self._queues.append(queue)
+ return JobSpecAndQueue(job, queue)
+ return None
+
+ def _set_queue_and_rqi_in_project(
+ self, project: LaunchProject, job: Dict[str, Any], queue: str
+ ) -> None:
+ project.queue_name = queue
+
+ # queue entity currently always matches the agent
+ project.queue_entity = self._entity
+ project.run_queue_item_id = job["runQueueItemId"]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/agent/config.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/agent/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..546756487820270ea863f6abedc7851a0dd9f70b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/agent/config.py
@@ -0,0 +1,296 @@
+"""Definition of the config object used by the Launch agent."""
+
+from enum import Enum
+from typing import List, Optional
+
+# ValidationError is imported for exception type checking purposes only.
+from pydantic import ( # type: ignore
+ BaseModel,
+ Field,
+ ValidationError,
+ root_validator,
+ validator,
+)
+
+import wandb
+from wandb.sdk.launch.utils import (
+ AZURE_BLOB_REGEX,
+ AZURE_CONTAINER_REGISTRY_URI_REGEX,
+ ELASTIC_CONTAINER_REGISTRY_URI_REGEX,
+ GCP_ARTIFACT_REGISTRY_URI_REGEX,
+ GCS_URI_RE,
+ S3_URI_RE,
+)
+
+__all__ = [
+ "ValidationError",
+ "AgentConfig",
+]
+
+
+class EnvironmentType(str, Enum):
+ """Enum of valid environment types."""
+
+ aws = "aws"
+ gcp = "gcp"
+ azure = "azure"
+
+
+class RegistryType(str, Enum):
+ """Enum of valid registry types."""
+
+ ecr = "ecr"
+ acr = "acr"
+ gcr = "gcr"
+
+
+class BuilderType(str, Enum):
+ """Enum of valid builder types."""
+
+ docker = "docker"
+ kaniko = "kaniko"
+ noop = "noop"
+
+
+class TargetPlatform(str, Enum):
+ """Enum of valid target platforms."""
+
+ linux_amd64 = "linux/amd64"
+ linux_arm64 = "linux/arm64"
+
+
+class RegistryConfig(BaseModel):
+ """Configuration for registry block.
+
+ Note that we don't forbid extra fields here because:
+ - We want to allow all fields supported by each registry
+ - We will perform validation on the registry object itself later
+ - Registry block is being deprecated in favor of destination field in builder
+ """
+
+ type: Optional[RegistryType] = Field(
+ None,
+ description="The type of registry to use.",
+ )
+ uri: Optional[str] = Field(
+ None,
+ description="The URI of the registry.",
+ )
+
+ @validator("uri") # type: ignore
+ @classmethod
+ def validate_uri(cls, uri: str) -> str:
+ return validate_registry_uri(uri)
+
+
+class EnvironmentConfig(BaseModel):
+ """Configuration for the environment block."""
+
+ type: Optional[EnvironmentType] = Field(
+ None,
+ description="The type of environment to use.",
+ )
+ region: Optional[str] = Field(..., description="The region to use.")
+
+ class Config:
+ extra = "allow"
+
+ @root_validator(pre=True) # type: ignore
+ @classmethod
+ def check_extra_fields(cls, values: dict) -> dict:
+ """Check for extra fields and print a warning."""
+ for key in values:
+ if key not in ["type", "region"]:
+ wandb.termwarn(
+ f"Unrecognized field {key} in environment block. Please check your config file."
+ )
+ return values
+
+
+class BuilderConfig(BaseModel):
+ type: Optional[BuilderType] = Field(
+ None,
+ description="The type of builder to use.",
+ )
+ destination: Optional[str] = Field(
+ None,
+ description="The destination to use for the built image. If not provided, "
+ "the image will be pushed to the registry.",
+ )
+
+ platform: Optional[TargetPlatform] = Field(
+ None,
+ description="The platform to use for the built image. If not provided, "
+ "the platform will be detected automatically.",
+ )
+
+ build_context_store: Optional[str] = Field(
+ None,
+ description="The build context store to use. Required for kaniko builds.",
+ alias="build-context-store",
+ )
+ build_job_name: Optional[str] = Field(
+ "wandb-launch-container-build",
+ description="Name prefix of the build job.",
+ alias="build-job-name",
+ )
+ secret_name: Optional[str] = Field(
+ None,
+ description="The name of the secret to use for the build job.",
+ alias="secret-name",
+ )
+ secret_key: Optional[str] = Field(
+ None,
+ description="The key of the secret to use for the build job.",
+ alias="secret-key",
+ )
+ kaniko_image: Optional[str] = Field(
+ "gcr.io/kaniko-project/executor:latest",
+ description="The image to use for the kaniko executor.",
+ alias="kaniko-image",
+ )
+
+ @validator("build_context_store") # type: ignore
+ @classmethod
+ def validate_build_context_store(
+ cls, build_context_store: Optional[str]
+ ) -> Optional[str]:
+ """Validate that the build context store is a valid container registry URI."""
+ if build_context_store is None:
+ return None
+ for regex in [
+ S3_URI_RE,
+ GCS_URI_RE,
+ AZURE_BLOB_REGEX,
+ ]:
+ if regex.match(build_context_store):
+ return build_context_store
+ raise ValueError(
+ "Invalid build context store. Build context store must be a URI for an "
+ "S3 bucket, GCS bucket, or Azure blob."
+ )
+
+ @root_validator(pre=True) # type: ignore
+ @classmethod
+ def validate_docker(cls, values: dict) -> dict:
+ """Right now there are no required fields for docker builds."""
+ return values
+
+ @validator("destination") # type: ignore
+ @classmethod
+ def validate_destination(cls, destination: Optional[str]) -> Optional[str]:
+ """Validate that the destination is a valid container registry URI."""
+ if destination is None:
+ return None
+ return validate_registry_uri(destination)
+
+
+class AgentConfig(BaseModel):
+ """Configuration for the Launch agent."""
+
+ queues: List[str] = Field(
+ default=[],
+ description="The queues to use for this agent.",
+ )
+ entity: Optional[str] = Field(
+ description="The W&B entity to use for this agent.",
+ )
+ max_jobs: Optional[int] = Field(
+ 1,
+ description="The maximum number of jobs to run concurrently.",
+ )
+ max_schedulers: Optional[int] = Field(
+ 1,
+ description="The maximum number of sweep schedulers to run concurrently.",
+ )
+ secure_mode: Optional[bool] = Field(
+ False,
+ description="Whether to use secure mode for this agent. If True, the "
+ "agent will reject runs that attempt to override the entrypoint or image.",
+ )
+ registry: Optional[RegistryConfig] = Field(
+ None,
+ description="The registry to use.",
+ )
+ environment: Optional[EnvironmentConfig] = Field(
+ None,
+ description="The environment to use.",
+ )
+ builder: Optional[BuilderConfig] = Field(
+ None,
+ description="The builder to use.",
+ )
+ verbosity: Optional[int] = Field(
+ 0,
+ description="How verbose to print, 0 = default, 1 = verbose, 2 = very verbose",
+ )
+ stopped_run_timeout: Optional[int] = Field(
+ 60,
+ description="How many seconds to wait after receiving the stop command before forcibly cancelling a run.",
+ )
+
+ class Config:
+ extra = "forbid"
+
+
+def validate_registry_uri(uri: str) -> str:
+ """Validate that the registry URI is a valid container registry URI.
+
+ The URI should resolve to an image name in a container registry. The recognized
+ formats are for ECR, ACR, and GCP Artifact Registry. If the URI does not match
+ any of these formats, a warning is printed indicating the registry type is not
+ recognized and the agent can't guarantee that images can be pushed.
+
+ If the format is recognized but does not resolve to an image name, an
+ error is raised. For example, if the URI is an ECR URI but does not include
+ an image name or includes a tag as well as an image name, an error is raised.
+ """
+ tag_msg = (
+ "Destination for built images may not include a tag, but the URI provided "
+ "includes the suffix '{tag}'. Please remove the tag and try again. The agent "
+ "will automatically tag each image with a unique hash of the source code."
+ )
+ if uri.startswith("https://"):
+ uri = uri[8:]
+
+ match = GCP_ARTIFACT_REGISTRY_URI_REGEX.match(uri)
+ if match:
+ if match.group("tag"):
+ raise ValueError(tag_msg.format(tag=match.group("tag")))
+ if not match.group("image_name"):
+ raise ValueError(
+ "An image name must be specified in the URI for a GCP Artifact Registry. "
+ "Please provide a uri with the format "
+ "'https://-docker.pkg.dev///'."
+ )
+ return uri
+
+ match = AZURE_CONTAINER_REGISTRY_URI_REGEX.match(uri)
+ if match:
+ if match.group("tag"):
+ raise ValueError(tag_msg.format(tag=match.group("tag")))
+ if not match.group("repository"):
+ raise ValueError(
+ "A repository name must be specified in the URI for an "
+ "Azure Container Registry. Please provide a uri with the format "
+ "'https://.azurecr.io/'."
+ )
+ return uri
+
+ match = ELASTIC_CONTAINER_REGISTRY_URI_REGEX.match(uri)
+ if match:
+ if match.group("tag"):
+ raise ValueError(tag_msg.format(tag=match.group("tag")))
+ if not match.group("repository"):
+ raise ValueError(
+ "A repository name must be specified in the URI for an "
+ "Elastic Container Registry. Please provide a uri with the format "
+ "'https://.dkr.ecr..amazonaws.com/'."
+ )
+ return uri
+
+ wandb.termwarn(
+ f"Unable to recognize registry type in URI {uri}. You are responsible "
+ "for ensuring the agent can push images to this registry."
+ )
+ return uri
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/agent/job_status_tracker.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/agent/job_status_tracker.py
new file mode 100644
index 0000000000000000000000000000000000000000..6baeb1e208b4170d25c2c05f74f023af5ff14188
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/agent/job_status_tracker.py
@@ -0,0 +1,55 @@
+import logging
+from dataclasses import dataclass
+from typing import Optional
+
+from wandb.apis.internal import Api
+from wandb.errors import CommError
+from wandb.sdk.launch._project_spec import LaunchProject
+
+from ..runner.abstract import AbstractRun
+from ..utils import event_loop_thread_exec
+from .run_queue_item_file_saver import RunQueueItemFileSaver
+
+_logger = logging.getLogger(__name__)
+
+
+@dataclass
+class JobAndRunStatusTracker:
+ run_queue_item_id: str
+ queue: str
+ saver: RunQueueItemFileSaver
+ run_id: Optional[str] = None
+ project: Optional[str] = None
+ entity: Optional[str] = None
+ run: Optional[AbstractRun] = None
+ failed_to_start: bool = False
+ completed_status: Optional[str] = None
+ is_scheduler: bool = False
+ err_stage: str = "agent"
+
+ @property
+ def job_completed(self) -> bool:
+ return self.failed_to_start or self.completed_status is not None
+
+ def update_run_info(self, launch_project: LaunchProject) -> None:
+ self.run_id = launch_project.run_id
+ self.project = launch_project.target_project
+ self.entity = launch_project.target_entity
+
+ def set_err_stage(self, stage: str) -> None:
+ self.err_stage = stage
+
+ async def check_wandb_run_stopped(self, api: Api) -> bool:
+ assert (
+ self.run_id is not None
+ and self.project is not None
+ and self.entity is not None
+ ), (
+ "Job tracker does not contain run info. Update with run info before checking if run stopped"
+ )
+ check_stop = event_loop_thread_exec(api.api.check_stop_requested)
+ try:
+ return bool(await check_stop(self.project, self.entity, self.run_id))
+ except CommError:
+ _logger.exception("CommError when checking if wandb run stopped")
+ return False
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/agent/run_queue_item_file_saver.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/agent/run_queue_item_file_saver.py
new file mode 100644
index 0000000000000000000000000000000000000000..56f2d0f075b57857a42135744c189217c2d208e6
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/agent/run_queue_item_file_saver.py
@@ -0,0 +1,39 @@
+"""Implementation of the run queue item file saver class."""
+
+import os
+from typing import List, Literal, Optional
+
+import wandb
+
+FileSubtypes = Literal["warning", "error"]
+
+
+class RunQueueItemFileSaver:
+ def __init__(
+ self,
+ agent_run: Optional["wandb.Run"],
+ run_queue_item_id: str,
+ ):
+ self.run_queue_item_id = run_queue_item_id
+ self.run = agent_run
+
+ def save_contents(
+ self, contents: str, fname: str, file_sub_type: FileSubtypes
+ ) -> Optional[List[str]]:
+ if not isinstance(self.run, wandb.Run):
+ wandb.termwarn("Not saving file contents because agent has no run")
+ return None
+ root_dir = self.run._settings.files_dir
+ saved_run_path = os.path.join(self.run_queue_item_id, file_sub_type, fname)
+ local_path = os.path.join(root_dir, saved_run_path)
+ os.makedirs(os.path.dirname(local_path), exist_ok=True)
+ with open(local_path, "w") as f:
+ f.write(contents)
+ res = self.run.save(local_path, base_path=root_dir, policy="now")
+ if isinstance(res, list):
+ return [saved_run_path]
+ else:
+ wandb.termwarn(
+ f"Failed to save files for run queue item: {self.run_queue_item_id}"
+ )
+ return None
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/abstract.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/abstract.py
new file mode 100644
index 0000000000000000000000000000000000000000..06bd33bc40e1cb398be05367bc326216c7e43a24
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/abstract.py
@@ -0,0 +1,156 @@
+"""Abstract plugin class defining the interface needed to build container images for W&B Launch."""
+
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING, Any, Dict, Optional
+
+from wandb.sdk.launch.environment.abstract import AbstractEnvironment
+from wandb.sdk.launch.registry.abstract import AbstractRegistry
+
+from .._project_spec import EntryPoint, LaunchProject
+from ..registry.anon import AnonynmousRegistry
+from ..utils import (
+ AZURE_CONTAINER_REGISTRY_URI_REGEX,
+ ELASTIC_CONTAINER_REGISTRY_URI_REGEX,
+ GCP_ARTIFACT_REGISTRY_URI_REGEX,
+)
+
+if TYPE_CHECKING:
+ from wandb.sdk.launch.agent.job_status_tracker import JobAndRunStatusTracker
+
+
+class AbstractBuilder(ABC):
+ """Abstract plugin class defining the interface needed to build container images for W&B Launch."""
+
+ builder_type: str
+ environment: AbstractEnvironment
+ registry: AbstractRegistry
+ builder_config: Dict[str, Any]
+
+ @abstractmethod
+ def __init__(
+ self,
+ environment: AbstractEnvironment,
+ registry: AbstractRegistry,
+ verify: bool = True,
+ ) -> None:
+ """Initialize a builder.
+
+ Arguments:
+ builder_config: The builder config.
+ registry: The registry to use.
+ verify: Whether to verify the functionality of the builder.
+
+ Raises:
+ LaunchError: If the builder cannot be initialized or verified.
+ """
+ raise NotImplementedError
+
+ @classmethod
+ @abstractmethod
+ def from_config(
+ cls,
+ config: dict,
+ environment: AbstractEnvironment,
+ registry: AbstractRegistry,
+ ) -> "AbstractBuilder":
+ """Create a builder from a config dictionary.
+
+ Arguments:
+ config: The config dictionary.
+ environment: The environment to use.
+ registry: The registry to use.
+ verify: Whether to verify the functionality of the builder.
+ login: Whether to login to the registry immediately.
+
+ Returns:
+ The builder.
+ """
+ raise NotImplementedError
+
+ @abstractmethod
+ async def build_image(
+ self,
+ launch_project: LaunchProject,
+ entrypoint: EntryPoint,
+ job_tracker: Optional["JobAndRunStatusTracker"] = None,
+ ) -> str:
+ """Build the image for the given project.
+
+ Arguments:
+ launch_project: The project to build.
+ build_ctx_path: The path to the build context.
+
+ Returns:
+ The image name.
+ """
+ raise NotImplementedError
+
+ @abstractmethod
+ async def verify(self) -> None:
+ """Verify that the builder can be used to build images.
+
+ Raises:
+ LaunchError: If the builder cannot be used to build images.
+ """
+ raise NotImplementedError
+
+
+def registry_from_uri(uri: str) -> AbstractRegistry:
+ """Create a registry helper object from a uri.
+
+ This function parses the URI and determines which supported registry it
+ belongs to. It then creates a registry helper object for that registry.
+ The supported remote registry types are:
+ - Azure Container Registry
+ - Google Container Registry
+ - AWS Elastic Container Registry
+
+ The format of the URI is as follows:
+ - Azure Container Registry: .azurecr.io//
+ - Google Container Registry: -docker.pkg.dev///
+ - AWS Elastic Container Registry: .dkr.ecr..amazonaws.com//
+
+ Our classification of the registry is based on the domain name. For example,
+ if the uri contains `.azurecr.io`, we classify it as an Azure
+ Container Registry. If the uri contains `.dkr.ecr`, we classify
+ it as an AWS Elastic Container Registry. If the uri contains
+ `-docker.pkg.dev`, we classify it as a Google Artifact Registry.
+
+ This function will attempt to load the appropriate cloud helpers for the
+
+ `https://` prefix is optional for all of the above.
+
+ Arguments:
+ uri: The uri to create a registry from.
+
+ Returns:
+ The registry.
+
+ Raises:
+ LaunchError: If the registry helper cannot be loaded for the given URI.
+ """
+ if uri.startswith("https://"):
+ uri = uri[len("https://") :]
+
+ if AZURE_CONTAINER_REGISTRY_URI_REGEX.match(uri) is not None:
+ from wandb.sdk.launch.registry.azure_container_registry import (
+ AzureContainerRegistry,
+ )
+
+ return AzureContainerRegistry(uri=uri)
+
+ elif GCP_ARTIFACT_REGISTRY_URI_REGEX.match(uri) is not None:
+ from wandb.sdk.launch.registry.google_artifact_registry import (
+ GoogleArtifactRegistry,
+ )
+
+ return GoogleArtifactRegistry(uri=uri)
+
+ elif ELASTIC_CONTAINER_REGISTRY_URI_REGEX.match(uri) is not None:
+ from wandb.sdk.launch.registry.elastic_container_registry import (
+ ElasticContainerRegistry,
+ )
+
+ return ElasticContainerRegistry(uri=uri)
+
+ return AnonynmousRegistry(uri=uri)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/build.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/build.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e60714b07e8cec6ebdfcadf2eb84a9688328214
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/build.py
@@ -0,0 +1,296 @@
+import hashlib
+import json
+import logging
+import os
+import pathlib
+import shlex
+import shutil
+from typing import Any, Dict, List, Tuple
+
+import wandb
+import wandb.env
+from wandb import docker
+from wandb.apis.internal import Api
+from wandb.sdk.launch.loader import (
+ builder_from_config,
+ environment_from_config,
+ registry_from_config,
+)
+from wandb.util import get_module
+
+from .._project_spec import EntryPoint, LaunchProject
+from ..errors import ExecutionError, LaunchError
+from ..utils import LOG_PREFIX, event_loop_thread_exec
+from .templates.dockerfile import (
+ ACCELERATOR_SETUP_TEMPLATE,
+ ENTRYPOINT_TEMPLATE,
+ PIP_TEMPLATE,
+ PYTHON_SETUP_TEMPLATE,
+ USER_CREATE_TEMPLATE,
+)
+
+_logger = logging.getLogger(__name__)
+
+
+_WANDB_DOCKERFILE_NAME = "Dockerfile.wandb"
+
+
+async def validate_docker_installation() -> None:
+ """Verify if Docker is installed on host machine."""
+ find_exec = event_loop_thread_exec(shutil.which)
+ if not await find_exec("docker"):
+ raise ExecutionError(
+ "Could not find Docker executable. "
+ "Ensure Docker is installed as per the instructions "
+ "at https://docs.docker.com/install/overview/."
+ )
+
+
+def join(split_command: List[str]) -> str:
+ """Return a shell-escaped string from *split_command*.
+
+ Also remove quotes from double quoted strings. Ex:
+ "'local container queue'" --> "local container queue"
+ """
+ return " ".join(shlex.quote(arg.replace("'", "")) for arg in split_command)
+
+
+async def build_image_from_project(
+ launch_project: LaunchProject,
+ api: Api,
+ launch_config: Dict[str, Any],
+) -> str:
+ """Construct a docker image from a project and returns the URI of the image.
+
+ Arguments:
+ launch_project: The project to build an image from.
+ api: The API object to use for fetching the project.
+ launch_config: The launch config to use for building the image.
+
+ Returns:
+ The URI of the built image.
+ """
+ assert launch_project.uri, "To build an image on queue a URI must be set."
+ launch_config = launch_config or {}
+ env_config = launch_config.get("environment", {})
+ if not isinstance(env_config, dict):
+ wrong_type = type(env_config).__name__
+ raise LaunchError(
+ f"Invalid environment config: {env_config} of type {wrong_type} "
+ "loaded from launch config. Expected dict."
+ )
+ environment = environment_from_config(env_config)
+
+ registry_config = launch_config.get("registry", {})
+ if not isinstance(registry_config, dict):
+ wrong_type = type(registry_config).__name__
+ raise LaunchError(
+ f"Invalid registry config: {registry_config} of type {wrong_type}"
+ " loaded from launch config. Expected dict."
+ )
+ registry = registry_from_config(registry_config, environment)
+
+ builder_config = launch_config.get("builder", {})
+ if not isinstance(builder_config, dict):
+ wrong_type = type(builder_config).__name__
+ raise LaunchError(
+ f"Invalid builder config: {builder_config} of type {wrong_type} "
+ "loaded from launch config. Expected dict."
+ )
+ builder = builder_from_config(builder_config, environment, registry)
+
+ if not builder:
+ raise LaunchError("Unable to build image. No builder found.")
+
+ launch_project.fetch_and_validate_project()
+
+ entry_point = (
+ launch_project.get_job_entry_point() or launch_project.override_entrypoint
+ )
+ assert entry_point is not None
+ wandb.termlog(f"{LOG_PREFIX}Building docker image from uri source")
+ image_uri = await builder.build_image(launch_project, entry_point)
+ if not image_uri:
+ raise LaunchError("Error building image uri")
+ else:
+ return image_uri
+
+
+def image_tag_from_dockerfile_and_source(
+ launch_project: LaunchProject, dockerfile_contents: str
+) -> str:
+ """Hashes the source and dockerfile contents into a unique tag."""
+ image_source_string = launch_project.get_image_source_string()
+ unique_id_string = image_source_string + dockerfile_contents
+ image_tag = hashlib.sha256(unique_id_string.encode("utf-8")).hexdigest()[:8]
+ return image_tag
+
+
+def get_docker_user(launch_project: LaunchProject, runner_type: str) -> Tuple[str, int]:
+ import getpass
+
+ username = getpass.getuser()
+
+ if runner_type == "sagemaker" and not launch_project.docker_image:
+ # unless user has provided their own image, sagemaker must run as root but keep the name for workdir etc
+ return username, 0
+
+ userid = launch_project.docker_user_id or os.geteuid()
+ return username, userid
+
+
+def get_base_setup(
+ launch_project: LaunchProject, py_version: str, py_major: str
+) -> str:
+ """Fill in the Dockerfile templates for stage 2 of build.
+
+ CPU version is built on python, Accelerator version is built on user provided.
+ """
+ minor = int(py_version.split(".")[1])
+ if minor < 12:
+ python_base_image = f"python:{py_version}-buster"
+ else:
+ python_base_image = f"python:{py_version}-bookworm"
+ if launch_project.accelerator_base_image:
+ _logger.info(
+ f"Using accelerator base image: {launch_project.accelerator_base_image}"
+ )
+ python_packages = [
+ f"python{py_version}",
+ f"libpython{py_version}",
+ "python3-pip",
+ "python3-setuptools",
+ ]
+ base_setup = ACCELERATOR_SETUP_TEMPLATE.format(
+ accelerator_base_image=launch_project.accelerator_base_image,
+ python_packages=" \\\n".join(python_packages),
+ py_version=py_version,
+ )
+ else:
+ python_packages = [
+ "python3-dev",
+ "gcc",
+ ] # gcc required for python < 3.7 for some reason
+ base_setup = PYTHON_SETUP_TEMPLATE.format(py_base_image=python_base_image)
+ return base_setup
+
+
+# Move this into the build context manager.
+def get_requirements_section(
+ launch_project: LaunchProject, build_context_dir: str, builder_type: str
+) -> str:
+ if builder_type == "docker":
+ buildx_installed = docker.is_buildx_installed()
+ if not buildx_installed:
+ wandb.termwarn(
+ "Docker BuildX is not installed, for faster builds upgrade docker: https://github.com/docker/buildx#installing"
+ )
+ prefix = "RUN WANDB_DISABLE_CACHE=true"
+ elif builder_type == "kaniko":
+ prefix = "RUN WANDB_DISABLE_CACHE=true"
+ buildx_installed = False
+
+ if buildx_installed:
+ prefix = "RUN --mount=type=cache,mode=0777,target=/root/.cache/pip"
+
+ requirements_files = []
+ deps_install_line = None
+
+ base_path = pathlib.Path(build_context_dir)
+ # If there is a requirements.txt at root of build context, use that.
+ if (base_path / "src" / "requirements.txt").exists():
+ requirements_files += ["src/requirements.txt"]
+ deps_install_line = "pip install uv && uv pip install -r requirements.txt"
+ with open(base_path / "src" / "requirements.txt") as f:
+ requirements = f.readlines()
+ if not any(["wandb" in r for r in requirements]):
+ wandb.termwarn(f"{LOG_PREFIX}wandb is not present in requirements.txt.")
+ return PIP_TEMPLATE.format(
+ buildx_optional_prefix=prefix,
+ requirements_files=" ".join(requirements_files),
+ pip_install=deps_install_line,
+ )
+
+ # Elif there is pyproject.toml at build context, convert the dependencies
+ # section to a requirements.txt and use that.
+ elif (base_path / "src" / "pyproject.toml").exists():
+ tomli = get_module("tomli")
+ if tomli is None:
+ wandb.termwarn(
+ "pyproject.toml found but tomli could not be loaded. To "
+ "install dependencies from pyproject.toml please run "
+ "`pip install tomli` and try again."
+ )
+ else:
+ # First try to read deps from standard pyproject format.
+ with open(base_path / "src" / "pyproject.toml", "rb") as f:
+ contents = tomli.load(f)
+ project_deps = [
+ str(d) for d in contents.get("project", {}).get("dependencies", [])
+ ]
+ if project_deps:
+ if not any(["wandb" in d for d in project_deps]):
+ wandb.termwarn(
+ f"{LOG_PREFIX}wandb is not present as a dependency in pyproject.toml."
+ )
+ with open(base_path / "src" / "requirements.txt", "w") as f:
+ f.write("\n".join(project_deps))
+ requirements_files += ["src/requirements.txt"]
+ deps_install_line = (
+ "pip install uv && uv pip install -r requirements.txt"
+ )
+ return PIP_TEMPLATE.format(
+ buildx_optional_prefix=prefix,
+ requirements_files=" ".join(requirements_files),
+ pip_install=deps_install_line,
+ )
+
+ # Else use frozen requirements from wandb run.
+ if (
+ not deps_install_line
+ and (base_path / "src" / "requirements.frozen.txt").exists()
+ ):
+ requirements_files += [
+ "src/requirements.frozen.txt",
+ "_wandb_bootstrap.py",
+ ]
+ deps_install_line = (
+ launch_project.parse_existing_requirements() + "python _wandb_bootstrap.py"
+ )
+
+ if not deps_install_line:
+ raise LaunchError(f"No dependency sources found for {launch_project}")
+
+ with open(base_path / "src" / "requirements.frozen.txt") as f:
+ requirements = f.readlines()
+ if not any(["wandb" in r for r in requirements]):
+ wandb.termwarn(
+ f"{LOG_PREFIX}wandb is not present in requirements.frozen.txt."
+ )
+
+ return PIP_TEMPLATE.format(
+ buildx_optional_prefix=prefix,
+ requirements_files=" ".join(requirements_files),
+ pip_install=deps_install_line,
+ )
+
+ else:
+ # this means no deps file was found
+ requirements_line = "RUN mkdir -p env/" # Docker fails otherwise
+ wandb.termwarn("No requirements file found. No packages will be installed.")
+ return requirements_line
+
+
+def get_user_setup(username: str, userid: int, runner_type: str) -> str:
+ if runner_type == "sagemaker":
+ # sagemaker must run as root
+ return "USER root"
+ user_create = USER_CREATE_TEMPLATE.format(uid=userid, user=username)
+ user_create += f"\nUSER {username}"
+ return user_create
+
+
+def get_entrypoint_setup(
+ entry_point: EntryPoint,
+) -> str:
+ return ENTRYPOINT_TEMPLATE.format(entrypoint=json.dumps(entry_point.command))
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/context_manager.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/context_manager.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1ceb3a21ce4627e7468339653343364ceac8b1b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/context_manager.py
@@ -0,0 +1,235 @@
+import logging
+import os
+import shutil
+import tempfile
+from typing import Tuple
+
+from wandb.sdk.launch._project_spec import LaunchProject
+from wandb.sdk.launch.builder.build import image_tag_from_dockerfile_and_source
+from wandb.sdk.launch.errors import LaunchError
+from wandb.sdk.launch.utils import get_current_python_version
+
+from .build import (
+ _WANDB_DOCKERFILE_NAME,
+ get_base_setup,
+ get_docker_user,
+ get_entrypoint_setup,
+ get_requirements_section,
+ get_user_setup,
+)
+from .templates.dockerfile import DOCKERFILE_TEMPLATE
+
+_logger = logging.getLogger(__name__)
+
+
+class BuildContextManager:
+ """Creates a build context for a container image from job source code.
+
+ The dockerfile and build context may be specified by the job itself. If not,
+ the behavior for creating the build context is as follows:
+
+ - If a Dockerfile.wandb is found adjacent to the entrypoint, the directory
+ containing the entrypoint is used as the build context and Dockerfile.wandb
+ is used as the Dockerfile.
+
+ - If `override_dockerfile` is set on the LaunchProject, the directory
+ containing the Dockerfile is used as the build context and the Dockerfile
+ is used as the Dockerfile. `override_dockerfile` can be set in a launch
+ spec via the `-D` flag to `wandb launch` or in the `overrides` section
+ of the launch drawer.
+
+ - If no dockerfile is set, a Dockerfile is generated from the job's
+ requirements and entrypoint.
+ """
+
+ def __init__(self, launch_project: LaunchProject):
+ """Initialize a BuildContextManager.
+
+ Arguments:
+ launch_project: The launch project.
+ """
+ self._launch_project = launch_project
+ assert self._launch_project.project_dir is not None
+ self._directory = tempfile.mkdtemp()
+
+ def _generate_dockerfile(self, builder_type: str) -> str:
+ """Generate a Dockerfile for the container image.
+
+ Arguments:
+ builder_type: The type of builder to use. One of "docker" or "kaniko".
+
+ Returns:
+ The contents of the Dockerfile.
+ """
+ launch_project = self._launch_project
+ entry_point = (
+ launch_project.override_entrypoint or launch_project.get_job_entry_point()
+ )
+
+ # get python versions truncated to major.minor to ensure image availability
+ if launch_project.python_version:
+ spl = launch_project.python_version.split(".")[:2]
+ py_version, py_major = (".".join(spl), spl[0])
+ else:
+ py_version, py_major = get_current_python_version()
+
+ python_build_image = (
+ f"python:{py_version}" # use full python image for package installation
+ )
+ requirements_section = get_requirements_section(
+ launch_project, self._directory, builder_type
+ )
+ # ----- stage 2: base -----
+ python_base_setup = get_base_setup(launch_project, py_version, py_major)
+
+ # set up user info
+ username, userid = get_docker_user(launch_project, launch_project.resource)
+ user_setup = get_user_setup(username, userid, launch_project.resource)
+ workdir = f"/home/{username}"
+
+ assert entry_point is not None
+ entrypoint_section = get_entrypoint_setup(entry_point)
+
+ dockerfile_contents = DOCKERFILE_TEMPLATE.format(
+ py_build_image=python_build_image,
+ requirements_section=requirements_section,
+ base_setup=python_base_setup,
+ uid=userid,
+ user_setup=user_setup,
+ workdir=workdir,
+ entrypoint_section=entrypoint_section,
+ )
+ return dockerfile_contents
+
+ def create_build_context(self, builder_type: str) -> Tuple[str, str]:
+ """Create the build context for the container image.
+
+ Returns:
+ A pair of str: the path to the build context locally and the image
+ tag computed from the Dockerfile.
+ """
+ entrypoint = (
+ self._launch_project.get_job_entry_point()
+ or self._launch_project.override_entrypoint
+ )
+ assert entrypoint is not None
+ assert entrypoint.name is not None
+ assert self._launch_project.project_dir is not None
+
+ # we use that as the build context.
+ build_context_root_dir = self._launch_project.project_dir
+ job_build_context = self._launch_project.job_build_context
+ if job_build_context:
+ full_path = os.path.join(build_context_root_dir, job_build_context)
+ if not os.path.exists(full_path):
+ raise LaunchError(f"Build context does not exist at {full_path}")
+ build_context_root_dir = full_path
+
+ # This is the case where the user specifies a Dockerfile to use.
+ # We use the directory containing the Dockerfile as the build context.
+ override_dockerfile = self._launch_project.override_dockerfile
+ if override_dockerfile:
+ full_path = os.path.join(
+ build_context_root_dir,
+ override_dockerfile,
+ )
+ if not os.path.exists(full_path):
+ raise LaunchError(f"Dockerfile does not exist at {full_path}")
+ shutil.copytree(
+ build_context_root_dir,
+ self._directory,
+ symlinks=True,
+ dirs_exist_ok=True,
+ ignore=shutil.ignore_patterns("fsmonitor--daemon.ipc"),
+ )
+ shutil.copy(
+ full_path,
+ os.path.join(self._directory, _WANDB_DOCKERFILE_NAME),
+ )
+ return self._directory, image_tag_from_dockerfile_and_source(
+ self._launch_project, open(full_path).read()
+ )
+
+ # If the job specifies a Dockerfile, we use that as the Dockerfile.
+ job_dockerfile = self._launch_project.job_dockerfile
+ if job_dockerfile:
+ dockerfile_path = os.path.join(build_context_root_dir, job_dockerfile)
+ if not os.path.exists(dockerfile_path):
+ raise LaunchError(f"Dockerfile does not exist at {dockerfile_path}")
+ shutil.copytree(
+ build_context_root_dir,
+ self._directory,
+ symlinks=True,
+ dirs_exist_ok=True,
+ ignore=shutil.ignore_patterns("fsmonitor--daemon.ipc"),
+ )
+ shutil.copy(
+ dockerfile_path,
+ os.path.join(self._directory, _WANDB_DOCKERFILE_NAME),
+ )
+ return self._directory, image_tag_from_dockerfile_and_source(
+ self._launch_project, open(dockerfile_path).read()
+ )
+
+ # This is the case where we find Dockerfile.wandb adjacent to the
+ # entrypoint. We use the entrypoint directory as the build context.
+ entrypoint_dir = os.path.dirname(entrypoint.name)
+ if entrypoint_dir:
+ path = os.path.join(
+ build_context_root_dir,
+ entrypoint_dir,
+ _WANDB_DOCKERFILE_NAME,
+ )
+ else:
+ path = os.path.join(build_context_root_dir, _WANDB_DOCKERFILE_NAME)
+ if os.path.exists(
+ path
+ ): # We found a Dockerfile.wandb adjacent to the entrypoint.
+ shutil.copytree(
+ os.path.dirname(path),
+ self._directory,
+ symlinks=True,
+ dirs_exist_ok=True,
+ ignore=shutil.ignore_patterns("fsmonitor--daemon.ipc"),
+ )
+ # TODO: remove this once we make things more explicit for users
+ if entrypoint_dir:
+ new_path = os.path.basename(entrypoint.name)
+ entrypoint = self._launch_project.get_job_entry_point()
+ if entrypoint is not None:
+ entrypoint.update_entrypoint_path(new_path)
+ with open(path) as f:
+ docker_file_contents = f.read()
+ return self._directory, image_tag_from_dockerfile_and_source(
+ self._launch_project, docker_file_contents
+ )
+
+ # This is the case where we use our own Dockerfile template. We move
+ # the user code into a src directory in the build context.
+ dst_path = os.path.join(self._directory, "src")
+ assert self._launch_project.project_dir is not None
+ shutil.copytree(
+ src=self._launch_project.project_dir,
+ dst=dst_path,
+ symlinks=True,
+ ignore=shutil.ignore_patterns("fsmonitor--daemon.ipc"),
+ )
+ shutil.copy(
+ os.path.join(os.path.dirname(__file__), "templates", "_wandb_bootstrap.py"),
+ os.path.join(self._directory),
+ )
+ if self._launch_project.python_version:
+ runtime_path = os.path.join(dst_path, "runtime.txt")
+ with open(runtime_path, "w") as fp:
+ fp.write(f"python-{self._launch_project.python_version}")
+
+ # TODO: we likely don't need to pass the whole git repo into the container
+ # with open(os.path.join(directory, ".dockerignore"), "w") as f:
+ # f.write("**/.git")
+ with open(os.path.join(self._directory, _WANDB_DOCKERFILE_NAME), "w") as handle:
+ docker_file_contents = self._generate_dockerfile(builder_type=builder_type)
+ handle.write(docker_file_contents)
+ image_tag = image_tag_from_dockerfile_and_source(
+ self._launch_project, docker_file_contents
+ )
+ return self._directory, image_tag
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/docker_builder.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/docker_builder.py
new file mode 100644
index 0000000000000000000000000000000000000000..d764ba005e38f3346452124816c3b2120ea81fdf
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/docker_builder.py
@@ -0,0 +1,177 @@
+"""Implementation of the docker builder."""
+
+import logging
+import os
+from typing import Any, Dict, Optional
+
+import wandb
+import wandb.docker as docker
+from wandb.sdk.launch.agent.job_status_tracker import JobAndRunStatusTracker
+from wandb.sdk.launch.builder.abstract import AbstractBuilder, registry_from_uri
+from wandb.sdk.launch.environment.abstract import AbstractEnvironment
+from wandb.sdk.launch.registry.abstract import AbstractRegistry
+
+from .._project_spec import EntryPoint, LaunchProject
+from ..errors import LaunchDockerError, LaunchError
+from ..registry.anon import AnonynmousRegistry
+from ..registry.local_registry import LocalRegistry
+from ..utils import (
+ LOG_PREFIX,
+ event_loop_thread_exec,
+ warn_failed_packages_from_build_logs,
+)
+from .build import _WANDB_DOCKERFILE_NAME, validate_docker_installation
+from .context_manager import BuildContextManager
+
+_logger = logging.getLogger(__name__)
+
+
+class DockerBuilder(AbstractBuilder):
+ """Builds a docker image for a project.
+
+ Attributes:
+ builder_config (Dict[str, Any]): The builder config.
+
+ """
+
+ builder_type = "docker"
+ target_platform = "linux/amd64"
+
+ def __init__(
+ self,
+ environment: AbstractEnvironment,
+ registry: AbstractRegistry,
+ config: Dict[str, Any],
+ ):
+ """Initialize a DockerBuilder.
+
+ Arguments:
+ environment (AbstractEnvironment): The environment to use.
+ registry (AbstractRegistry): The registry to use.
+
+ Raises:
+ LaunchError: If docker is not installed
+ """
+ self.environment = environment # Docker builder doesn't actually use this.
+ self.registry = registry
+ self.config = config
+
+ @classmethod
+ def from_config(
+ cls,
+ config: Dict[str, Any],
+ environment: AbstractEnvironment,
+ registry: AbstractRegistry,
+ ) -> "DockerBuilder":
+ """Create a DockerBuilder from a config.
+
+ Arguments:
+ config (Dict[str, Any]): The config.
+ registry (AbstractRegistry): The registry to use.
+ verify (bool, optional): Whether to verify the functionality of the builder.
+ login (bool, optional): Whether to login to the registry.
+
+ Returns:
+ DockerBuilder: The DockerBuilder.
+ """
+ # If the user provided a destination URI in the builder config
+ # we use that as the registry.
+ image_uri = config.get("destination")
+ if image_uri:
+ if registry is not None:
+ wandb.termwarn(
+ f"{LOG_PREFIX}Overriding registry from registry config"
+ f" with {image_uri} from builder config."
+ )
+ registry = registry_from_uri(image_uri)
+
+ return cls(environment, registry, config)
+
+ async def verify(self) -> None:
+ """Verify the builder."""
+ await validate_docker_installation()
+
+ async def login(self) -> None:
+ """Login to the registry."""
+ if isinstance(self.registry, LocalRegistry):
+ _logger.info(f"{LOG_PREFIX}No registry configured, skipping login.")
+ elif isinstance(self.registry, AnonynmousRegistry):
+ _logger.info(f"{LOG_PREFIX}Anonymous registry, skipping login.")
+ else:
+ username, password = await self.registry.get_username_password()
+ login = event_loop_thread_exec(docker.login)
+ await login(username, password, self.registry.uri)
+
+ async def build_image(
+ self,
+ launch_project: LaunchProject,
+ entrypoint: EntryPoint,
+ job_tracker: Optional[JobAndRunStatusTracker] = None,
+ ) -> str:
+ """Build the image for the given project.
+
+ Arguments:
+ launch_project (LaunchProject): The project to build.
+ entrypoint (EntryPoint): The entrypoint to use.
+ """
+ await self.verify()
+ await self.login()
+
+ build_context_manager = BuildContextManager(launch_project=launch_project)
+ build_ctx_path, image_tag = build_context_manager.create_build_context("docker")
+ dockerfile = os.path.join(build_ctx_path, _WANDB_DOCKERFILE_NAME)
+ repository = None if not self.registry else await self.registry.get_repo_uri()
+
+ # if repo is set, use the repo name as the image name
+ if repository:
+ image_uri = f"{repository}:{image_tag}"
+ # otherwise, base the image name off of the source
+ # which the launch_project checks in image_name
+ else:
+ image_uri = f"{launch_project.image_name}:{image_tag}"
+
+ if (
+ not launch_project.build_required()
+ and await self.registry.check_image_exists(image_uri)
+ ):
+ return image_uri
+
+ _logger.info(
+ f"image {image_uri} does not already exist in repository, building."
+ )
+ try:
+ output = await event_loop_thread_exec(docker.build)(
+ tags=[image_uri],
+ file=dockerfile,
+ context_path=build_ctx_path,
+ platform=self.config.get("platform"),
+ )
+
+ warn_failed_packages_from_build_logs(
+ output, image_uri, launch_project.api, job_tracker
+ )
+
+ except docker.DockerError as e:
+ if job_tracker:
+ job_tracker.set_err_stage("build")
+ raise LaunchDockerError(f"Error communicating with docker client: {e}")
+
+ try:
+ os.remove(build_ctx_path)
+ except Exception:
+ _msg = f"{LOG_PREFIX}Temporary docker context file {build_ctx_path} was not deleted."
+ _logger.info(_msg)
+
+ if repository:
+ reg, tag = image_uri.split(":")
+ wandb.termlog(f"{LOG_PREFIX}Pushing image {image_uri}")
+ push_resp = await event_loop_thread_exec(docker.push)(reg, tag)
+ if push_resp is None:
+ raise LaunchError("Failed to push image to repository")
+ elif (
+ launch_project.resource == "sagemaker"
+ and f"The push refers to repository [{repository}]" not in push_resp
+ ):
+ raise LaunchError(f"Unable to push image to ECR, response: {push_resp}")
+
+ return image_uri
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/kaniko_builder.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/kaniko_builder.py
new file mode 100644
index 0000000000000000000000000000000000000000..3740c05e24eb2b723473a78f03c5c2664a27f8bf
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/kaniko_builder.py
@@ -0,0 +1,595 @@
+import asyncio
+import base64
+import copy
+import json
+import logging
+import os
+import shutil
+import tarfile
+import tempfile
+import time
+import traceback
+from typing import Any, Dict, Optional
+
+import wandb
+from wandb.sdk.launch.agent.job_status_tracker import JobAndRunStatusTracker
+from wandb.sdk.launch.builder.abstract import AbstractBuilder, registry_from_uri
+from wandb.sdk.launch.environment.abstract import AbstractEnvironment
+from wandb.sdk.launch.environment.azure_environment import AzureEnvironment
+from wandb.sdk.launch.registry.abstract import AbstractRegistry
+from wandb.sdk.launch.registry.azure_container_registry import AzureContainerRegistry
+from wandb.sdk.launch.registry.elastic_container_registry import (
+ ElasticContainerRegistry,
+)
+from wandb.sdk.launch.registry.google_artifact_registry import GoogleArtifactRegistry
+from wandb.util import get_module
+
+from .._project_spec import EntryPoint, LaunchProject
+from ..errors import LaunchError
+from ..utils import (
+ LOG_PREFIX,
+ get_kube_context_and_api_client,
+ warn_failed_packages_from_build_logs,
+)
+from .build import _WANDB_DOCKERFILE_NAME
+from .context_manager import BuildContextManager
+
+get_module(
+ "kubernetes_asyncio",
+ required="Kaniko builder requires the kubernetes_asyncio package. Please install it with `pip install wandb[launch]`.",
+)
+
+import kubernetes_asyncio as kubernetes # type: ignore # noqa: E402
+from kubernetes_asyncio import client # noqa: E402
+
+_logger = logging.getLogger(__name__)
+
+_DEFAULT_BUILD_TIMEOUT_SECS = 1800 # 30 minute build timeout
+
+SERVICE_ACCOUNT_NAME = os.environ.get("WANDB_LAUNCH_SERVICE_ACCOUNT_NAME", "default")
+PVC_NAME = os.environ.get("WANDB_LAUNCH_KANIKO_PVC_NAME")
+PVC_MOUNT_PATH = (
+ os.environ.get("WANDB_LAUNCH_KANIKO_PVC_MOUNT_PATH", "/kaniko").rstrip("/")
+ if PVC_NAME
+ else None
+)
+DOCKER_CONFIG_SECRET = os.environ.get("WANDB_LAUNCH_KANIKO_AUTH_SECRET")
+
+
+if os.path.exists("/var/run/secrets/kubernetes.io/serviceaccount/namespace"):
+ with open("/var/run/secrets/kubernetes.io/serviceaccount/namespace") as f:
+ NAMESPACE = f.read().strip()
+else:
+ NAMESPACE = "wandb"
+
+
+def get_pod_name_safe(job: client.V1Job):
+ try:
+ return job.spec.template.metadata.name
+ except AttributeError:
+ return None
+
+
+async def _wait_for_completion(
+ batch_client: client.BatchV1Api, job_name: str, deadline_secs: Optional[int] = None
+) -> bool:
+ start_time = time.time()
+ while True:
+ job = await batch_client.read_namespaced_job_status(job_name, NAMESPACE)
+ if job.status.succeeded is not None and job.status.succeeded >= 1:
+ return True
+ elif job.status.failed is not None and job.status.failed >= 1:
+ wandb.termerror(f"{LOG_PREFIX}Build job {job.status.failed} failed {job}")
+ return False
+ wandb.termlog(f"{LOG_PREFIX}Waiting for build job to complete...")
+ if deadline_secs is not None and time.time() - start_time > deadline_secs:
+ return False
+
+ await asyncio.sleep(5)
+
+
+class KanikoBuilder(AbstractBuilder):
+ """Builds a docker image for a project using Kaniko."""
+
+ type = "kaniko"
+
+ build_job_name: str
+ build_context_store: str
+ secret_name: Optional[str]
+ secret_key: Optional[str]
+ image: str
+
+ def __init__(
+ self,
+ environment: AbstractEnvironment,
+ registry: AbstractRegistry,
+ build_job_name: str = "wandb-launch-container-build",
+ build_context_store: str = "",
+ secret_name: str = "",
+ secret_key: str = "",
+ image: str = "gcr.io/kaniko-project/executor:v1.11.0",
+ config: Optional[dict] = None,
+ ):
+ """Initialize a KanikoBuilder.
+
+ Arguments:
+ environment (AbstractEnvironment): The environment to use.
+ registry (AbstractRegistry): The registry to use.
+ build_job_name (str, optional): The name of the build job.
+ build_context_store (str, optional): The name of the build context store.
+ secret_name (str, optional): The name of the secret to use for the registry.
+ secret_key (str, optional): The key of the secret to use for the registry.
+ verify (bool, optional): Whether to verify the functionality of the builder.
+ Defaults to True.
+ """
+ self.environment = environment
+ self.registry = registry
+ self.build_job_name = build_job_name
+ self.build_context_store = build_context_store.rstrip("/")
+ self.secret_name = secret_name
+ self.secret_key = secret_key
+ self.image = image
+ self.kaniko_config = config or {}
+
+ @classmethod
+ def from_config(
+ cls,
+ config: dict,
+ environment: AbstractEnvironment,
+ registry: AbstractRegistry,
+ verify: bool = True,
+ login: bool = True,
+ ) -> "AbstractBuilder":
+ """Create a KanikoBuilder from a config dict.
+
+ Arguments:
+ config: A dict containing the builder config. Must contain a "type" key
+ with value "kaniko".
+ environment: The environment to use for the build.
+ registry: The registry to use for the build.
+ verify: Whether to verify the builder config.
+
+ Returns:
+ A KanikoBuilder instance.
+ """
+ if config.get("type") != "kaniko":
+ raise LaunchError(
+ "Builder config must include 'type':'kaniko' to create a KanikoBuilder."
+ )
+ build_context_store = config.get("build-context-store", "")
+ if build_context_store is None:
+ if not PVC_MOUNT_PATH:
+ raise LaunchError(
+ "You must specify a build context store for kaniko builds. "
+ "You can set builder.build-context-store in your agent config "
+ "to a valid s3, gcs, or azure blog storage URI. Or, configure "
+ "a persistent volume claim through the agent helm chart: "
+ "https://github.com/wandb/helm-charts/tree/main/charts/launch-agent"
+ )
+ build_job_name = config.get("build-job-name", "wandb-launch-container-build")
+ secret_name = config.get("secret-name", "")
+ secret_key = config.get("secret-key", "")
+ kaniko_image = config.get(
+ "kaniko-image", "gcr.io/kaniko-project/executor:v1.11.0"
+ )
+ image_uri = config.get("destination")
+ if image_uri is not None:
+ registry = registry_from_uri(image_uri)
+ kaniko_config = config.get("kaniko-config", {})
+
+ return cls(
+ environment,
+ registry,
+ build_context_store=build_context_store,
+ build_job_name=build_job_name,
+ secret_name=secret_name,
+ secret_key=secret_key,
+ image=kaniko_image,
+ config=kaniko_config,
+ )
+
+ async def verify(self) -> None:
+ """Verify that the builder config is valid.
+
+ Raises:
+ LaunchError: If the builder config is invalid.
+ """
+ if self.build_context_store:
+ await self.environment.verify_storage_uri(self.build_context_store)
+
+ def login(self) -> None:
+ """Login to the registry."""
+
+ async def _create_docker_ecr_config_map(
+ self, job_name: str, corev1_client: client.CoreV1Api, repository: str
+ ) -> None:
+ username, password = await self.registry.get_username_password()
+ encoded = base64.b64encode(f"{username}:{password}".encode()).decode("utf-8")
+ ecr_config_map = client.V1ConfigMap(
+ api_version="v1",
+ kind="ConfigMap",
+ metadata=client.V1ObjectMeta(
+ name=f"docker-config-{job_name}",
+ namespace=NAMESPACE,
+ ),
+ data={
+ "config.json": json.dumps(
+ {
+ "auths": {
+ f"{await self.registry.get_repo_uri()}": {"auth": encoded}
+ }
+ }
+ )
+ },
+ immutable=True,
+ )
+ await corev1_client.create_namespaced_config_map(NAMESPACE, ecr_config_map)
+
+ async def _delete_docker_ecr_config_map(
+ self, job_name: str, client: client.CoreV1Api
+ ) -> None:
+ if self.secret_name:
+ await client.delete_namespaced_config_map(
+ f"docker-config-{job_name}", NAMESPACE
+ )
+
+ async def _upload_build_context(self, run_id: str, context_path: str) -> str:
+ # creat a tar archive of the build context and upload it to s3
+ context_file = tempfile.NamedTemporaryFile(delete=False)
+ with tarfile.TarFile.open(fileobj=context_file, mode="w:gz") as context_tgz:
+ context_tgz.add(context_path, arcname=".")
+ context_file.close()
+ if PVC_MOUNT_PATH is None:
+ destination = f"{self.build_context_store}/{run_id}.tgz"
+ if self.environment is None:
+ raise LaunchError("No environment specified for Kaniko build.")
+ await self.environment.upload_file(context_file.name, destination)
+ return destination
+ else:
+ destination = f"{PVC_MOUNT_PATH}/{run_id}.tgz"
+ try:
+ shutil.copy(context_file.name, destination)
+ except Exception as e:
+ raise LaunchError(
+ f"Error copying build context to PVC mounted at {PVC_MOUNT_PATH}: {e}"
+ ) from e
+ return f"tar:///context/{run_id}.tgz"
+
+ async def build_image(
+ self,
+ launch_project: LaunchProject,
+ entrypoint: EntryPoint,
+ job_tracker: Optional[JobAndRunStatusTracker] = None,
+ ) -> str:
+ await self.verify()
+
+ build_contex_manager = BuildContextManager(launch_project=launch_project)
+ context_path, image_tag = build_contex_manager.create_build_context("kaniko")
+ run_id = launch_project.run_id
+ repo_uri = await self.registry.get_repo_uri()
+ image_uri = repo_uri + ":" + image_tag
+
+ # The DOCKER_CONFIG_SECRET option is mutually exclusive with the
+ # registry classes, so we must skip the check for image existence in
+ # that case.
+ if not launch_project.build_required():
+ if DOCKER_CONFIG_SECRET:
+ wandb.termlog(
+ f"Skipping check for existing image {image_uri} due to custom dockerconfig."
+ )
+ else:
+ if await self.registry.check_image_exists(image_uri):
+ return image_uri
+
+ _logger.info(f"Building image {image_uri}...")
+ _, api_client = await get_kube_context_and_api_client(
+ kubernetes, launch_project.resource_args
+ )
+ # TODO: use same client as kubernetes_runner.py
+ batch_v1 = client.BatchV1Api(api_client)
+ core_v1 = client.CoreV1Api(api_client)
+
+ build_job_name = f"{self.build_job_name}-{run_id}"
+
+ build_context = await self._upload_build_context(run_id, context_path)
+ build_job = await self._create_kaniko_job(
+ build_job_name, repo_uri, image_uri, build_context, core_v1, api_client
+ )
+ wandb.termlog(f"{LOG_PREFIX}Created kaniko job {build_job_name}")
+
+ try:
+ # DOCKER_CONFIG_SECRET is a user provided dockerconfigjson. Skip our
+ # dockerconfig handling if it's set.
+ if (
+ isinstance(self.registry, AzureContainerRegistry)
+ and not DOCKER_CONFIG_SECRET
+ ):
+ dockerfile_config_map = client.V1ConfigMap(
+ metadata=client.V1ObjectMeta(
+ name=f"docker-config-{build_job_name}"
+ ),
+ data={
+ "config.json": json.dumps(
+ {
+ "credHelpers": {
+ f"{self.registry.registry_name}.azurecr.io": "acr-env"
+ }
+ }
+ )
+ },
+ )
+ await core_v1.create_namespaced_config_map(
+ "wandb", dockerfile_config_map
+ )
+ if self.secret_name:
+ await self._create_docker_ecr_config_map(
+ build_job_name, core_v1, repo_uri
+ )
+ k8s_job = await batch_v1.create_namespaced_job(NAMESPACE, build_job)
+ # wait for double the job deadline since it might take time to schedule
+ if not await _wait_for_completion(
+ batch_v1, build_job_name, 3 * _DEFAULT_BUILD_TIMEOUT_SECS
+ ):
+ if job_tracker:
+ job_tracker.set_err_stage("build")
+ msg = f"Failed to build image in kaniko for job {run_id}."
+ pod_name = get_pod_name_safe(k8s_job)
+ if pod_name:
+ msg += f" View logs with `kubectl logs -n {NAMESPACE} {pod_name}`."
+ raise Exception(msg) # noqa: TRY301
+ try:
+ pods_from_job = await core_v1.list_namespaced_pod(
+ namespace=NAMESPACE, label_selector=f"job-name={build_job_name}"
+ )
+ if len(pods_from_job.items) != 1:
+ raise Exception( # noqa: TRY301
+ f"Expected 1 pod for job {build_job_name},"
+ f" found {len(pods_from_job.items)}"
+ )
+ pod_name = pods_from_job.items[0].metadata.name
+ logs = await core_v1.read_namespaced_pod_log(pod_name, NAMESPACE)
+ warn_failed_packages_from_build_logs(
+ logs, image_uri, launch_project.api, job_tracker
+ )
+ except Exception as e:
+ wandb.termwarn(
+ f"{LOG_PREFIX}Failed to get logs for kaniko job {build_job_name}: {e}"
+ )
+ except Exception as e:
+ wandb.termerror(
+ f"{LOG_PREFIX}Exception when creating Kubernetes resources: {e}\n"
+ )
+ raise
+ finally:
+ wandb.termlog(f"{LOG_PREFIX}Cleaning up resources")
+ try:
+ if (
+ isinstance(self.registry, AzureContainerRegistry)
+ and not DOCKER_CONFIG_SECRET
+ ):
+ await core_v1.delete_namespaced_config_map(
+ f"docker-config-{build_job_name}", "wandb"
+ )
+ if self.secret_name:
+ await self._delete_docker_ecr_config_map(build_job_name, core_v1)
+ await batch_v1.delete_namespaced_job(build_job_name, NAMESPACE)
+ except Exception as e:
+ traceback.print_exc()
+ raise LaunchError(
+ f"Exception during Kubernetes resource clean up {e}"
+ ) from e
+ return image_uri
+
+ async def _create_kaniko_job(
+ self,
+ job_name: str,
+ repository: str,
+ image_tag: str,
+ build_context_path: str,
+ core_client: client.CoreV1Api,
+ api_client,
+ ) -> Dict[str, Any]:
+ job = copy.deepcopy(self.kaniko_config)
+ job_metadata = job.get("metadata", {})
+ job_labels = job_metadata.get("labels", {})
+ job_spec = job.get("spec", {})
+ pod_template = job_spec.get("template", {})
+ pod_metadata = pod_template.get("metadata", {})
+ pod_labels = pod_metadata.get("labels", {})
+ pod_spec = pod_template.get("spec", {})
+ volumes = pod_spec.get("volumes", [])
+ containers = pod_spec.get("containers") or [{}]
+ if len(containers) > 1:
+ raise LaunchError(
+ "Multiple container configs not supported for kaniko builder."
+ )
+ container = containers[0]
+ volume_mounts = container.get("volumeMounts", [])
+ env = container.get("env", [])
+ custom_args = container.get("args", [])
+
+ if PVC_MOUNT_PATH:
+ volumes.append(
+ {"name": "kaniko-pvc", "persistentVolumeClaim": {"claimName": PVC_NAME}}
+ )
+ volume_mounts.append({"name": "kaniko-pvc", "mountPath": "/context"})
+
+ if bool(self.secret_name) != bool(self.secret_key):
+ raise LaunchError(
+ "Both secret_name and secret_key or neither must be specified "
+ "for kaniko build. You provided only one of them."
+ )
+ if isinstance(self.registry, ElasticContainerRegistry):
+ env.append(
+ {
+ "name": "AWS_REGION",
+ "value": self.registry.region,
+ }
+ )
+ # TODO(ben): Refactor all of this environment/registry
+ # specific stuff into methods of those classes.
+ if isinstance(self.environment, AzureEnvironment):
+ # Use the core api to check if the secret exists
+ try:
+ await core_client.read_namespaced_secret(
+ "azure-storage-access-key",
+ "wandb",
+ )
+ except Exception as e:
+ raise LaunchError(
+ "Secret azure-storage-access-key does not exist in "
+ "namespace wandb. Please create it with the key password "
+ "set to your azure storage access key."
+ ) from e
+ env.append(
+ {
+ "name": "AZURE_STORAGE_ACCESS_KEY",
+ "valueFrom": {
+ "secretKeyRef": {
+ "name": "azure-storage-access-key",
+ "key": "password",
+ }
+ },
+ }
+ )
+ if DOCKER_CONFIG_SECRET:
+ volumes.append(
+ {
+ "name": "kaniko-docker-config",
+ "secret": {
+ "secretName": DOCKER_CONFIG_SECRET,
+ "items": [
+ {
+ "key": ".dockerconfigjson",
+ "path": "config.json",
+ }
+ ],
+ },
+ }
+ )
+ volume_mounts.append(
+ {"name": "kaniko-docker-config", "mountPath": "/kaniko/.docker"}
+ )
+ elif self.secret_name and self.secret_key:
+ volumes.append(
+ {
+ "name": "docker-config",
+ "configMap": {"name": f"docker-config-{job_name}"},
+ }
+ )
+ volume_mounts.append(
+ {"name": "docker-config", "mountPath": "/kaniko/.docker"}
+ )
+ # TODO(ben): I don't like conditioning on the registry type here. As a
+ # future change I want the registry and environment classes to provide
+ # a list of environment variables and volume mounts that need to be
+ # added to the job. The environment class provides credentials for
+ # build context access, and the registry class provides credentials
+ # for pushing the image. This way we can have separate secrets for
+ # each and support build contexts and registries that require
+ # different credentials.
+ if isinstance(self.registry, ElasticContainerRegistry):
+ mount_path = "/root/.aws"
+ key = "credentials"
+ elif isinstance(self.registry, GoogleArtifactRegistry):
+ mount_path = "/kaniko/.config/gcloud"
+ key = "config.json"
+ env.append(
+ {
+ "name": "GOOGLE_APPLICATION_CREDENTIALS",
+ "value": "/kaniko/.config/gcloud/config.json",
+ }
+ )
+ else:
+ wandb.termwarn(
+ f"{LOG_PREFIX}Automatic credential handling is not supported for registry type {type(self.registry)}. Build job: {self.build_job_name}"
+ )
+ volumes.append(
+ {
+ "name": self.secret_name,
+ "secret": {
+ "secretName": self.secret_name,
+ "items": [{"key": self.secret_key, "path": key}],
+ },
+ }
+ )
+ volume_mounts.append(
+ {
+ "name": self.secret_name,
+ "mountPath": mount_path,
+ "readOnly": True,
+ }
+ )
+ if (
+ isinstance(self.registry, AzureContainerRegistry)
+ and not DOCKER_CONFIG_SECRET
+ ):
+ # Add the docker config map
+ volumes.append(
+ {
+ "name": "docker-config",
+ "configMap": {"name": f"docker-config-{job_name}"},
+ }
+ )
+ volume_mounts.append(
+ {"name": "docker-config", "mountPath": "/kaniko/.docker/"}
+ )
+ # Kaniko doesn't want https:// at the beginning of the image tag.
+ destination = image_tag
+ if destination.startswith("https://"):
+ destination = destination.replace("https://", "")
+ args = {
+ "--context": build_context_path,
+ "--dockerfile": _WANDB_DOCKERFILE_NAME,
+ "--destination": destination,
+ "--cache": "true",
+ "--cache-repo": repository.replace("https://", ""),
+ "--snapshot-mode": "redo",
+ "--compressed-caching": "false",
+ }
+ for custom_arg in custom_args:
+ arg_name, arg_value = custom_arg.split("=", 1)
+ args[arg_name] = arg_value
+ parsed_args = [
+ f"{arg_name}={arg_value}" for arg_name, arg_value in args.items()
+ ]
+ container["args"] = parsed_args
+
+ # Apply the rest of our defaults
+ pod_labels["wandb"] = "launch"
+ # This annotation is required to enable azure workload identity.
+ # Don't add this label if using a docker config secret for auth.
+ if (
+ isinstance(self.registry, AzureContainerRegistry)
+ and not DOCKER_CONFIG_SECRET
+ ):
+ pod_labels["azure.workload.identity/use"] = "true"
+ pod_spec["restartPolicy"] = pod_spec.get("restartPolicy", "Never")
+ pod_spec["activeDeadlineSeconds"] = pod_spec.get(
+ "activeDeadlineSeconds", _DEFAULT_BUILD_TIMEOUT_SECS
+ )
+ pod_spec["serviceAccountName"] = pod_spec.get(
+ "serviceAccountName", SERVICE_ACCOUNT_NAME
+ )
+ job_spec["backoffLimit"] = job_spec.get("backoffLimit", 0)
+ job_labels["wandb"] = "launch"
+ job_metadata["namespace"] = job_metadata.get("namespace", NAMESPACE)
+ job_metadata["name"] = job_metadata.get("name", job_name)
+ job["apiVersion"] = "batch/v1"
+ job["kind"] = "Job"
+
+ # Apply all nested configs from the bottom up
+ pod_metadata["labels"] = pod_labels
+ pod_template["metadata"] = pod_metadata
+ container["name"] = container.get("name", "wandb-container-build")
+ container["image"] = container.get("image", self.image)
+ container["volumeMounts"] = volume_mounts
+ container["env"] = env
+ pod_spec["containers"] = [container]
+ pod_spec["volumes"] = volumes
+ pod_template["spec"] = pod_spec
+ job_spec["template"] = pod_template
+ job_metadata["labels"] = job_labels
+ job["metadata"] = job_metadata
+ job["spec"] = job_spec
+ return job
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/noop.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/noop.py
new file mode 100644
index 0000000000000000000000000000000000000000..52a64cf5e17dab77bf1792a540421f99e22b5c55
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/noop.py
@@ -0,0 +1,58 @@
+"""NoOp builder implementation."""
+
+from typing import Any, Dict, Optional
+
+from wandb.sdk.launch.builder.abstract import AbstractBuilder
+from wandb.sdk.launch.environment.abstract import AbstractEnvironment
+from wandb.sdk.launch.errors import LaunchError
+from wandb.sdk.launch.registry.abstract import AbstractRegistry
+
+from .._project_spec import EntryPoint, LaunchProject
+from ..agent.job_status_tracker import JobAndRunStatusTracker
+
+
+class NoOpBuilder(AbstractBuilder):
+ """NoOp builder."""
+
+ type = "noop"
+
+ def __init__(
+ self,
+ builder_config: Dict[str, Any],
+ environment: AbstractEnvironment,
+ registry: AbstractRegistry,
+ ) -> None:
+ """Initialize a NoOpBuilder."""
+ self.environment = environment
+ self.registry = registry
+
+ @classmethod
+ def from_config(
+ cls,
+ config: dict,
+ environment: AbstractEnvironment,
+ registry: AbstractRegistry,
+ verify: bool = True,
+ ) -> "AbstractBuilder":
+ """Create a noop builder from a config."""
+ return cls(config, environment, registry)
+
+ async def verify(self) -> None:
+ """Verify the builder."""
+ raise LaunchError("Attempted to verify noop builder.")
+
+ async def build_image(
+ self,
+ launch_project: LaunchProject,
+ entrypoint: EntryPoint,
+ job_tracker: Optional[JobAndRunStatusTracker] = None,
+ ) -> str:
+ """Build the image.
+
+ For this we raise a launch error since it can't build.
+ """
+ raise LaunchError(
+ "Attempted build with noop builder. Specify a builder in your launch config at ~/.config/wandb/launch-config.yaml.\n"
+ "Note: Jobs sourced from git repos and code artifacts require a builder, while jobs sourced from Docker images do not.\n"
+ "See https://docs.wandb.ai/guides/launch/create-job."
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/templates/_wandb_bootstrap.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/templates/_wandb_bootstrap.py
new file mode 100644
index 0000000000000000000000000000000000000000..81e9197775943aa057f74cf2e07a876f1a9452e4
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/templates/_wandb_bootstrap.py
@@ -0,0 +1,188 @@
+import json
+import os
+import re
+import subprocess
+import sys
+from typing import List, Optional, Set
+
+FAILED_PACKAGES_PREFIX = "ERROR: Failed to install: "
+FAILED_PACKAGES_POSTFIX = ". During automated build process."
+ONLY_INCLUDE = {x for x in os.getenv("WANDB_ONLY_INCLUDE", "").split(",") if x != ""}
+OPTS = []
+# If the builder doesn't support buildx no need to use the cache
+if os.getenv("WANDB_DISABLE_CACHE"):
+ OPTS.append("--no-cache-dir")
+# When installing all packages from requirements.frozen.txt no need to resolve deps
+if len(ONLY_INCLUDE) == 0:
+ OPTS.append("--no-deps")
+# When installing the intersection of requirements.frozen.txt and requirements.txt
+# force the frozen versions
+else:
+ OPTS.append("--force")
+
+TORCH_DEP_REGEX = r"torch(vision|audio)?==\d+\.\d+\.\d+(\+(?:cu[\d]{2,3})|(?:\+cpu))?"
+
+
+def install_deps(
+ deps: List[str],
+ failed: Optional[Set[str]] = None,
+ extra_index: Optional[str] = None,
+ opts: Optional[List[str]] = None,
+) -> Optional[Set[str]]:
+ """Install pip dependencies.
+
+ Arguments:
+ deps {List[str]} -- List of dependencies to install
+ failed (set, None): The libraries that failed to install
+
+ Returns:
+ deps (str[], None): The dependencies that failed to install
+ """
+ try:
+ subprocess.check_output(["pip", "install", "uv"], stderr=subprocess.STDOUT)
+ # Include only uri if @ is present
+ clean_deps = [d.split("@")[-1].strip() if "@" in d else d for d in deps]
+ index_args = ["--extra-index-url", extra_index] if extra_index else []
+ print("installing {}...".format(", ".join(clean_deps)))
+ opts = opts or []
+ args = ["uv", "pip", "install"] + opts + clean_deps + index_args
+ sys.stdout.flush()
+ subprocess.check_output(args, stderr=subprocess.STDOUT)
+ return failed
+ except subprocess.CalledProcessError as e:
+ if failed is None:
+ failed = set()
+ num_failed = len(failed)
+ current_pkg = None
+ for line in e.output.decode("utf8").splitlines():
+ # Since the name of the package might not be on the same line as
+ # the error msg, keep track of the currently installing package
+ current_pkg = get_current_package(line, clean_deps, current_pkg)
+
+ if "error: subprocess-exited-with-error" in line:
+ if current_pkg is not None:
+ failed.add(current_pkg)
+ elif line.startswith("ERROR:"):
+ clean_dep = find_package_in_error_string(clean_deps, line)
+ if clean_dep is not None:
+ if clean_dep in deps:
+ failed.add(clean_dep)
+ else:
+ for d in deps:
+ if clean_dep in d:
+ failed.add(d.replace(" ", ""))
+ break
+ if len(set(clean_deps) - failed) == 0:
+ return failed
+ elif len(failed) > num_failed:
+ return install_deps(
+ list(set(clean_deps) - failed),
+ failed,
+ extra_index=extra_index,
+ opts=opts,
+ )
+ else:
+ return failed
+
+
+def main() -> None:
+ """Install deps in requirements.frozen.txt."""
+ extra_index = None
+ torch_reqs = []
+ if os.path.exists("requirements.frozen.txt"):
+ with open("requirements.frozen.txt") as f:
+ print("Installing frozen dependencies...")
+ reqs = []
+ for req in f:
+ if (
+ len(ONLY_INCLUDE) == 0
+ or req in ONLY_INCLUDE
+ or req.split("=")[0].lower() in ONLY_INCLUDE
+ ):
+ # can't pip install wandb==0.*.*.dev1 through pip. Lets just install wandb for now
+ if req.startswith("wandb==") and "dev1" in req:
+ req = "wandb"
+ match = re.match(
+ TORCH_DEP_REGEX,
+ req,
+ )
+ if match:
+ variant = match.group(2)
+ if variant:
+ extra_index = (
+ f"https://download.pytorch.org/whl/{variant[1:]}"
+ )
+ torch_reqs.append(req.strip().replace(" ", ""))
+ else:
+ reqs.append(req.strip().replace(" ", ""))
+ else:
+ print(f"Ignoring requirement: {req} from frozen requirements")
+ failed = install_deps(reqs, opts=OPTS) or set()
+ with open("_wandb_bootstrap_errors.json", "w") as f:
+ f.write(json.dumps({"pip": list(failed)}))
+ if len(failed) > 0:
+ sys.stderr.write(
+ FAILED_PACKAGES_PREFIX + ",".join(failed) + FAILED_PACKAGES_POSTFIX
+ )
+ sys.stderr.flush()
+ install_deps(torch_reqs, extra_index=extra_index)
+ else:
+ print("No frozen requirements found")
+
+
+def add_version_to_package_name(deps: List[str], package: str) -> Optional[str]:
+ """Add the associated version to a package name.
+
+ For example: `my-package` -> `my-package==1.0.0`
+ """
+ for dep in deps:
+ if dep.split("==")[0] == package:
+ return dep
+ return None
+
+
+def get_current_package(
+ line: str, deps: List[str], current_pkg: Optional[str]
+) -> Optional[str]:
+ """Tries to pull a package name from the line.
+
+ Used to keep track of what the currently-installing package is,
+ in case an error message isn't on the same line as the package
+ """
+ # "Collecting my-package==1.0.0"
+ if line.startswith("Collecting"):
+ return line.split(" ")[1]
+ # "Building wheel for my-package (pyproject.toml): finished with status 'error'"
+ elif line.strip().startswith("Building wheel") and line.strip().endswith(
+ "finished with status 'error'"
+ ):
+ return add_version_to_package_name(deps, line.strip().split(" ")[3])
+ # "Running setup.py install for my-package: finished with status 'error'"
+ elif line.strip().startswith("Running setup.py install") and line.strip().endswith(
+ "finished with status 'error'"
+ ):
+ return add_version_to_package_name(deps, line.strip().split(" ")[4][:-1])
+ return current_pkg
+
+
+# hacky way to get the name of the requirement that failed
+# attempt last word which is the name of the package often
+# fall back to checking all words in the line for the package name
+def find_package_in_error_string(deps: List[str], line: str) -> Optional[str]:
+ # if the last word in the error string is in the list of deps, return it
+ last_word = line.split(" ")[-1]
+ if last_word in deps:
+ return last_word
+ # if the last word is not in the list of deps, check all words
+ # TODO: this could report the wrong package if the error string
+ # contains a reference to another package in the deps
+ # before the package that failed to install
+ for word in line.split(" "):
+ if word.strip(",") in deps:
+ return word
+ # if we can't find the package, return None
+ return None
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/templates/dockerfile.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/templates/dockerfile.py
new file mode 100644
index 0000000000000000000000000000000000000000..54ac5bc62201946541541cee6c235391fd9c2d14
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/builder/templates/dockerfile.py
@@ -0,0 +1,92 @@
+DOCKERFILE_TEMPLATE = """
+# ----- stage 1: build -----
+FROM {py_build_image} as build
+
+# requirements section depends on pip vs conda, and presence of buildx
+ENV PIP_PROGRESS_BAR off
+{requirements_section}
+
+# ----- stage 2: base -----
+{base_setup}
+
+COPY --from=build /env /env
+ENV PATH="/env/bin:$PATH"
+
+ENV SHELL /bin/bash
+
+# some resources (eg sagemaker) must run on root
+{user_setup}
+
+WORKDIR {workdir}
+RUN chown -R {uid} {workdir}
+
+# make artifacts cache dir unrelated to build
+RUN mkdir -p {workdir}/.cache && chown -R {uid} {workdir}/.cache
+
+# copy code/etc
+COPY --chown={uid} src/ {workdir}
+
+ENV PYTHONUNBUFFERED=1
+
+{entrypoint_section}
+"""
+
+# this goes into base_setup in TEMPLATE
+PYTHON_SETUP_TEMPLATE = """
+FROM {py_base_image} as base
+"""
+
+# this goes into base_setup in TEMPLATE
+ACCELERATOR_SETUP_TEMPLATE = """
+FROM {accelerator_base_image} as base
+
+# make non-interactive so build doesn't block on questions
+ENV DEBIAN_FRONTEND=noninteractive
+
+# install python
+RUN apt-get update -qq && apt-get install --no-install-recommends -y \
+ {python_packages} \
+ && apt-get -qq purge && apt-get -qq clean \
+ && rm -rf /var/lib/apt/lists/*
+
+# make sure `python` points at the right version
+RUN update-alternatives --install /usr/bin/python python /usr/bin/python{py_version} 1 \
+ && update-alternatives --install /usr/local/bin/python python /usr/bin/python{py_version} 1
+"""
+
+# this goes into requirements_section in TEMPLATE
+PIP_TEMPLATE = """
+RUN python -m venv /env
+# make sure we install into the env
+ENV PATH="/env/bin:$PATH"
+
+COPY {requirements_files} ./
+{buildx_optional_prefix} {pip_install}
+"""
+
+# this goes into requirements_section in TEMPLATE
+CONDA_TEMPLATE = """
+COPY src/environment.yml .
+{buildx_optional_prefix} conda env create -f environment.yml -n env
+
+# pack the environment so that we can transfer to the base image
+RUN conda install -c conda-forge conda-pack
+RUN conda pack -n env -o /tmp/env.tar && \
+ mkdir /env && cd /env && tar xf /tmp/env.tar && \
+ rm /tmp/env.tar
+RUN /env/bin/conda-unpack
+"""
+
+USER_CREATE_TEMPLATE = """
+RUN useradd \
+ --create-home \
+ --no-log-init \
+ --shell /bin/bash \
+ --gid 0 \
+ --uid {uid} \
+ {user} || echo ""
+"""
+
+ENTRYPOINT_TEMPLATE = """
+ENTRYPOINT {entrypoint}
+"""
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/create_job.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/create_job.py
new file mode 100644
index 0000000000000000000000000000000000000000..d275c386391030861d0756ca896122e5900275f7
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/create_job.py
@@ -0,0 +1,542 @@
+import json
+import logging
+import os
+import re
+import sys
+import tempfile
+from typing import Any, Dict, List, Optional, Tuple
+
+import wandb
+from wandb.apis.internal import Api
+from wandb.sdk.artifacts.artifact import Artifact
+from wandb.sdk.internal.job_builder import JobBuilder
+from wandb.sdk.launch.git_reference import GitReference
+from wandb.sdk.launch.inputs.internal import _validate_schema
+from wandb.sdk.launch.utils import (
+ _is_git_uri,
+ get_current_python_version,
+ get_entrypoint_file,
+)
+from wandb.sdk.lib import filesystem
+from wandb.util import make_artifact_name_safe
+
+logging.basicConfig(stream=sys.stdout, level=logging.INFO)
+_logger = logging.getLogger("wandb")
+
+
+CODE_ARTIFACT_EXCLUDE_PATHS = ["wandb", ".git"]
+
+
+def create_job(
+ path: str,
+ job_type: str,
+ entity: Optional[str] = None,
+ project: Optional[str] = None,
+ name: Optional[str] = None,
+ description: Optional[str] = None,
+ aliases: Optional[List[str]] = None,
+ runtime: Optional[str] = None,
+ entrypoint: Optional[str] = None,
+ git_hash: Optional[str] = None,
+ build_context: Optional[str] = None,
+ dockerfile: Optional[str] = None,
+) -> Optional[Artifact]:
+ """Create a job from a path, not as the output of a run.
+
+ Arguments:
+ path (str): Path to the job directory.
+ job_type (str): Type of the job. One of "git", "code", or "image".
+ entity (Optional[str]): Entity to create the job under.
+ project (Optional[str]): Project to create the job under.
+ name (Optional[str]): Name of the job.
+ description (Optional[str]): Description of the job.
+ aliases (Optional[List[str]]): Aliases for the job.
+ runtime (Optional[str]): Python runtime of the job, like 3.9.
+ entrypoint (Optional[str]): Entrypoint of the job. If build_context is
+ provided, path is relative to build_context.
+ git_hash (Optional[str]): Git hash of a specific commit, when using git type jobs.
+ build_context (Optional[str]): Path to the build context, when using image type jobs.
+ dockerfile (Optional[str]): Path to the Dockerfile, when using image type jobs.
+ If build_context is provided, path is relative to build_context.
+
+ Returns:
+ Optional[Artifact]: The artifact created by the job, the action (for printing), and job aliases.
+ None if job creation failed.
+
+ Example:
+ ```python
+ artifact_job = wandb.create_job(
+ job_type="code",
+ path=".",
+ entity="wandb",
+ project="jobs",
+ name="my-train-job",
+ description="My training job",
+ aliases=["train"],
+ runtime="3.9",
+ entrypoint="train.py",
+ )
+ # then run the newly created job
+ artifact_job.call()
+ ```
+ """
+ api = Api()
+
+ artifact_job, _action, _aliases = _create_job(
+ api,
+ job_type,
+ path,
+ entity,
+ project,
+ name,
+ description,
+ aliases,
+ runtime,
+ entrypoint,
+ git_hash,
+ build_context,
+ dockerfile,
+ )
+
+ return artifact_job
+
+
+def _create_job(
+ api: Api,
+ job_type: str,
+ path: str,
+ entity: Optional[str] = None,
+ project: Optional[str] = None,
+ name: Optional[str] = None,
+ description: Optional[str] = None,
+ aliases: Optional[List[str]] = None,
+ runtime: Optional[str] = None,
+ entrypoint: Optional[str] = None,
+ git_hash: Optional[str] = None,
+ build_context: Optional[str] = None,
+ dockerfile: Optional[str] = None,
+ base_image: Optional[str] = None,
+ services: Optional[Dict[str, str]] = None,
+ schema: Optional[Dict[str, Any]] = None,
+) -> Tuple[Optional[Artifact], str, List[str]]:
+ wandb.termlog(f"Creating launch job of type: {job_type}...")
+
+ if name and name != make_artifact_name_safe(name):
+ wandb.termerror(
+ f"Artifact names may only contain alphanumeric characters, dashes, underscores, and dots. Did you mean: {make_artifact_name_safe(name)}"
+ )
+ return None, "", []
+
+ if runtime is not None:
+ if not re.match(r"^3\.\d+$", runtime):
+ wandb.termerror(
+ f"Runtime (-r, --runtime) must be a minor version of Python 3, "
+ f"e.g. 3.9 or 3.10, received {runtime}"
+ )
+ return None, "", []
+ aliases = aliases or []
+ tempdir = tempfile.TemporaryDirectory()
+ try:
+ metadata, requirements = _make_metadata_for_partial_job(
+ job_type=job_type,
+ tempdir=tempdir,
+ git_hash=git_hash,
+ runtime=runtime,
+ path=path,
+ entrypoint=entrypoint,
+ )
+ if not metadata:
+ return None, "", []
+ except Exception as e:
+ wandb.termerror(f"Error creating job: {e}")
+ return None, "", []
+
+ _dump_metadata_and_requirements(
+ metadata=metadata,
+ tmp_path=tempdir.name,
+ requirements=requirements,
+ )
+
+ try:
+ # init hidden wandb run with job building disabled (handled manually)
+ run = wandb.init(
+ dir=tempdir.name,
+ settings={"silent": True, "disable_job_creation": True},
+ entity=entity,
+ project=project,
+ job_type="cli_create_job",
+ )
+ except Exception:
+ # Error printed by wandb.init
+ return None, "", []
+
+ job_builder = _configure_job_builder_for_partial(tempdir.name, job_source=job_type)
+ job_builder._settings.job_name = name
+ job_builder._services = services or {}
+ if job_type == "code":
+ assert entrypoint is not None
+ job_name = _make_code_artifact(
+ api=api,
+ job_builder=job_builder,
+ path=path,
+ entrypoint=entrypoint,
+ run=run, # type: ignore
+ entity=entity,
+ project=project,
+ name=name,
+ )
+ if not job_name:
+ return None, "", []
+ name = job_name
+
+ # build job artifact, loads wandb-metadata and creates wandb-job.json here
+ artifact = job_builder.build(
+ api.api,
+ dockerfile=dockerfile,
+ build_context=build_context,
+ base_image=base_image,
+ )
+ if not artifact:
+ wandb.termerror("JobBuilder failed to build a job")
+ _logger.debug("Failed to build job, check job source and metadata")
+ return None, "", []
+
+ if not name:
+ name = artifact.name
+
+ aliases += job_builder._aliases
+ if "latest" not in aliases:
+ aliases += ["latest"]
+
+ metadata = {"_partial": True}
+ if schema:
+ _validate_schema(schema)
+ metadata = {
+ "input_schemas": {
+ "@wandb.config": schema,
+ }
+ }
+
+ res, _ = api.create_artifact(
+ artifact_type_name="job",
+ artifact_collection_name=name,
+ digest=artifact.digest,
+ client_id=artifact._client_id,
+ sequence_client_id=artifact._sequence_client_id,
+ entity_name=entity,
+ project_name=project,
+ run_name=run.id, # type: ignore # run will be deleted after creation
+ description=description,
+ metadata=metadata,
+ is_user_created=True,
+ aliases=[{"artifactCollectionName": name, "alias": a} for a in aliases],
+ )
+ action = "No changes detected for"
+ if not res.get("artifactSequence", {}).get("latestArtifact"):
+ # When there is no latestArtifact, we are creating new
+ action = "Created"
+ elif res.get("state") == "PENDING":
+ # updating an existing artifafct, state is pending awaiting call to
+ # log_artifact to upload and finalize artifact. If not pending, digest
+ # is the same as latestArtifact, so no changes detected
+ action = "Updated"
+
+ run.log_artifact(artifact, aliases=aliases) # type: ignore
+ artifact.wait()
+ run.finish() # type: ignore
+
+ # fetch, then delete hidden run
+ _run = wandb.Api().run(f"{entity}/{project}/{run.id}") # type: ignore
+ _run.delete()
+
+ return artifact, action, aliases
+
+
+def _make_metadata_for_partial_job(
+ job_type: str,
+ tempdir: tempfile.TemporaryDirectory,
+ git_hash: Optional[str],
+ runtime: Optional[str],
+ path: str,
+ entrypoint: Optional[str],
+) -> Tuple[Optional[Dict[str, Any]], Optional[List[str]]]:
+ """Create metadata for partial jobs, return metadata and requirements."""
+ metadata = {}
+ if job_type == "git":
+ assert entrypoint is not None
+ repo_metadata = _create_repo_metadata(
+ path=path,
+ tempdir=tempdir.name,
+ entrypoint=entrypoint,
+ git_hash=git_hash,
+ runtime=runtime,
+ )
+ if not repo_metadata:
+ tempdir.cleanup() # otherwise git can pollute
+ return None, None
+ metadata.update(repo_metadata)
+ return metadata, None
+
+ if job_type == "code":
+ assert entrypoint is not None
+ artifact_metadata, requirements = _create_artifact_metadata(
+ path=path, entrypoint=entrypoint, runtime=runtime
+ )
+ if not artifact_metadata:
+ return None, None
+ metadata.update(artifact_metadata)
+ return metadata, requirements
+
+ if job_type == "image":
+ if runtime:
+ wandb.termwarn(
+ "Setting runtime is not supported for image jobs, ignoring runtime"
+ )
+ # TODO(gst): support entrypoint for image based jobs
+ if entrypoint:
+ wandb.termwarn(
+ "Setting an entrypoint is not currently supported for image jobs, ignoring entrypoint argument"
+ )
+ metadata.update({"python": runtime or "", "docker": path})
+ return metadata, None
+
+ wandb.termerror(f"Invalid job type: {job_type}")
+ return None, None
+
+
+def _maybe_warn_python_no_executable(entrypoint: str):
+ entrypoint_list = entrypoint.split(" ")
+ if len(entrypoint_list) == 1 and entrypoint_list[0].endswith(".py"):
+ wandb.termwarn(
+ f"Entrypoint {entrypoint} is a python file without an executable, you may want to use `python {entrypoint}` as the entrypoint instead."
+ )
+
+
+def _create_repo_metadata(
+ path: str,
+ tempdir: str,
+ entrypoint: str,
+ git_hash: Optional[str] = None,
+ runtime: Optional[str] = None,
+) -> Optional[Dict[str, Any]]:
+ # Make sure the entrypoint doesn't contain any backward path traversal
+ if entrypoint and ".." in entrypoint:
+ wandb.termerror("Entrypoint cannot contain backward path traversal")
+ return None
+
+ _maybe_warn_python_no_executable(entrypoint)
+
+ if not _is_git_uri(path):
+ wandb.termerror("Path must be a git URI")
+ return None
+
+ ref = GitReference(path, git_hash)
+ if not ref:
+ wandb.termerror("Could not parse git URI")
+ return None
+
+ ref.fetch(tempdir)
+
+ commit = ref.commit_hash
+ if not commit:
+ if not ref.commit_hash:
+ wandb.termerror("Could not find git commit hash")
+ return None
+ commit = ref.commit_hash
+
+ local_dir = os.path.join(tempdir, ref.path or "")
+ python_version = runtime
+ if not python_version:
+ if os.path.exists(os.path.join(local_dir, "runtime.txt")):
+ with open(os.path.join(local_dir, "runtime.txt")) as f:
+ python_version = f.read().strip()
+ elif os.path.exists(os.path.join(local_dir, ".python-version")):
+ with open(os.path.join(local_dir, ".python-version")) as f:
+ python_version = f.read().strip().splitlines()[0]
+ else:
+ python_version, _ = get_current_python_version()
+
+ python_version = _clean_python_version(python_version)
+
+ metadata = {
+ "git": {
+ "commit": commit,
+ "remote": ref.url,
+ },
+ "entrypoint": entrypoint.split(" "),
+ "python": python_version, # used to build container
+ "notebook": False, # partial jobs from notebooks not supported
+ }
+
+ return metadata
+
+
+def _create_artifact_metadata(
+ path: str, entrypoint: str, runtime: Optional[str] = None
+) -> Tuple[Optional[Dict[str, Any]], Optional[List[str]]]:
+ if not os.path.isdir(path):
+ wandb.termerror("Path must be a valid file or directory")
+ return {}, []
+
+ _maybe_warn_python_no_executable(entrypoint)
+
+ entrypoint_list = entrypoint.split(" ")
+ entrypoint_file = get_entrypoint_file(entrypoint_list)
+
+ # read local requirements.txt and dump to temp dir for builder
+ requirements = []
+ depspath = os.path.join(path, "requirements.txt")
+ if os.path.exists(depspath):
+ with open(depspath) as f:
+ requirements = f.read().splitlines()
+
+ if not any(["wandb" in r for r in requirements]):
+ wandb.termwarn("wandb is not present in requirements.txt.")
+
+ if runtime:
+ python_version = _clean_python_version(runtime)
+ else:
+ python_version, _ = get_current_python_version()
+ python_version = _clean_python_version(python_version)
+
+ metadata = {
+ "python": python_version,
+ "codePath": entrypoint_file,
+ "entrypoint": entrypoint_list,
+ }
+ return metadata, requirements
+
+
+def _configure_job_builder_for_partial(tmpdir: str, job_source: str) -> JobBuilder:
+ """Configure job builder with temp dir and job source."""
+ # adjust git source to repo
+ if job_source == "git":
+ job_source = "repo"
+
+ # adjust code source to artifact
+ if job_source == "code":
+ job_source = "artifact"
+
+ settings = wandb.Settings(job_source=job_source)
+ job_builder = JobBuilder(
+ settings=settings, # type: ignore
+ verbose=True,
+ files_dir=tmpdir,
+ )
+ job_builder._partial = True
+ # never allow notebook runs
+ job_builder._is_notebook_run = False
+ # set run inputs and outputs to empty dicts
+ job_builder.set_config({})
+ job_builder.set_summary({})
+ return job_builder
+
+
+def _make_code_artifact(
+ api: Api,
+ job_builder: JobBuilder,
+ run: "wandb.Run",
+ path: str,
+ entrypoint: str,
+ entity: Optional[str],
+ project: Optional[str],
+ name: Optional[str],
+) -> Optional[str]:
+ """Helper for creating and logging code artifacts.
+
+ Returns the name of the eventual job.
+ """
+ entrypoint_list = entrypoint.split(" ")
+ # We no longer require the entrypoint to end in an existing file. But we
+ # need something to use as the default job artifact name. In the future we
+ # may require the user to provide a job name explicitly when calling
+ # wandb job create.
+ entrypoint_file = entrypoint_list[-1]
+ artifact_name = _make_code_artifact_name(os.path.join(path, entrypoint_file), name)
+ code_artifact = wandb.Artifact(
+ name=artifact_name,
+ type="code",
+ description="Code artifact for job",
+ )
+
+ try:
+ code_artifact.add_dir(path)
+ except Exception as e:
+ if os.path.islink(path):
+ wandb.termerror(
+ "Symlinks are not supported for code artifact jobs, please copy the code into a directory and try again"
+ )
+ wandb.termerror(f"Error adding to code artifact: {e}")
+ return None
+
+ # Remove paths we don't want to include, if present
+ for item in CODE_ARTIFACT_EXCLUDE_PATHS:
+ try:
+ code_artifact.remove(item)
+ except FileNotFoundError:
+ pass
+
+ res, _ = api.create_artifact(
+ artifact_type_name="code",
+ artifact_collection_name=artifact_name,
+ digest=code_artifact.digest,
+ client_id=code_artifact._client_id,
+ sequence_client_id=code_artifact._sequence_client_id,
+ entity_name=entity,
+ project_name=project,
+ run_name=run.id, # run will be deleted after creation
+ description="Code artifact for job",
+ metadata={"codePath": path, "entrypoint": entrypoint_file},
+ is_user_created=True,
+ aliases=[
+ {"artifactCollectionName": artifact_name, "alias": a} for a in ["latest"]
+ ],
+ )
+ run.log_artifact(code_artifact)
+ code_artifact.wait()
+ job_builder._handle_server_artifact(res, code_artifact) # type: ignore
+
+ # code artifacts have "code" prefix, remove it and alias
+ if not name:
+ name = code_artifact.name.replace("code", "job").split(":")[0]
+
+ return name
+
+
+def _make_code_artifact_name(path: str, name: Optional[str]) -> str:
+ """Make a code artifact name from a path and user provided name."""
+ if name:
+ return f"code-{name}"
+
+ clean_path = path.replace("./", "")
+ if clean_path[0] == "/":
+ clean_path = clean_path[1:]
+ if clean_path[-1] == "/":
+ clean_path = clean_path[:-1]
+
+ path_name = f"code-{make_artifact_name_safe(clean_path)}"
+ return path_name
+
+
+def _dump_metadata_and_requirements(
+ tmp_path: str, metadata: Dict[str, Any], requirements: Optional[List[str]]
+) -> None:
+ """Dump manufactured metadata and requirements.txt.
+
+ File used by the job_builder to create a job from provided metadata.
+ """
+ filesystem.mkdir_exists_ok(tmp_path)
+ with open(os.path.join(tmp_path, "wandb-metadata.json"), "w") as f:
+ json.dump(metadata, f)
+
+ requirements = requirements or []
+ with open(os.path.join(tmp_path, "requirements.txt"), "w") as f:
+ f.write("\n".join(requirements))
+
+
+def _clean_python_version(python_version: str) -> str:
+ # remove micro if present
+ if python_version.count(".") > 1:
+ python_version = ".".join(python_version.split(".")[:2])
+ _logger.debug(f"micro python version stripped. Now: {python_version}")
+ return python_version
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/environment/abstract.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/environment/abstract.py
new file mode 100644
index 0000000000000000000000000000000000000000..a736ef0404018f0e640a6dad397de281a77895b2
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/environment/abstract.py
@@ -0,0 +1,29 @@
+"""Abstract base class for environments."""
+
+from abc import ABC, abstractmethod
+
+
+class AbstractEnvironment(ABC):
+ """Abstract base class for environments."""
+
+ region: str
+
+ @abstractmethod
+ async def verify(self) -> None:
+ """Verify that the environment is configured correctly."""
+ raise NotImplementedError
+
+ @abstractmethod
+ async def upload_file(self, source: str, destination: str) -> None:
+ """Upload a file from the local filesystem to storage in the environment."""
+ raise NotImplementedError
+
+ @abstractmethod
+ async def upload_dir(self, source: str, destination: str) -> None:
+ """Upload the contents of a directory from the local filesystem to the environment."""
+ raise NotImplementedError
+
+ @abstractmethod
+ async def verify_storage_uri(self, uri: str) -> None:
+ """Verify that the storage URI is configured correctly."""
+ raise NotImplementedError
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/environment/aws_environment.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/environment/aws_environment.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ca54b6d1ac269916fcd98a7c0a4b6fa25465b45
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/environment/aws_environment.py
@@ -0,0 +1,322 @@
+"""Implements the AWS environment."""
+
+import logging
+import os
+from typing import Dict, Optional
+
+from wandb.sdk.launch.errors import LaunchError
+from wandb.util import get_module
+
+from ..utils import ARN_PARTITION_RE, S3_URI_RE, event_loop_thread_exec
+from .abstract import AbstractEnvironment
+
+boto3 = get_module(
+ "boto3",
+ required="AWS environment requires boto3 to be installed. Please install "
+ "it with `pip install wandb[launch]`.",
+)
+botocore = get_module(
+ "botocore",
+ required="AWS environment requires botocore to be installed. Please install "
+ "it with `pip install wandb[launch]`.",
+)
+
+_logger = logging.getLogger(__name__)
+
+
+class AwsEnvironment(AbstractEnvironment):
+ """AWS environment."""
+
+ def __init__(
+ self,
+ region: str,
+ access_key: str,
+ secret_key: str,
+ session_token: str,
+ ) -> None:
+ """Initialize the AWS environment.
+
+ Arguments:
+ region (str): The AWS region.
+
+ Raises:
+ LaunchError: If the AWS environment is not configured correctly.
+ """
+ super().__init__()
+ _logger.info(f"Initializing AWS environment in region {region}.")
+ self._region = region
+ self._access_key = access_key
+ self._secret_key = secret_key
+ self._session_token = session_token
+ self._account = None
+ self._partition = None
+
+ @classmethod
+ def from_default(cls, region: Optional[str] = None) -> "AwsEnvironment":
+ """Create an AWS environment from the default AWS environment.
+
+ Arguments:
+ region (str, optional): The AWS region.
+ verify (bool, optional): Whether to verify the AWS environment. Defaults to True.
+
+ Returns:
+ AwsEnvironment: The AWS environment.
+ """
+ _logger.info("Creating AWS environment from default credentials.")
+ try:
+ session = boto3.Session()
+ if hasattr(session, "region"):
+ region = region or session.region
+ region = region or os.environ.get("AWS_REGION")
+ credentials = session.get_credentials()
+ if not credentials:
+ raise LaunchError(
+ "Could not create AWS environment from default environment. Please verify that your AWS credentials are configured correctly."
+ )
+ access_key = credentials.access_key
+ secret_key = credentials.secret_key
+ session_token = credentials.token
+ except botocore.client.ClientError as e:
+ raise LaunchError(
+ f"Could not create AWS environment from default environment. Please verify that your AWS credentials are configured correctly. {e}"
+ )
+ if not region:
+ raise LaunchError(
+ "Could not create AWS environment from default environment. Region not specified."
+ )
+ return cls(
+ region=region,
+ access_key=access_key,
+ secret_key=secret_key,
+ session_token=session_token,
+ )
+
+ @classmethod
+ def from_config(
+ cls,
+ config: Dict[str, str],
+ ) -> "AwsEnvironment":
+ """Create an AWS environment from the default AWS environment.
+
+ Arguments:
+ config (dict): Configuration dictionary.
+ verify (bool, optional): Whether to verify the AWS environment. Defaults to True.
+
+ Returns:
+ AwsEnvironment: The AWS environment.
+ """
+ region = str(config.get("region", ""))
+ if not region:
+ raise LaunchError(
+ "Could not create AWS environment from config. Region not specified."
+ )
+ return cls.from_default(
+ region=region,
+ )
+
+ @property
+ def region(self) -> str:
+ """The AWS region."""
+ return self._region
+
+ @region.setter
+ def region(self, region: str) -> None:
+ self._region = region
+
+ async def get_partition(self) -> str:
+ """Set the partition for the AWS environment."""
+ try:
+ session = await self.get_session()
+ client = await event_loop_thread_exec(session.client)("sts")
+ get_caller_identity = event_loop_thread_exec(client.get_caller_identity)
+ identity = await get_caller_identity()
+ arn = identity.get("Arn")
+ if not arn:
+ raise LaunchError(
+ "Could not set partition for AWS environment. ARN not found."
+ )
+ matched_partition = ARN_PARTITION_RE.match(arn)
+ if not matched_partition:
+ raise LaunchError(
+ f"Could not set partition for AWS environment. ARN {arn} is not valid."
+ )
+ partition = matched_partition.group(1)
+ return partition
+ except botocore.exceptions.ClientError as e:
+ raise LaunchError(
+ f"Could not set partition for AWS environment. {e}"
+ ) from e
+
+ async def verify(self) -> None:
+ """Verify that the AWS environment is configured correctly.
+
+ Raises:
+ LaunchError: If the AWS environment is not configured correctly.
+ """
+ _logger.debug("Verifying AWS environment.")
+ try:
+ session = await self.get_session()
+ client = await event_loop_thread_exec(session.client)("sts")
+ get_caller_identity = event_loop_thread_exec(client.get_caller_identity)
+ self._account = (await get_caller_identity()).get("Account")
+ # TODO: log identity details from the response
+ except botocore.exceptions.ClientError as e:
+ raise LaunchError(
+ f"Could not verify AWS environment. Please verify that your AWS credentials are configured correctly. {e}"
+ ) from e
+
+ async def get_session(self) -> "boto3.Session": # type: ignore
+ """Get an AWS session.
+
+ Returns:
+ boto3.Session: The AWS session.
+
+ Raises:
+ LaunchError: If the AWS session could not be created.
+ """
+ _logger.debug(f"Creating AWS session in region {self._region}")
+ try:
+ session = event_loop_thread_exec(boto3.Session)
+ return await session(
+ region_name=self._region,
+ aws_access_key_id=self._access_key,
+ aws_secret_access_key=self._secret_key,
+ aws_session_token=self._session_token,
+ )
+ except botocore.exceptions.ClientError as e:
+ raise LaunchError(f"Could not create AWS session. {e}")
+
+ async def upload_file(self, source: str, destination: str) -> None:
+ """Upload a file to s3 from local storage.
+
+ The destination is a valid s3 URI, e.g. s3://bucket/key and will
+ be used as a prefix for the uploaded file. Only the filename of the source
+ is kept in the upload key. So if the source is "foo/bar" and the
+ destination is "s3://bucket/key", the file "foo/bar" will be uploaded
+ to "s3://bucket/key/bar".
+
+ Arguments:
+ source (str): The path to the file or directory.
+ destination (str): The uri of the storage destination. This should
+ be a valid s3 URI, e.g. s3://bucket/key.
+
+ Raises:
+ LaunchError: If the copy fails, the source path does not exist, or the
+ destination is not a valid s3 URI, or the upload fails.
+ """
+ _logger.debug(f"Uploading {source} to {destination}")
+ _err_prefix = f"Error attempting to copy {source} to {destination}."
+ if not os.path.isfile(source):
+ raise LaunchError(f"{_err_prefix}: Source {source} does not exist.")
+ match = S3_URI_RE.match(destination)
+ if not match:
+ raise LaunchError(
+ f"{_err_prefix}: Destination {destination} is not a valid s3 URI."
+ )
+ bucket = match.group(1)
+ key = match.group(2).lstrip("/")
+ if not key:
+ key = ""
+ session = await self.get_session()
+ try:
+ client = await event_loop_thread_exec(session.client)("s3")
+ client.upload_file(source, bucket, key)
+ except botocore.exceptions.ClientError as e:
+ raise LaunchError(
+ f"{_err_prefix}: botocore error attempting to copy {source} to {destination}. {e}"
+ )
+
+ async def upload_dir(self, source: str, destination: str) -> None:
+ """Upload a directory to s3 from local storage.
+
+ The upload will place the contents of the source directory in the destination
+ with the same directory structure. So if the source is "foo/bar" and the
+ destination is "s3://bucket/key", the contents of "foo/bar" will be uploaded
+ to "s3://bucket/key/bar".
+
+ Arguments:
+ source (str): The path to the file or directory.
+ destination (str): The URI of the storage.
+ recursive (bool, optional): If True, copy the directory recursively. Defaults to False.
+
+ Raises:
+ LaunchError: If the copy fails, the source path does not exist, or the
+ destination is not a valid s3 URI.
+ """
+ _logger.debug(f"Uploading {source} to {destination}")
+ _err_prefix = f"Error attempting to copy {source} to {destination}."
+ if not os.path.isdir(source):
+ raise LaunchError(f"{_err_prefix}: Source {source} does not exist.")
+ match = S3_URI_RE.match(destination)
+ if not match:
+ raise LaunchError(
+ f"{_err_prefix}: Destination {destination} is not a valid s3 URI."
+ )
+ bucket = match.group(1)
+ key = match.group(2).lstrip("/")
+ if not key:
+ key = ""
+ session = await self.get_session()
+ try:
+ client = await event_loop_thread_exec(session.client)("s3")
+ for path, _, files in os.walk(source):
+ for file in files:
+ abs_path = os.path.join(path, file)
+ key_path = (
+ abs_path.replace(source, "").replace("\\", "/").lstrip("/")
+ )
+ client.upload_file(
+ abs_path,
+ bucket,
+ key_path,
+ )
+ except botocore.exceptions.ClientError as e:
+ raise LaunchError(
+ f"{_err_prefix}: botocore error attempting to copy {source} to {destination}. {e}"
+ ) from e
+ except Exception as e:
+ raise LaunchError(
+ f"{_err_prefix}: Unexpected error attempting to copy {source} to {destination}. {e}"
+ ) from e
+
+ async def verify_storage_uri(self, uri: str) -> None:
+ """Verify that s3 storage is configured correctly.
+
+ This will check that the bucket exists and that the credentials are
+ configured correctly.
+
+ Arguments:
+ uri (str): The URI of the storage.
+
+ Raises:
+ LaunchError: If the storage is not configured correctly or the URI is
+ not a valid s3 URI.
+
+ Returns:
+ None
+ """
+ _logger.debug(f"Verifying storage {uri}")
+ match = S3_URI_RE.match(uri)
+ if not match:
+ raise LaunchError(
+ f"Failed to validate storage uri: {uri} is not a valid s3 URI."
+ )
+ bucket = match.group(1)
+ try:
+ session = await self.get_session()
+ client = await event_loop_thread_exec(session.client)("s3")
+ client.head_bucket(Bucket=bucket)
+ except botocore.exceptions.ClientError as e:
+ if e.response["Error"]["Code"] == "404":
+ raise LaunchError(
+ f"Could not verify AWS storage uri {uri}. Bucket {bucket} does not exist."
+ )
+ if e.response["Error"]["Code"] == "403":
+ raise LaunchError(
+ f"Could not verify AWS storage uri {uri}. "
+ "Bucket {bucket} is not accessible. Please check that this "
+ "client is authenticated with permission to access the bucket."
+ )
+ raise LaunchError(
+ f"Failed to verify AWS storage uri {uri}. Response: {e.response} Please verify that your AWS credentials are configured correctly."
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/environment/azure_environment.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/environment/azure_environment.py
new file mode 100644
index 0000000000000000000000000000000000000000..2dbfebbe14d499302b4c22dd2321cdfb4ff8df63
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/environment/azure_environment.py
@@ -0,0 +1,105 @@
+"""Implementation of AzureEnvironment class."""
+
+from typing import Tuple
+
+from azure.core.exceptions import HttpResponseError # type: ignore
+from azure.identity import DefaultAzureCredential # type: ignore
+from azure.storage.blob import BlobClient, BlobServiceClient # type: ignore
+
+from ..errors import LaunchError
+from ..utils import AZURE_BLOB_REGEX
+from .abstract import AbstractEnvironment
+
+
+class AzureEnvironment(AbstractEnvironment):
+ """AzureEnvironment is a helper for accessing Azure resources."""
+
+ def __init__(
+ self,
+ ) -> None:
+ """Initialize an AzureEnvironment."""
+
+ @classmethod
+ def from_config(cls, config: dict, verify: bool = True) -> "AzureEnvironment":
+ """Create an AzureEnvironment from a config dict."""
+ return cls()
+
+ @classmethod
+ def get_credentials(cls) -> DefaultAzureCredential:
+ """Get Azure credentials."""
+ try:
+ return DefaultAzureCredential()
+ except Exception as e:
+ raise LaunchError(
+ f"Could not get Azure credentials. Please make sure you have "
+ f"configured your Azure CLI correctly.\n{e}"
+ ) from e
+
+ async def upload_file(self, source: str, destination: str) -> None:
+ """Upload a file to Azure blob storage.
+
+ Arguments:
+ source (str): The path to the file to upload.
+ destination (str): The destination path in Azure blob storage. Ex:
+ https://.blob.core.windows.net//
+ Raise:
+ LaunchError: If the file could not be uploaded.
+ """
+ storage_account, storage_container, path = self.parse_uri(destination)
+ _err_prefix = f"Could not upload file {source} to Azure blob {destination}"
+ creds = self.get_credentials()
+ try:
+ client = BlobClient(
+ f"https://{storage_account}.blob.core.windows.net",
+ storage_container,
+ path,
+ credential=creds,
+ )
+ with open(source, "rb") as f:
+ client.upload_blob(f, overwrite=True)
+ except HttpResponseError as e:
+ raise LaunchError(f"{_err_prefix}: {e.message}") from e
+ except Exception as e:
+ raise LaunchError(f"{_err_prefix}: {e.__class__.__name__}: {e}") from e
+
+ async def upload_dir(self, source: str, destination: str) -> None:
+ """Upload a directory to Azure blob storage."""
+ raise NotImplementedError()
+
+ async def verify_storage_uri(self, uri: str) -> None:
+ """Verify that the given blob storage prefix exists.
+
+ Args:
+ uri (str): The URI to verify.
+ """
+ creds = self.get_credentials()
+ storage_account, storage_container, _ = self.parse_uri(uri)
+ try:
+ client = BlobServiceClient(
+ f"https://{storage_account}.blob.core.windows.net",
+ credential=creds,
+ )
+ client.get_container_client(storage_container)
+ except Exception as e:
+ raise LaunchError(
+ f"Could not verify storage URI {uri} in container {storage_container}."
+ ) from e
+
+ async def verify(self) -> None:
+ """Verify that the AzureEnvironment is valid."""
+ self.get_credentials()
+
+ @staticmethod
+ def parse_uri(uri: str) -> Tuple[str, str, str]:
+ """Parse an Azure blob storage URI into a storage account and container.
+
+ Args:
+ uri (str): The URI to parse.
+
+ Returns:
+ Tuple[str, str, prefix]: The storage account, container, and path.
+ """
+ match = AZURE_BLOB_REGEX.match(uri)
+ if match is None:
+ raise LaunchError(f"Could not parse Azure blob URI {uri}.")
+ return match.group(1), match.group(2), match.group(3)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/environment/gcp_environment.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/environment/gcp_environment.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9847a9853cb76830d79b4ccf0ca41bdc7ae83db
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/environment/gcp_environment.py
@@ -0,0 +1,334 @@
+"""Implementation of the GCP environment for wandb launch."""
+
+import logging
+import os
+import subprocess
+from typing import Optional
+
+from wandb.sdk.launch.errors import LaunchError
+from wandb.util import get_module
+
+from ..utils import GCS_URI_RE, event_loop_thread_exec
+from .abstract import AbstractEnvironment
+
+google = get_module(
+ "google",
+ required="Google Cloud Platform support requires the google package. Please"
+ " install it with `pip install wandb[launch]`.",
+)
+google.cloud.compute_v1 = get_module(
+ "google.cloud.compute_v1",
+ required="Google Cloud Platform support requires the google-cloud-compute package. "
+ "Please install it with `pip install wandb[launch]`.",
+)
+google.auth.credentials = get_module(
+ "google.auth.credentials",
+ required="Google Cloud Platform support requires google-auth. "
+ "Please install it with `pip install wandb[launch]`.",
+)
+google.auth.transport.requests = get_module(
+ "google.auth.transport.requests",
+ required="Google Cloud Platform support requires google-auth. "
+ "Please install it with `pip install wandb[launch]`.",
+)
+google.api_core.exceptions = get_module(
+ "google.api_core.exceptions",
+ required="Google Cloud Platform support requires google-api-core. "
+ "Please install it with `pip install wandb[launch]`.",
+)
+google.cloud.storage = get_module(
+ "google.cloud.storage",
+ required="Google Cloud Platform support requires google-cloud-storage. "
+ "Please install it with `pip install wandb[launch].",
+)
+
+
+_logger = logging.getLogger(__name__)
+
+GCP_REGION_ENV_VAR = "GOOGLE_CLOUD_REGION"
+
+
+class GcpEnvironment(AbstractEnvironment):
+ """GCP Environment.
+
+ Attributes:
+ region: The GCP region.
+ """
+
+ region: str
+
+ def __init__(
+ self,
+ region: str,
+ ) -> None:
+ """Initialize the GCP environment.
+
+ Arguments:
+ region: The GCP region.
+ verify: Whether to verify the credentials, region, and project.
+
+ Raises:
+ LaunchError: If verify is True and the environment is not properly
+ configured.
+ """
+ super().__init__()
+ _logger.info(f"Initializing GcpEnvironment in region {region}")
+ self.region: str = region
+ self._project = ""
+
+ @classmethod
+ def from_config(cls, config: dict) -> "GcpEnvironment":
+ """Create a GcpEnvironment from a config dictionary.
+
+ Arguments:
+ config: The config dictionary.
+
+ Returns:
+ GcpEnvironment: The GcpEnvironment.
+ """
+ if config.get("type") != "gcp":
+ raise LaunchError(
+ f"Could not create GcpEnvironment from config. Expected type 'gcp' "
+ f"but got '{config.get('type')}'."
+ )
+ region = config.get("region", None)
+ if not region:
+ raise LaunchError(
+ "Could not create GcpEnvironment from config. Missing 'region' field."
+ )
+ return cls(region=region)
+
+ @classmethod
+ def from_default(
+ cls,
+ ) -> "GcpEnvironment":
+ """Create a GcpEnvironment from the default configuration.
+
+ Returns:
+ GcpEnvironment: The GcpEnvironment.
+ """
+ region = get_default_region()
+ if region is None:
+ raise LaunchError(
+ "Could not create GcpEnvironment from user's gcloud configuration. "
+ "Please set the default region with `gcloud config set compute/region` "
+ "or set the environment variable {GCP_REGION_ENV_VAR}. "
+ "Alternatively, you may specify the region explicitly in your "
+ "wandb launch configuration at `$HOME/.config/wandb/launch-config.yaml`. "
+ "See https://docs.wandb.ai/guides/launch/run-agent#environments for more information."
+ )
+ return cls(region=region)
+
+ @property
+ def project(self) -> str:
+ """Get the name of the gcp project associated with the credentials.
+
+ Returns:
+ str: The name of the gcp project.
+
+ Raises:
+ LaunchError: If the launch environment cannot be verified.
+ """
+ return self._project
+
+ async def get_credentials(self) -> google.auth.credentials.Credentials: # type: ignore
+ """Get the GCP credentials.
+
+ Uses google.auth.default() to get the credentials. If the credentials
+ are invalid, this method will refresh them. If the credentials are
+ still invalid after refreshing, this method will raise an error.
+
+ Returns:
+ google.auth.credentials.Credentials: The GCP credentials.
+
+ Raises:
+ LaunchError: If the GCP credentials are invalid.
+ """
+ _logger.debug("Getting GCP credentials")
+ # TODO: Figure out a minimal set of scopes.
+ try:
+ google_auth_default = event_loop_thread_exec(google.auth.default)
+ creds, project = await google_auth_default()
+ if not self._project:
+ self._project = project
+ _logger.debug("Refreshing GCP credentials")
+ await event_loop_thread_exec(creds.refresh)(
+ google.auth.transport.requests.Request()
+ )
+ except google.auth.exceptions.DefaultCredentialsError as e:
+ raise LaunchError(
+ "No Google Cloud Platform credentials found. Please run "
+ "`gcloud auth application-default login` or set the environment "
+ "variable GOOGLE_APPLICATION_CREDENTIALS to the path of a valid "
+ "service account key file."
+ ) from e
+ except google.auth.exceptions.RefreshError as e:
+ raise LaunchError(
+ "Could not refresh Google Cloud Platform credentials. Please run "
+ "`gcloud auth application-default login` or set the environment "
+ "variable GOOGLE_APPLICATION_CREDENTIALS to the path of a valid "
+ "service account key file."
+ ) from e
+ if not creds.valid:
+ raise LaunchError(
+ "Invalid Google Cloud Platform credentials. Please run "
+ "`gcloud auth application-default login` or set the environment "
+ "variable GOOGLE_APPLICATION_CREDENTIALS to the path of a valid "
+ "service account key file."
+ )
+ return creds
+
+ async def verify(self) -> None:
+ """Verify the credentials, region, and project.
+
+ Credentials and region are verified by calling get_credentials(). The
+ region and is verified by calling the compute API.
+
+ Raises:
+ LaunchError: If the credentials, region, or project are invalid.
+
+ Returns:
+ None
+ """
+ _logger.debug("Verifying GCP environment")
+ await self.get_credentials()
+
+ async def verify_storage_uri(self, uri: str) -> None:
+ """Verify that a storage URI is valid.
+
+ Arguments:
+ uri: The storage URI.
+
+ Raises:
+ LaunchError: If the storage URI is invalid.
+ """
+ match = GCS_URI_RE.match(uri)
+ if not match:
+ raise LaunchError(f"Invalid GCS URI: {uri}")
+ bucket = match.group(1)
+ cloud_storage_client = event_loop_thread_exec(google.cloud.storage.Client)
+ try:
+ credentials = await self.get_credentials()
+ storage_client = await cloud_storage_client(credentials=credentials)
+ bucket = await event_loop_thread_exec(storage_client.get_bucket)(bucket)
+ except google.api_core.exceptions.GoogleAPICallError as e:
+ raise LaunchError(
+ f"Failed verifying storage uri {uri}: bucket {bucket} does not exist."
+ ) from e
+ except google.api_core.exceptions.Forbidden as e:
+ raise LaunchError(
+ f"Failed verifying storage uri {uri}: bucket {bucket} is not accessible. Please check your permissions and try again."
+ ) from e
+
+ async def upload_file(self, source: str, destination: str) -> None:
+ """Upload a file to GCS.
+
+ Arguments:
+ source: The path to the local file.
+ destination: The path to the GCS file.
+
+ Raises:
+ LaunchError: If the file cannot be uploaded.
+ """
+ _logger.debug(f"Uploading file {source} to {destination}")
+ _err_prefix = f"Could not upload file {source} to GCS destination {destination}"
+ if not os.path.isfile(source):
+ raise LaunchError(f"{_err_prefix}: File {source} does not exist.")
+ match = GCS_URI_RE.match(destination)
+ if not match:
+ raise LaunchError(f"{_err_prefix}: Invalid GCS URI: {destination}")
+ bucket = match.group(1)
+ key = match.group(2).lstrip("/")
+ google_storage_client = event_loop_thread_exec(google.cloud.storage.Client)
+ credentials = await self.get_credentials()
+ try:
+ storage_client = await google_storage_client(credentials=credentials)
+ bucket = await event_loop_thread_exec(storage_client.bucket)(bucket)
+ blob = await event_loop_thread_exec(bucket.blob)(key)
+ await event_loop_thread_exec(blob.upload_from_filename)(source)
+ except google.api_core.exceptions.GoogleAPICallError as e:
+ resp = e.response
+ assert resp is not None
+ try:
+ message = resp.json()["error"]["message"]
+ except Exception:
+ message = str(resp)
+ raise LaunchError(f"{_err_prefix}: {message}") from e
+
+ async def upload_dir(self, source: str, destination: str) -> None:
+ """Upload a directory to GCS.
+
+ Arguments:
+ source: The path to the local directory.
+ destination: The path to the GCS directory.
+
+ Raises:
+ LaunchError: If the directory cannot be uploaded.
+ """
+ _logger.debug(f"Uploading directory {source} to {destination}")
+ _err_prefix = (
+ f"Could not upload directory {source} to GCS destination {destination}"
+ )
+ if not os.path.isdir(source):
+ raise LaunchError(f"{_err_prefix}: Directory {source} does not exist.")
+ match = GCS_URI_RE.match(destination)
+ if not match:
+ raise LaunchError(f"{_err_prefix}: Invalid GCS URI: {destination}")
+ bucket = match.group(1)
+ key = match.group(2).lstrip("/")
+ google_storage_client = event_loop_thread_exec(google.cloud.storage.Client)
+ credentials = await self.get_credentials()
+ try:
+ storage_client = await google_storage_client(credentials=credentials)
+ bucket = await event_loop_thread_exec(storage_client.bucket)(bucket)
+ for root, _, files in os.walk(source):
+ for file in files:
+ local_path = os.path.join(root, file)
+ gcs_path = os.path.join(
+ key, os.path.relpath(local_path, source)
+ ).replace("\\", "/")
+ blob = await event_loop_thread_exec(bucket.blob)(gcs_path)
+ await event_loop_thread_exec(blob.upload_from_filename)(local_path)
+ except google.api_core.exceptions.GoogleAPICallError as e:
+ resp = e.response
+ assert resp is not None
+ try:
+ message = resp.json()["error"]["message"]
+ except Exception:
+ message = str(resp)
+ raise LaunchError(f"{_err_prefix}: {message}") from e
+ except Exception as e:
+ raise LaunchError(f"{_err_prefix}: GCS upload failed: {e}") from e
+
+
+def get_gcloud_config_value(config_name: str) -> Optional[str]:
+ """Get a value from gcloud config.
+
+ Arguments:
+ config_name: The name of the config value.
+
+ Returns:
+ str: The config value, or None if the value is not set.
+ """
+ try:
+ output = subprocess.check_output(
+ ["gcloud", "config", "get-value", config_name], stderr=subprocess.STDOUT
+ )
+ value = str(output.decode("utf-8").strip())
+ if value and "unset" not in value:
+ return value
+ return None
+ except subprocess.CalledProcessError:
+ return None
+
+
+def get_default_region() -> Optional[str]:
+ """Get the default region from gcloud config or environment variables.
+
+ Returns:
+ str: The default region, or None if it cannot be determined.
+ """
+ region = get_gcloud_config_value("compute/region")
+ if not region:
+ region = os.environ.get(GCP_REGION_ENV_VAR)
+ return region
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/environment/local_environment.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/environment/local_environment.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe726354de7cead29d3f663d25b300014aac6380
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/environment/local_environment.py
@@ -0,0 +1,65 @@
+"""Dummy local environment implementation. This is the default environment."""
+
+from typing import Any, Dict, Union
+
+from wandb.sdk.launch.errors import LaunchError
+
+from .abstract import AbstractEnvironment
+
+
+class LocalEnvironment(AbstractEnvironment):
+ """Local environment class."""
+
+ def __init__(self) -> None:
+ """Initialize a local environment by doing nothing."""
+
+ @classmethod
+ def from_config(
+ cls, config: Dict[str, Union[Dict[str, Any], str]]
+ ) -> "LocalEnvironment":
+ """Create a local environment from a config.
+
+ Arguments:
+ config (dict): The config. This is ignored.
+
+ Returns:
+ LocalEnvironment: The local environment.
+ """
+ return cls()
+
+ async def verify(self) -> None:
+ """Verify that the local environment is configured correctly."""
+ raise LaunchError("Attempted to verify LocalEnvironment.")
+
+ async def verify_storage_uri(self, uri: str) -> None:
+ """Verify that the storage URI is configured correctly.
+
+ Arguments:
+ uri (str): The storage URI. This is ignored.
+ """
+ raise LaunchError("Attempted to verify storage uri for LocalEnvironment.")
+
+ async def upload_file(self, source: str, destination: str) -> None:
+ """Upload a file from the local filesystem to storage in the environment.
+
+ Arguments:
+ source (str): The source file. This is ignored.
+ destination (str): The destination file. This is ignored.
+ """
+ raise LaunchError("Attempted to upload file for LocalEnvironment.")
+
+ async def upload_dir(self, source: str, destination: str) -> None:
+ """Upload the contents of a directory from the local filesystem to the environment.
+
+ Arguments:
+ source (str): The source directory. This is ignored.
+ destination (str): The destination directory. This is ignored.
+ """
+ raise LaunchError("Attempted to upload directory for LocalEnvironment.")
+
+ async def get_project(self) -> str:
+ """Get the project of the local environment.
+
+ Returns: An empty string.
+ """
+ raise LaunchError("Attempted to get project for LocalEnvironment.")
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/errors.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/errors.py
new file mode 100644
index 0000000000000000000000000000000000000000..44111ff236245d71b59826791c5c232f0de3b090
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/errors.py
@@ -0,0 +1,13 @@
+from wandb.errors import Error
+
+
+class LaunchError(Error):
+ """Raised when a known error occurs in wandb launch."""
+
+
+class LaunchDockerError(Error):
+ """Raised when Docker daemon is not running."""
+
+
+class ExecutionError(Error):
+ """Generic execution exception."""
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/git_reference.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/git_reference.py
new file mode 100644
index 0000000000000000000000000000000000000000..4eeac74e09f00fe32eb65f41baab0f69519c4842
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/git_reference.py
@@ -0,0 +1,109 @@
+"""Support for parsing GitHub URLs (which might be user provided) into constituent parts."""
+
+import re
+from dataclasses import dataclass
+from enum import IntEnum
+from typing import Optional, Tuple, Union
+
+from wandb.sdk.launch.errors import LaunchError
+
+PREFIX_HTTPS = "https://"
+PREFIX_SSH = "git@"
+SUFFIX_GIT = ".git"
+
+
+GIT_COMMIT_REGEX = re.compile(r"[0-9a-f]{40}")
+
+
+class ReferenceType(IntEnum):
+ BRANCH = 1
+ COMMIT = 2
+
+
+def _parse_netloc(netloc: str) -> Tuple[Optional[str], Optional[str], str]:
+ """Parse netloc into username, password, and host.
+
+ github.com => None, None, "@github.com"
+ username@github.com => "username", None, "github.com"
+ username:password@github.com => "username", "password", "github.com"
+ """
+ parts = netloc.split("@", 1)
+ if len(parts) == 1:
+ return None, None, parts[0]
+ auth, host = parts
+ parts = auth.split(":", 1)
+ if len(parts) == 1:
+ return parts[0], None, host
+ return parts[0], parts[1], host
+
+
+@dataclass
+class GitReference:
+ def __init__(self, remote: str, ref: Optional[str] = None) -> None:
+ """Initialize a reference from a remote and ref.
+
+ Arguments:
+ remote: A remote URL or URI.
+ ref: A branch, tag, or commit hash.
+ """
+ self.uri = remote
+ self.ref = ref
+
+ @property
+ def url(self) -> Optional[str]:
+ return self.uri
+
+ def fetch(self, dst_dir: str) -> None:
+ """Fetch the repo into dst_dir and refine githubref based on what we learn."""
+ # We defer importing git until the last moment, because the import requires that the git
+ # executable is available on the PATH, so we only want to fail if we actually need it.
+ import git # type: ignore
+
+ repo = git.Repo.init(dst_dir)
+ self.path = repo.working_dir
+ origin = repo.create_remote("origin", self.uri or "")
+
+ try:
+ # We fetch the origin so that we have branch and tag references
+ origin.fetch()
+ except git.exc.GitCommandError as e:
+ raise LaunchError(
+ f"Unable to fetch from git remote repository {self.url}:\n{e}"
+ )
+
+ ref: Union[git.RemoteReference, str]
+ if self.ref:
+ if self.ref in origin.refs:
+ ref = origin.refs[self.ref]
+ else:
+ ref = self.ref
+ head = repo.create_head(self.ref, ref)
+ head.checkout()
+ self.commit_hash = head.commit.hexsha
+
+ else:
+ # TODO: Is there a better way to do this?
+ default_branch = None
+ for ref in repo.references:
+ if hasattr(ref, "tag"): # Skip tag references
+ continue
+ refname = ref.name
+ if refname.startswith("origin/"): # Trim off "origin/"
+ refname = refname[7:]
+ if refname == "main":
+ default_branch = "main"
+ break
+ if refname == "master":
+ default_branch = "master"
+ # Keep looking in case we also have a main, which we let take precedence
+ # (While the references appear to be sorted, not clear if that's guaranteed.)
+ if not default_branch:
+ raise LaunchError(
+ f"Unable to determine branch or commit to checkout from {self.url}"
+ )
+ self.default_branch = default_branch
+ self.ref = default_branch
+ head = repo.create_head(default_branch, origin.refs[default_branch])
+ head.checkout()
+ self.commit_hash = head.commit.hexsha
+ repo.submodule_update(init=True, recursive=True)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/inputs/files.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/inputs/files.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0fb790a0e19eae4dea6974d5a3e878da3352fee
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/inputs/files.py
@@ -0,0 +1,148 @@
+import json
+import os
+from typing import Any, Dict
+
+import yaml
+
+from ..errors import LaunchError
+
+FILE_OVERRIDE_ENV_VAR = "WANDB_LAUNCH_FILE_OVERRIDES"
+
+
+class FileOverrides:
+ """Singleton that read file overrides json from environment variables."""
+
+ _instance = None
+
+ def __new__(cls):
+ if cls._instance is None:
+ cls._instance = object.__new__(cls)
+ cls._instance.overrides = {}
+ cls._instance.load()
+ return cls._instance
+
+ def load(self) -> None:
+ """Load overrides from an environment variable."""
+ overrides = os.environ.get(FILE_OVERRIDE_ENV_VAR)
+ if overrides is None:
+ if f"{FILE_OVERRIDE_ENV_VAR}_0" in os.environ:
+ overrides = ""
+ idx = 0
+ while f"{FILE_OVERRIDE_ENV_VAR}_{idx}" in os.environ:
+ overrides += os.environ[f"{FILE_OVERRIDE_ENV_VAR}_{idx}"]
+ idx += 1
+ if overrides:
+ try:
+ contents = json.loads(overrides)
+ if not isinstance(contents, dict):
+ raise LaunchError(f"Invalid JSON in {FILE_OVERRIDE_ENV_VAR}")
+ self.overrides = contents
+ except json.JSONDecodeError:
+ raise LaunchError(f"Invalid JSON in {FILE_OVERRIDE_ENV_VAR}")
+
+
+def config_path_is_valid(path: str) -> None:
+ """Validate a config file path.
+
+ This function checks if a given config file path is valid. A valid path
+ should meet the following criteria:
+
+ - The path must be expressed as a relative path without any upwards path
+ traversal, e.g. `../config.json`.
+ - The file specified by the path must exist.
+ - The file must have a supported extension (`.json`, `.yaml`, or `.yml`).
+
+ Args:
+ path (str): The path to validate.
+
+ Raises:
+ LaunchError: If the path is not valid.
+ """
+ if os.path.isabs(path):
+ raise LaunchError(
+ f"Invalid config path: {path}. Please provide a relative path."
+ )
+ if ".." in path:
+ raise LaunchError(
+ f"Invalid config path: {path}. Please provide a relative path "
+ "without any upward path traversal, e.g. `../config.json`."
+ )
+ path = os.path.normpath(path)
+ if not os.path.exists(path):
+ raise LaunchError(f"Invalid config path: {path}. File does not exist.")
+ if not any(path.endswith(ext) for ext in [".json", ".yaml", ".yml"]):
+ raise LaunchError(
+ f"Invalid config path: {path}. Only JSON and YAML files are supported."
+ )
+
+
+def override_file(path: str) -> None:
+ """Check for file overrides in the environment and apply them if found."""
+ file_overrides = FileOverrides()
+ if path in file_overrides.overrides:
+ overrides = file_overrides.overrides.get(path)
+ if overrides is not None:
+ config = _read_config_file(path)
+ _update_dict(config, overrides)
+ _write_config_file(path, config)
+
+
+def _write_config_file(path: str, config: Any) -> None:
+ """Write a config file to disk.
+
+ Args:
+ path (str): The path to the config file.
+ config (Any): The contents of the config file as a Python object.
+
+ Raises:
+ LaunchError: If the file extension is not supported.
+ """
+ _, ext = os.path.splitext(path)
+ if ext == ".json":
+ with open(path, "w") as f:
+ json.dump(config, f, indent=2)
+ elif ext in [".yaml", ".yml"]:
+ with open(path, "w") as f:
+ yaml.safe_dump(config, f)
+ else:
+ raise LaunchError(f"Unsupported file extension: {ext}")
+
+
+def _read_config_file(path: str) -> Any:
+ """Read a config file from disk.
+
+ Args:
+ path (str): The path to the config file.
+
+ Returns:
+ Any: The contents of the config file as a Python object.
+ """
+ _, ext = os.path.splitext(path)
+ if ext == ".json":
+ with open(
+ path,
+ ) as f:
+ return json.load(f)
+ elif ext in [".yaml", ".yml"]:
+ with open(
+ path,
+ ) as f:
+ return yaml.safe_load(f)
+ else:
+ raise LaunchError(f"Unsupported file extension: {ext}")
+
+
+def _update_dict(target: Dict, source: Dict) -> None:
+ """Update a dictionary with the contents of another dictionary.
+
+ Args:
+ target (Dict): The dictionary to update.
+ source (Dict): The dictionary to update from.
+ """
+ for key, value in source.items():
+ if isinstance(value, dict):
+ if key not in target:
+ target[key] = {}
+ _update_dict(target[key], value)
+ else:
+ target[key] = value
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/inputs/internal.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/inputs/internal.py
new file mode 100644
index 0000000000000000000000000000000000000000..824d34e0e56bee5b5c86e0594bf10ff5ec6f69c2
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/inputs/internal.py
@@ -0,0 +1,315 @@
+"""The layer between launch sdk user code and the wandb internal process.
+
+If there is an active run this communication is done through the wandb run's
+backend interface.
+
+If there is no active run, the messages are staged on the StagedLaunchInputs
+singleton and sent when a run is created.
+"""
+
+import os
+import pathlib
+import shutil
+import tempfile
+from typing import Any, Dict, List, Optional
+
+import wandb
+import wandb.data_types
+from wandb.sdk.launch.errors import LaunchError
+from wandb.sdk.launch.inputs.schema import META_SCHEMA
+from wandb.util import get_module
+
+from .files import config_path_is_valid, override_file
+
+PERIOD = "."
+BACKSLASH = "\\"
+LAUNCH_MANAGED_CONFIGS_DIR = "_wandb_configs"
+
+
+class ConfigTmpDir:
+ """Singleton for managing temporary directories for configuration files.
+
+ Any configuration files designated as inputs to a launch job are copied to
+ a temporary directory. This singleton manages the temporary directory and
+ provides paths to the configuration files.
+ """
+
+ _instance = None
+
+ def __new__(cls):
+ if cls._instance is None:
+ cls._instance = object.__new__(cls)
+ return cls._instance
+
+ def __init__(self):
+ if not hasattr(self, "_tmp_dir"):
+ self._tmp_dir = tempfile.mkdtemp()
+ self._configs_dir = os.path.join(self._tmp_dir, LAUNCH_MANAGED_CONFIGS_DIR)
+ os.mkdir(self._configs_dir)
+
+ @property
+ def tmp_dir(self):
+ return pathlib.Path(self._tmp_dir)
+
+ @property
+ def configs_dir(self):
+ return pathlib.Path(self._configs_dir)
+
+
+class JobInputArguments:
+ """Arguments for the publish_job_input of Interface."""
+
+ def __init__(
+ self,
+ include: Optional[List[str]] = None,
+ exclude: Optional[List[str]] = None,
+ schema: Optional[dict] = None,
+ file_path: Optional[str] = None,
+ run_config: Optional[bool] = None,
+ ):
+ self.include = include
+ self.exclude = exclude
+ self.schema = schema
+ self.file_path = file_path
+ self.run_config = run_config
+
+
+class StagedLaunchInputs:
+ _instance = None
+
+ def __new__(cls):
+ if cls._instance is None:
+ cls._instance = object.__new__(cls)
+ return cls._instance
+
+ def __init__(self) -> None:
+ if not hasattr(self, "_staged_inputs"):
+ self._staged_inputs: List[JobInputArguments] = []
+
+ def add_staged_input(
+ self,
+ input_arguments: JobInputArguments,
+ ):
+ self._staged_inputs.append(input_arguments)
+
+ def apply(self, run: wandb.Run):
+ """Apply the staged inputs to the given run."""
+ for input in self._staged_inputs:
+ _publish_job_input(input, run)
+
+
+def _publish_job_input(
+ input: JobInputArguments,
+ run: wandb.Run,
+) -> None:
+ """Publish a job input to the backend interface of the given run.
+
+ Arguments:
+ input (JobInputArguments): The arguments for the job input.
+ run (wandb.Run): The run to publish the job input to.
+ """
+ assert run._backend is not None
+ assert run._backend.interface is not None
+ assert input.run_config is not None
+
+ interface = run._backend.interface
+ if input.file_path:
+ config_dir = ConfigTmpDir()
+ dest = os.path.join(config_dir.configs_dir, input.file_path)
+ run.save(dest, base_path=config_dir.tmp_dir)
+ interface.publish_job_input(
+ include_paths=[_split_on_unesc_dot(path) for path in input.include]
+ if input.include
+ else [],
+ exclude_paths=[_split_on_unesc_dot(path) for path in input.exclude]
+ if input.exclude
+ else [],
+ input_schema=input.schema,
+ run_config=input.run_config,
+ file_path=input.file_path or "",
+ )
+
+
+def _replace_refs_and_allofs(schema: dict, defs: Optional[dict]) -> dict:
+ """Recursively fix JSON schemas with common issues.
+
+ 1. Replaces any instances of $ref with their associated definition in defs
+ 2. Removes any "allOf" lists that only have one item, "lifting" the item up
+ See test_internal.py for examples
+ """
+ ret: Dict[str, Any] = {}
+ if "$ref" in schema and defs:
+ # Reference found, replace it with its definition
+ def_key = schema.pop("$ref").split("#/$defs/")[1]
+ # Also run recursive replacement in case a ref contains more refs
+ ret = _replace_refs_and_allofs(defs[def_key], defs)
+ for key, val in schema.items():
+ if isinstance(val, dict):
+ # Step into dicts recursively
+ new_val_dict = _replace_refs_and_allofs(val, defs)
+ ret[key] = new_val_dict
+ elif isinstance(val, list):
+ # Step into each item in the list
+ new_val_list = []
+ for item in val:
+ if isinstance(item, dict):
+ new_val_list.append(_replace_refs_and_allofs(item, defs))
+ else:
+ new_val_list.append(item)
+ # Lift up allOf blocks with only one item
+ if (
+ key == "allOf"
+ and len(new_val_list) == 1
+ and isinstance(new_val_list[0], dict)
+ ):
+ ret.update(new_val_list[0])
+ else:
+ ret[key] = new_val_list
+ else:
+ # For anything else (str, int, etc) keep it as-is
+ ret[key] = val
+ return ret
+
+
+def _prepare_schema(schema: Any) -> dict:
+ """Prepare a schema for validation.
+
+ This function prepares a schema for validation by:
+ 1. Converting a Pydantic model instance or class to a dict
+ 2. Replacing $ref with their associated definition in defs
+ 3. Removing any "allOf" lists that only have one item, "lifting" the item up
+
+ We support both an instance of a pydantic BaseModel class (e.g. schema=MySchema(...))
+ or the BaseModel class itself (e.g. schema=MySchema)
+ """
+ if hasattr(schema, "model_json_schema") and callable(
+ schema.model_json_schema # type: ignore
+ ):
+ schema = schema.model_json_schema()
+ if not isinstance(schema, dict):
+ raise LaunchError(
+ "schema must be a dict, Pydantic model instance, or Pydantic model class."
+ )
+ defs = schema.pop("$defs", None)
+ return _replace_refs_and_allofs(schema, defs)
+
+
+def _validate_schema(schema: dict) -> None:
+ jsonschema = get_module(
+ "jsonschema",
+ required="Setting job schema requires the jsonschema package. Please install it with `pip install 'wandb[launch]'`.",
+ lazy=False,
+ )
+ validator = jsonschema.Draft202012Validator(META_SCHEMA)
+ errs = sorted(validator.iter_errors(schema), key=str)
+ if errs:
+ wandb.termwarn(f"Schema includes unhandled or invalid configurations:\n{errs}")
+
+
+def handle_config_file_input(
+ path: str,
+ include: Optional[List[str]] = None,
+ exclude: Optional[List[str]] = None,
+ schema: Optional[Any] = None,
+):
+ """Declare an overridable configuration file for a launch job.
+
+ The configuration file is copied to a temporary directory and the path to
+ the copy is sent to the backend interface of the active run and used to
+ configure the job builder.
+
+ If there is no active run, the configuration file is staged and sent when a
+ run is created.
+ """
+ config_path_is_valid(path)
+ override_file(path)
+ tmp_dir = ConfigTmpDir()
+ dest = os.path.join(tmp_dir.configs_dir, path)
+ dest_dir = os.path.dirname(dest)
+ if not os.path.exists(dest_dir):
+ os.makedirs(dest_dir)
+ shutil.copy(
+ path,
+ dest,
+ )
+ if schema:
+ schema = _prepare_schema(schema)
+ _validate_schema(schema)
+ arguments = JobInputArguments(
+ include=include,
+ exclude=exclude,
+ schema=schema,
+ file_path=path,
+ run_config=False,
+ )
+ if wandb.run is not None:
+ _publish_job_input(arguments, wandb.run)
+ else:
+ staged_inputs = StagedLaunchInputs()
+ staged_inputs.add_staged_input(arguments)
+
+
+def handle_run_config_input(
+ include: Optional[List[str]] = None,
+ exclude: Optional[List[str]] = None,
+ schema: Optional[Any] = None,
+):
+ """Declare wandb.config as an overridable configuration for a launch job.
+
+ The include and exclude paths are sent to the backend interface of the
+ active run and used to configure the job builder.
+
+ If there is no active run, the include and exclude paths are staged and sent
+ when a run is created.
+ """
+ if schema:
+ schema = _prepare_schema(schema)
+ _validate_schema(schema)
+ arguments = JobInputArguments(
+ include=include,
+ exclude=exclude,
+ schema=schema,
+ run_config=True,
+ file_path=None,
+ )
+ if wandb.run is not None:
+ _publish_job_input(arguments, wandb.run)
+ else:
+ stage_inputs = StagedLaunchInputs()
+ stage_inputs.add_staged_input(arguments)
+
+
+def _split_on_unesc_dot(path: str) -> List[str]:
+ r"""Split a string on unescaped dots.
+
+ Arguments:
+ path (str): The string to split.
+
+ Raises:
+ ValueError: If the path has a trailing escape character.
+
+ Returns:
+ List[str]: The split string.
+ """
+ parts = []
+ part = ""
+ i = 0
+ while i < len(path):
+ if path[i] == BACKSLASH:
+ if i == len(path) - 1:
+ raise LaunchError(
+ f"Invalid config path {path}: trailing {BACKSLASH}.",
+ )
+ if path[i + 1] == PERIOD:
+ part += PERIOD
+ i += 2
+ elif path[i] == PERIOD:
+ parts.append(part)
+ part = ""
+ i += 1
+ else:
+ part += path[i]
+ i += 1
+ if part:
+ parts.append(part)
+ return parts
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/inputs/manage.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/inputs/manage.py
new file mode 100644
index 0000000000000000000000000000000000000000..91104eeae4e17dfdbc5fbc8f3e2f016873abffd2
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/inputs/manage.py
@@ -0,0 +1,113 @@
+"""Functions for declaring overridable configuration for launch jobs."""
+
+from typing import Any, List, Optional
+
+
+def manage_config_file(
+ path: str,
+ include: Optional[List[str]] = None,
+ exclude: Optional[List[str]] = None,
+ schema: Optional[Any] = None,
+):
+ r"""Declare an overridable configuration file for a launch job.
+
+ If a new job version is created from the active run, the configuration file
+ will be added to the job's inputs. If the job is launched and overrides
+ have been provided for the configuration file, this function will detect
+ the overrides from the environment and update the configuration file on disk.
+ Note that these overrides will only be applied in ephemeral containers.
+ `include` and `exclude` are lists of dot separated paths with the config.
+ The paths are used to filter subtrees of the configuration file out of the
+ job's inputs.
+
+ For example, given the following configuration file:
+ ```yaml
+ model:
+ name: resnet
+ layers: 18
+ training:
+ epochs: 10
+ batch_size: 32
+ ```
+
+ Passing `include=['model']` will only include the `model` subtree in the
+ job's inputs. Passing `exclude=['model.layers']` will exclude the `layers`
+ key from the `model` subtree. Note that `exclude` takes precedence over
+ `include`.
+
+ `.` is used as a separator for nested keys. If a key contains a `.`, it
+ should be escaped with a backslash, e.g. `include=[r'model\.layers']`. Note
+ the use of `r` to denote a raw string when using escape chars.
+
+ Args:
+ path (str): The path to the configuration file. This path must be
+ relative and must not contain backwards traversal, i.e. `..`.
+ include (List[str]): A list of keys to include in the configuration file.
+ exclude (List[str]): A list of keys to exclude from the configuration file.
+ schema (dict | Pydantic model): A JSON Schema or Pydantic model describing
+ describing which attributes will be editable from the Launch drawer.
+ Accepts both an instance of a Pydantic BaseModel class or the BaseModel
+ class itself.
+
+ Raises:
+ LaunchError: If the path is not valid, or if there is no active run.
+ """
+ # note: schema's Any type is because in the case where a BaseModel class is
+ # provided, its type is a pydantic internal type that we don't want our typing
+ # to depend on. schema's type should be considered
+ # "Optional[dict | ]"
+ from .internal import handle_config_file_input
+
+ return handle_config_file_input(path, include, exclude, schema)
+
+
+def manage_wandb_config(
+ include: Optional[List[str]] = None,
+ exclude: Optional[List[str]] = None,
+ schema: Optional[Any] = None,
+):
+ r"""Declare wandb.config as an overridable configuration for a launch job.
+
+ If a new job version is created from the active run, the run config
+ (wandb.config) will become an overridable input of the job. If the job is
+ launched and overrides have been provided for the run config, the overrides
+ will be applied to the run config when `wandb.init` is called.
+ `include` and `exclude` are lists of dot separated paths with the config.
+ The paths are used to filter subtrees of the configuration file out of the
+ job's inputs.
+
+ For example, given the following run config contents:
+ ```yaml
+ model:
+ name: resnet
+ layers: 18
+ training:
+ epochs: 10
+ batch_size: 32
+ ```
+ Passing `include=['model']` will only include the `model` subtree in the
+ job's inputs. Passing `exclude=['model.layers']` will exclude the `layers`
+ key from the `model` subtree. Note that `exclude` takes precedence over
+ `include`.
+ `.` is used as a separator for nested keys. If a key contains a `.`, it
+ should be escaped with a backslash, e.g. `include=[r'model\.layers']`. Note
+ the use of `r` to denote a raw string when using escape chars.
+
+ Args:
+ include (List[str]): A list of subtrees to include in the configuration.
+ exclude (List[str]): A list of subtrees to exclude from the configuration.
+ schema (dict | Pydantic model): A JSON Schema or Pydantic model describing
+ describing which attributes will be editable from the Launch drawer.
+ Accepts both an instance of a Pydantic BaseModel class or the BaseModel
+ class itself.
+
+ Raises:
+ LaunchError: If there is no active run.
+ """
+ # note: schema's Any type is because in the case where a BaseModel class is
+ # provided, its type is a pydantic internal type that we don't want our typing
+ # to depend on. schema's type should be considered
+ # "Optional[dict | ]"
+ from .internal import handle_run_config_input
+
+ handle_run_config_input(include, exclude, schema)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/inputs/schema.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/inputs/schema.py
new file mode 100644
index 0000000000000000000000000000000000000000..07c48cc07701d2646e87225859167ff8e26d82b6
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/inputs/schema.py
@@ -0,0 +1,70 @@
+META_SCHEMA = {
+ "type": "object",
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": ["boolean", "integer", "number", "string", "object", "array"],
+ },
+ "title": {"type": "string"},
+ "description": {"type": "string"},
+ "format": {"type": "string"},
+ "enum": {"type": "array", "items": {"type": ["integer", "number", "string"]}},
+ "properties": {"type": "object", "patternProperties": {".*": {"$ref": "#"}}},
+ "allOf": {"type": "array", "items": {"$ref": "#"}},
+ # Array-specific properties
+ "items": {"$ref": "#"},
+ "uniqueItems": {"type": "boolean"},
+ "minItems": {"type": "integer", "minimum": 0},
+ "maxItems": {"type": "integer", "minimum": 0},
+ },
+ "allOf": [
+ {
+ "if": {"properties": {"type": {"const": "number"}}},
+ "then": {
+ "properties": {
+ "minimum": {"type": ["integer", "number"]},
+ "maximum": {"type": ["integer", "number"]},
+ "exclusiveMinimum": {"type": ["integer", "number"]},
+ "exclusiveMaximum": {"type": ["integer", "number"]},
+ }
+ },
+ },
+ {
+ "if": {"properties": {"type": {"const": "integer"}}},
+ "then": {
+ "properties": {
+ "minimum": {"type": "integer"},
+ "maximum": {"type": "integer"},
+ "exclusiveMinimum": {"type": "integer"},
+ "exclusiveMaximum": {"type": "integer"},
+ }
+ },
+ },
+ {
+ "if": {"properties": {"type": {"const": "array"}}},
+ "then": {
+ "required": ["items"],
+ "properties": {
+ "items": {
+ "properties": {
+ "type": {"enum": ["integer", "number", "string"]},
+ "enum": {
+ "type": "array",
+ "items": {"type": ["integer", "number", "string"]},
+ },
+ "title": {"type": "string"},
+ "description": {"type": "string"},
+ "format": {"type": "string"},
+ },
+ "required": ["type", "enum"],
+ "unevaluatedProperties": False,
+ },
+ "uniqueItems": {"type": "boolean"},
+ "minItems": {"type": "integer", "minimum": 0},
+ "maxItems": {"type": "integer", "minimum": 0},
+ },
+ },
+ },
+ ],
+ "unevaluatedProperties": False,
+}
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/loader.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/loader.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8015a25d233688ab2e2e1634d0bed621121235d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/loader.py
@@ -0,0 +1,249 @@
+"""Utilities for the agent."""
+
+from typing import Any, Dict, Optional
+
+import wandb
+from wandb.apis.internal import Api
+from wandb.docker import is_docker_installed
+from wandb.sdk.launch.errors import LaunchError
+
+from .builder.abstract import AbstractBuilder
+from .environment.abstract import AbstractEnvironment
+from .registry.abstract import AbstractRegistry
+from .runner.abstract import AbstractRunner
+
+WANDB_RUNNERS = {
+ "local-container",
+ "local-process",
+ "kubernetes",
+ "vertex",
+ "sagemaker",
+}
+
+
+def environment_from_config(config: Optional[Dict[str, Any]]) -> AbstractEnvironment:
+ """Create an environment from a config.
+
+ This helper function is used to create an environment from a config. The
+ config should have a "type" key that specifies the type of environment to
+ create. The remaining keys are passed to the environment's from_config
+ method. If the config is None or empty, a LocalEnvironment is returned.
+
+ Arguments:
+ config (Dict[str, Any]): The config.
+
+ Returns:
+ Environment: The environment constructed.
+ """
+ if not config:
+ from .environment.local_environment import LocalEnvironment
+
+ return LocalEnvironment() # This is the default, dummy environment.
+ env_type = config.get("type")
+ if not env_type:
+ raise LaunchError(
+ "Could not create environment from config. Environment type not specified!"
+ )
+ if env_type == "local":
+ from .environment.local_environment import LocalEnvironment
+
+ return LocalEnvironment.from_config(config)
+ if env_type == "aws":
+ from .environment.aws_environment import AwsEnvironment
+
+ return AwsEnvironment.from_config(config)
+ if env_type == "gcp":
+ from .environment.gcp_environment import GcpEnvironment
+
+ return GcpEnvironment.from_config(config)
+ if env_type == "azure":
+ from .environment.azure_environment import AzureEnvironment
+
+ return AzureEnvironment.from_config(config)
+ raise LaunchError(
+ f"Could not create environment from config. Invalid type: {env_type}"
+ )
+
+
+def registry_from_config(
+ config: Optional[Dict[str, Any]], environment: AbstractEnvironment
+) -> AbstractRegistry:
+ """Create a registry from a config.
+
+ This helper function is used to create a registry from a config. The
+ config should have a "type" key that specifies the type of registry to
+ create. The remaining keys are passed to the registry's from_config
+ method. If the config is None or empty, a LocalRegistry is returned.
+
+ Arguments:
+ config (Dict[str, Any]): The registry config.
+ environment (Environment): The environment of the registry.
+
+ Returns:
+ The registry if config is not None, otherwise None.
+
+ Raises:
+ LaunchError: If the registry is not configured correctly.
+ """
+ if not config:
+ from .registry.local_registry import LocalRegistry
+
+ return LocalRegistry() # This is the default, dummy registry.
+
+ wandb.termwarn(
+ "The `registry` block of the launch agent config is being deprecated. "
+ "Please specify an image repository URI under the `builder.destination` "
+ "key of your launch agent config. See "
+ "https://docs.wandb.ai/guides/launch/setup-agent-advanced#agent-configuration "
+ "for more information."
+ )
+
+ registry_type = config.get("type")
+ if registry_type is None or registry_type == "local":
+ from .registry.local_registry import LocalRegistry
+
+ return LocalRegistry() # This is the default, dummy registry.
+ if registry_type == "ecr":
+ from .registry.elastic_container_registry import ElasticContainerRegistry
+
+ return ElasticContainerRegistry.from_config(config)
+ if registry_type == "gcr":
+ from .registry.google_artifact_registry import GoogleArtifactRegistry
+
+ return GoogleArtifactRegistry.from_config(config)
+ if registry_type == "acr":
+ from .registry.azure_container_registry import AzureContainerRegistry
+
+ return AzureContainerRegistry.from_config(config)
+ raise LaunchError(
+ f"Could not create registry from config. Invalid registry type: {registry_type}"
+ )
+
+
+def builder_from_config(
+ config: Optional[Dict[str, Any]],
+ environment: AbstractEnvironment,
+ registry: AbstractRegistry,
+) -> AbstractBuilder:
+ """Create a builder from a config.
+
+ This helper function is used to create a builder from a config. The
+ config should have a "type" key that specifies the type of builder to import
+ and create. The remaining keys are passed to the builder's from_config
+ method. If the config is None or empty, a default builder is returned.
+
+ The default builder will be a DockerBuilder if we find a working docker cli
+ on the system, otherwise it will be a NoOpBuilder.
+
+ Arguments:
+ config (Dict[str, Any]): The builder config.
+ registry (Registry): The registry of the builder.
+
+ Returns:
+ The builder.
+
+ Raises:
+ LaunchError: If the builder is not configured correctly.
+ """
+ if not config:
+ if is_docker_installed():
+ from .builder.docker_builder import DockerBuilder
+
+ return DockerBuilder.from_config(
+ {}, environment, registry
+ ) # This is the default builder.
+
+ from .builder.noop import NoOpBuilder
+
+ return NoOpBuilder.from_config({}, environment, registry)
+
+ builder_type = config.get("type")
+ if builder_type is None:
+ raise LaunchError(
+ "Could not create builder from config. Builder type not specified"
+ )
+ if builder_type == "docker":
+ from .builder.docker_builder import DockerBuilder
+
+ return DockerBuilder.from_config(config, environment, registry)
+ if builder_type == "kaniko":
+ from .builder.kaniko_builder import KanikoBuilder
+
+ return KanikoBuilder.from_config(config, environment, registry)
+ if builder_type == "noop":
+ from .builder.noop import NoOpBuilder
+
+ return NoOpBuilder.from_config(config, environment, registry)
+ raise LaunchError(
+ f"Could not create builder from config. Invalid builder type: {builder_type}"
+ )
+
+
+def runner_from_config(
+ runner_name: str,
+ api: Api,
+ runner_config: Dict[str, Any],
+ environment: AbstractEnvironment,
+ registry: AbstractRegistry,
+) -> AbstractRunner:
+ """Create a runner from a config.
+
+ This helper function is used to create a runner from a config. The
+ config should have a "type" key that specifies the type of runner to import
+ and create. The remaining keys are passed to the runner's from_config
+ method. If the config is None or empty, a LocalContainerRunner is returned.
+
+ Arguments:
+ runner_name (str): The name of the backend.
+ api (Api): The API.
+ runner_config (Dict[str, Any]): The backend config.
+
+ Returns:
+ The runner.
+
+ Raises:
+ LaunchError: If the runner is not configured correctly.
+ """
+ if not runner_name or runner_name in ["local-container", "local"]:
+ from .runner.local_container import LocalContainerRunner
+
+ return LocalContainerRunner(api, runner_config, environment, registry)
+ if runner_name == "local-process":
+ from .runner.local_process import LocalProcessRunner
+
+ return LocalProcessRunner(api, runner_config)
+ if runner_name == "sagemaker":
+ from .environment.aws_environment import AwsEnvironment
+
+ if not isinstance(environment, AwsEnvironment):
+ try:
+ environment = AwsEnvironment.from_default()
+ except LaunchError as e:
+ raise LaunchError(
+ "Could not create Sagemaker runner. "
+ "Environment must be an instance of AwsEnvironment."
+ ) from e
+ from .runner.sagemaker_runner import SageMakerRunner
+
+ return SageMakerRunner(api, runner_config, environment, registry)
+ if runner_name in ["vertex", "gcp-vertex"]:
+ from .environment.gcp_environment import GcpEnvironment
+
+ if not isinstance(environment, GcpEnvironment):
+ try:
+ environment = GcpEnvironment.from_default()
+ except LaunchError as e:
+ raise LaunchError(
+ "Could not create Vertex runner. "
+ "Environment must be an instance of GcpEnvironment."
+ ) from e
+ from .runner.vertex_runner import VertexRunner
+
+ return VertexRunner(api, runner_config, environment, registry)
+ if runner_name == "kubernetes":
+ from .runner.kubernetes_runner import KubernetesRunner
+
+ return KubernetesRunner(api, runner_config, environment, registry)
+ raise LaunchError(
+ f"Could not create runner from config. Invalid runner name: {runner_name}"
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/registry/abstract.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/registry/abstract.py
new file mode 100644
index 0000000000000000000000000000000000000000..9be4ba0787ff10297173a9b152833f21efa6928a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/registry/abstract.py
@@ -0,0 +1,48 @@
+"""Abstract base class for registries."""
+
+from abc import ABC, abstractmethod
+from typing import Tuple
+
+
+class AbstractRegistry(ABC):
+ """Abstract base class for registries."""
+
+ uri: str
+
+ async def get_username_password(self) -> Tuple[str, str]:
+ """Get the username and password for the registry.
+
+ Returns:
+ (str, str): The username and password.
+ """
+ raise NotImplementedError
+
+ @abstractmethod
+ async def get_repo_uri(self) -> str:
+ """Get the URI for a repository.
+
+ Returns:
+ str: The URI.
+ """
+ raise NotImplementedError
+
+ @abstractmethod
+ async def check_image_exists(self, image_uri: str) -> bool:
+ """Check if an image exists in the registry.
+
+ Arguments:
+ image_uri (str): The URI of the image.
+
+ Returns:
+ bool: True if the image exists.
+ """
+ raise NotImplementedError
+
+ @classmethod
+ @abstractmethod
+ def from_config(
+ cls,
+ config: dict,
+ ) -> "AbstractRegistry":
+ """Create a registry from a config."""
+ raise NotImplementedError
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/registry/anon.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/registry/anon.py
new file mode 100644
index 0000000000000000000000000000000000000000..7408606415fac01e234423614906e364a9561ea4
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/registry/anon.py
@@ -0,0 +1,29 @@
+from typing import Tuple
+
+from wandb.docker import is_docker_installed
+from wandb.sdk.launch.utils import docker_image_exists
+
+from .abstract import AbstractRegistry
+
+
+class AnonynmousRegistry(AbstractRegistry):
+ def __init__(self, uri: str) -> None:
+ """Initialize the registry."""
+ self.uri = uri
+
+ async def get_username_password(self) -> Tuple[str, str]:
+ """Get the username and password for the registry."""
+ raise NotImplementedError("Anonymous registry does not require authentication")
+
+ async def get_repo_uri(self) -> str:
+ return self.uri
+
+ async def check_image_exists(self, image_uri: str) -> bool:
+ """Check if an image exists in the registry."""
+ if not is_docker_installed():
+ return False
+ return docker_image_exists(image_uri)
+
+ @classmethod
+ def from_config(cls, config: dict) -> "AbstractRegistry":
+ return cls(uri=config["uri"])
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/registry/azure_container_registry.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/registry/azure_container_registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5456a778a680008ff1eec854420b9b7c8bb0831
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/registry/azure_container_registry.py
@@ -0,0 +1,124 @@
+"""Implementation of AzureContainerRegistry class."""
+
+import re
+from typing import TYPE_CHECKING, Optional, Tuple
+
+from wandb.sdk.launch.environment.azure_environment import AzureEnvironment
+from wandb.sdk.launch.errors import LaunchError
+from wandb.sdk.launch.utils import AZURE_CONTAINER_REGISTRY_URI_REGEX
+from wandb.util import get_module
+
+from .abstract import AbstractRegistry
+
+if TYPE_CHECKING:
+ from azure.containerregistry import ContainerRegistryClient # type: ignore
+ from azure.core.exceptions import ResourceNotFoundError # type: ignore
+
+
+ContainerRegistryClient = get_module(
+ "azure.containerregistry",
+ required="The azure-containerregistry package is required to use launch with Azure. Please install it with `pip install azure-containerregistry`.",
+).ContainerRegistryClient
+
+ResourceNotFoundError = get_module(
+ "azure.core.exceptions",
+ required="The azure-core package is required to use launch with Azure. Please install it with `pip install azure-core`.",
+).ResourceNotFoundError
+
+
+class AzureContainerRegistry(AbstractRegistry):
+ """Helper for accessing Azure Container Registry resources."""
+
+ def __init__(
+ self,
+ uri: Optional[str] = None,
+ registry_name: Optional[str] = None,
+ repo_name: Optional[str] = None,
+ ):
+ """Initialize an AzureContainerRegistry."""
+ if uri is not None:
+ self.uri = uri
+ if any(x is not None for x in (registry_name, repo_name)):
+ raise LaunchError(
+ "Please specify either a registry name and repo name or a registry URI."
+ )
+ if self.uri.startswith("https://"):
+ self.uri = self.uri[len("https://") :]
+ match = AZURE_CONTAINER_REGISTRY_URI_REGEX.match(self.uri)
+ if match is None:
+ raise LaunchError(
+ f"Unable to parse Azure Container Registry URI: {self.uri}"
+ )
+ self.registry_name = match.group(1)
+ self.repo_name = match.group(2)
+ else:
+ if any(x is None for x in (registry_name, repo_name)):
+ raise LaunchError(
+ "Please specify both a registry name and repo name or a registry URI."
+ )
+ self.registry_name = registry_name
+ self.repo_name = repo_name
+ self.uri = f"{self.registry_name}.azurecr.io/{self.repo_name}"
+
+ @classmethod
+ def from_config(
+ cls,
+ config: dict,
+ ) -> "AzureContainerRegistry":
+ """Create an AzureContainerRegistry from a config dict.
+
+ Args:
+ config (dict): The config dict.
+ environment (AbstractEnvironment): The environment to use.
+ verify (bool, optional): Whether to verify the registry. Defaults to True.
+
+ Returns:
+ AzureContainerRegistry: The registry.
+
+ Raises:
+ LaunchError: If the config is invalid.
+ """
+ uri = config.get("uri")
+ if uri is None:
+ raise LaunchError(
+ "Please specify a registry name to use under the registry.uri."
+ )
+ return cls(
+ uri=uri,
+ )
+
+ async def get_username_password(self) -> Tuple[str, str]:
+ """Get username and password for container registry."""
+ raise NotImplementedError
+
+ async def check_image_exists(self, image_uri: str) -> bool:
+ """Check if image exists in container registry.
+
+ Args:
+ image_uri (str): Image URI to check.
+
+ Returns:
+ bool: True if image exists, False otherwise.
+ """
+ match = re.match(AZURE_CONTAINER_REGISTRY_URI_REGEX, image_uri)
+ if match is None:
+ raise LaunchError(
+ f"Unable to parse Azure Container Registry URI: {image_uri}"
+ )
+ registry = match.group(1)
+ repository = match.group(2)
+ tag = match.group(3)
+ credential = AzureEnvironment.get_credentials()
+ client = ContainerRegistryClient(f"https://{registry}.azurecr.io", credential)
+ try:
+ client.get_manifest_properties(repository, tag)
+ return True
+ except ResourceNotFoundError:
+ return False
+ except Exception as e:
+ raise LaunchError(
+ f"Unable to check if image exists in Azure Container Registry: {e}"
+ ) from e
+
+ async def get_repo_uri(self) -> str:
+ return f"{self.registry_name}.azurecr.io/{self.repo_name}"
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/registry/elastic_container_registry.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/registry/elastic_container_registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..e731cd0688d216546b4f1d5cbaf5b96d8f1003a7
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/registry/elastic_container_registry.py
@@ -0,0 +1,192 @@
+"""Implementation of Elastic Container Registry class for wandb launch."""
+
+import base64
+import logging
+from typing import Dict, Optional, Tuple
+
+from wandb.sdk.launch.errors import LaunchError
+from wandb.sdk.launch.registry.abstract import AbstractRegistry
+from wandb.sdk.launch.utils import (
+ ELASTIC_CONTAINER_REGISTRY_URI_REGEX,
+ event_loop_thread_exec,
+)
+from wandb.util import get_module
+
+_logger = logging.getLogger(__name__)
+
+botocore = get_module(
+ "botocore",
+ required="The boto3 package is required to use launch with AWS. Please install it with `pip install wandb[launch]`.",
+)
+boto3 = get_module(
+ "boto3",
+ required="The boto3 package is required to use launch with AWS. Please install it with `pip install wandb[launch]`.",
+)
+
+
+class ElasticContainerRegistry(AbstractRegistry):
+ """Elastic Container Registry class."""
+
+ def __init__(
+ self,
+ uri: Optional[str] = None,
+ account_id: Optional[str] = None,
+ region: Optional[str] = None,
+ repo_name: Optional[str] = None,
+ ) -> None:
+ """Initialize the Elastic Container Registry.
+
+ Arguments:
+ uri: The uri of the repository.
+ account_id: The AWS account id.
+ region: The AWS region of the container registry.
+ repository: The name of the repository.
+
+ Raises:
+ LaunchError: If there is an error initializing the Elastic Container Registry helper.
+ """
+ if uri:
+ self.uri = uri
+ if any([account_id, region, repo_name]):
+ raise LaunchError(
+ "Could not create ElasticContainerRegistry from config. Either 'uri' or "
+ "'account_id', 'region', and 'repo_name' are required."
+ )
+ match = ELASTIC_CONTAINER_REGISTRY_URI_REGEX.match(
+ self.uri,
+ )
+ if not match:
+ raise LaunchError(
+ f"Could not create ElasticContainerRegistry from config. The uri "
+ f"{self.uri} is invalid."
+ )
+ self.account_id = match.group("account")
+ self.region = match.group("region")
+ self.repo_name = match.group("repository")
+ else:
+ if not all([account_id, region, repo_name]):
+ raise LaunchError(
+ "Could not create ElasticContainerRegistry from config. Either 'uri' or "
+ "'account_id', 'region', and 'repo_name' are required."
+ )
+ self.account_id = account_id
+ self.region = region
+ self.repo_name = repo_name
+ self.uri = f"{self.account_id}.dkr.ecr.{self.region}.amazonaws.com/{self.repo_name}"
+ if self.account_id is None:
+ raise LaunchError(
+ "Could not create ElasticContainerRegistry from config. Either 'uri' or "
+ "'account_id' is required."
+ )
+ if self.region is None:
+ raise LaunchError(
+ "Could not create ElasticContainerRegistry from config. Either 'uri' or "
+ "'region' is required."
+ )
+ if self.repo_name is None:
+ raise LaunchError(
+ "Could not create ElasticContainerRegistry from config. Either 'uri' or "
+ "'repository' is required."
+ )
+
+ @classmethod
+ def from_config(
+ cls,
+ config: Dict[str, str],
+ ) -> "ElasticContainerRegistry":
+ """Create an Elastic Container Registry from a config.
+
+ Arguments:
+ config (dict): The config.
+
+ Returns:
+ ElasticContainerRegistry: The Elastic Container Registry.
+ """
+ # TODO: Replace this with pydantic.
+ acceptable_keys = {
+ "uri",
+ "type",
+ "account_id",
+ "region",
+ "repo_name",
+ }
+ unsupported_keys = set(config.keys()) - acceptable_keys
+ if unsupported_keys:
+ raise LaunchError(
+ f"The Elastic Container Registry config contains unsupported keys: "
+ f"{unsupported_keys}. Please remove these keys. The acceptable "
+ f"keys are: {acceptable_keys}."
+ )
+ return cls(
+ uri=config.get("uri"),
+ account_id=config.get("account_id"),
+ region=config.get("region"),
+ repo_name=config.get("repository"),
+ )
+
+ async def get_username_password(self) -> Tuple[str, str]:
+ """Get the username and password for the registry.
+
+ Returns:
+ (str, str): The username and password.
+
+ Raises:
+ RegistryError: If there is an error getting the username and password.
+ """
+ _logger.debug("Getting username and password for Elastic Container Registry.")
+ try:
+ session = boto3.Session(region_name=self.region)
+ client = await event_loop_thread_exec(session.client)("ecr")
+ response = await event_loop_thread_exec(client.get_authorization_token)()
+ username, password = base64.standard_b64decode(
+ response["authorizationData"][0]["authorizationToken"]
+ ).split(b":")
+ return username.decode("utf-8"), password.decode("utf-8")
+
+ except botocore.exceptions.ClientError as e:
+ code = e.response["Error"]["Code"]
+ msg = e.response["Error"]["Message"]
+ # TODO: Log the code and the message here?
+ raise LaunchError(f"Error getting username and password: {code} {msg}")
+
+ async def get_repo_uri(self) -> str:
+ """Get the uri of the repository.
+
+ Returns:
+ str: The uri of the repository.
+ """
+ return f"{self.account_id}.dkr.ecr.{self.region}.amazonaws.com/{self.repo_name}"
+
+ async def check_image_exists(self, image_uri: str) -> bool:
+ """Check if the image tag exists.
+
+ Arguments:
+ image_uri (str): The full image_uri.
+
+ Returns:
+ bool: True if the image tag exists.
+ """
+ if ":" not in image_uri:
+ tag = image_uri
+ else:
+ uri, tag = image_uri.split(":")
+ repo_uri = await self.get_repo_uri()
+ if uri != repo_uri:
+ raise LaunchError(
+ f"Image uri {image_uri} does not match Elastic Container Registry uri {repo_uri}."
+ )
+ _logger.debug(f"Checking if image tag {tag} exists in repository {self.uri}")
+ try:
+ session = boto3.Session(region_name=self.region)
+ client = await event_loop_thread_exec(session.client)("ecr")
+ response = await event_loop_thread_exec(client.describe_images)(
+ repositoryName=self.repo_name, imageIds=[{"imageTag": tag}]
+ )
+ return len(response["imageDetails"]) > 0
+
+ except botocore.exceptions.ClientError as e:
+ code = e.response["Error"]["Code"]
+ if code == "ImageNotFoundException":
+ return False
+ msg = e.response["Error"]["Message"]
+ raise LaunchError(f"Error checking if image tag exists: {code} {msg}")
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/registry/google_artifact_registry.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/registry/google_artifact_registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..088e1b540f3eb50f0d40f020513f11baa8fe1369
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/registry/google_artifact_registry.py
@@ -0,0 +1,219 @@
+"""Implementation of Google Artifact Registry for wandb launch."""
+
+import logging
+from typing import Optional, Tuple
+
+import google.auth # type: ignore
+import google.cloud.artifactregistry # type: ignore
+
+from wandb.sdk.launch.errors import LaunchError
+from wandb.sdk.launch.utils import (
+ GCP_ARTIFACT_REGISTRY_URI_REGEX,
+ event_loop_thread_exec,
+)
+from wandb.util import get_module
+
+from .abstract import AbstractRegistry
+
+_logger = logging.getLogger(__name__)
+
+google = get_module(
+ "google",
+ required="The google package is required to use launch with Google. Please install it with `pip install wandb[launch]`.",
+)
+google.auth = get_module(
+ "google.auth",
+ required="The google-auth package is required to use launch with Google. Please install it with `pip install wandb[launch]`.",
+)
+
+google.cloud.artifactregistry = get_module(
+ "google.cloud.artifactregistry",
+ required="The google-cloud-artifactregistry package is required to use launch with Google. Please install it with `pip install wandb[launch]`.",
+)
+
+
+class GoogleArtifactRegistry(AbstractRegistry):
+ """Google Artifact Registry helper for interacting with the registry.
+
+ This helper should be constructed from either a uri or a repository,
+ project, and optional image-name. If constructed from a uri, the uri
+ must be of the form REGION-docker.pkg.dev/PROJECT/REPOSITORY/[IMAGE_NAME],
+ with an optional https:// preceding.
+ """
+
+ def __init__(
+ self,
+ uri: Optional[str] = None,
+ repository: Optional[str] = None,
+ image_name: Optional[str] = None,
+ project: Optional[str] = None,
+ region: Optional[str] = None,
+ ) -> None:
+ """Initialize the Google Artifact Registry.
+
+ Either uri or repository and image_name must be provided. Project and
+ region are optional, and will be inferred from the uri if provided, or
+ from the default credentials if not.
+
+ Arguments:
+ uri (optional): The uri of the repository.
+ repository (optional): The repository name.
+ image_name (optional): The image name.
+ project (optional): The GCP project name.
+ region (optional): The GCP region name.
+
+ Raises:
+ LaunchError: If verify is True and the container registry or its
+ environment have not been properly configured. Or if the environment
+ is not an instance of GcpEnvironment.
+ """
+ _logger.info(
+ f"Initializing Google Artifact Registry with repository {repository} "
+ f"and image name {image_name}"
+ )
+
+ if uri is not None:
+ self.uri = uri
+ # Raise an error if any other kwargs were provided in addition to uri.
+ if any([repository, image_name, project, region]):
+ raise LaunchError(
+ "The Google Artifact Registry must be specified with either "
+ "the uri key or the repository, image-name, project and region "
+ "keys, but not both."
+ )
+ match = GCP_ARTIFACT_REGISTRY_URI_REGEX.match(self.uri)
+ if not match:
+ raise LaunchError(
+ f"The Google Artifact Registry uri {self.uri} is invalid. "
+ "Please provide a uri of the form "
+ "REGION-docker.pkg.dev/PROJECT/REPOSITORY/IMAGE_NAME."
+ )
+ self.project = match.group("project")
+ self.region = match.group("region")
+ self.repository = match.group("repository")
+ self.image_name = match.group("image_name")
+ else:
+ if any(x is None for x in (repository, region, image_name)):
+ raise LaunchError(
+ "The Google Artifact Registry must be specified with either "
+ "the uri key or the repository, image-name, project and region "
+ "keys."
+ )
+ self.project = project
+ self.region = region
+ self.repository = repository
+ self.image_name = image_name
+ self.uri = f"{self.region}-docker.pkg.dev/{self.project}/{self.repository}/{self.image_name}"
+
+ _missing_kwarg_msg = (
+ "The Google Artifact Registry is missing the {} kwarg. "
+ "Please specify it by name or as part of the uri argument."
+ )
+ if not self.region:
+ raise LaunchError(_missing_kwarg_msg.format("region"))
+ if not self.repository:
+ raise LaunchError(_missing_kwarg_msg.format("repository"))
+ if not self.image_name:
+ raise LaunchError(_missing_kwarg_msg.format("image-name"))
+ # Try to load default project from the default credentials.
+ self.credentials, project = google.auth.default()
+ self.project = self.project or project
+ self.credentials.refresh(google.auth.transport.requests.Request())
+
+ @classmethod
+ def from_config(
+ cls,
+ config: dict,
+ ) -> "GoogleArtifactRegistry":
+ """Create a Google Artifact Registry from a config.
+
+ Arguments:
+ config: A dictionary containing the following keys:
+ repository: The repository name.
+ image-name: The image name.
+ environment: A GcpEnvironment configured for access to this registry.
+
+ Returns:
+ A GoogleArtifactRegistry.
+ """
+ # TODO: Replace this with pydantic.
+ acceptable_keys = {
+ "uri",
+ "type",
+ "repository",
+ "image-name",
+ "region",
+ "project",
+ }
+ unacceptable_keys = set(config.keys()) - acceptable_keys
+ if unacceptable_keys:
+ raise LaunchError(
+ f"The Google Artifact Registry config contains unacceptable keys: "
+ f"{unacceptable_keys}. Please remove these keys. The acceptable "
+ f"keys are: {acceptable_keys}."
+ )
+ return cls(
+ uri=config.get("uri"),
+ repository=config.get("repository"),
+ image_name=config.get("image-name"),
+ project=config.get("project"),
+ region=config.get("region"),
+ )
+
+ async def get_username_password(self) -> Tuple[str, str]:
+ """Get the username and password for the registry.
+
+ Returns:
+ A tuple of the username and password.
+ """
+ if not self.credentials.token:
+ self.credentials.refresh(google.auth.transport.requests.Request())
+ return "oauth2accesstoken", self.credentials.token
+
+ async def get_repo_uri(self) -> str:
+ """Get the URI for the given repository.
+
+ Arguments:
+ repo_name: The repository name.
+
+ Returns:
+ The repository URI.
+ """
+ return (
+ f"{self.region}-docker.pkg.dev/"
+ f"{self.project}/{self.repository}/{self.image_name}"
+ )
+
+ async def check_image_exists(self, image_uri: str) -> bool:
+ """Check if the image exists.
+
+ Arguments:
+ image_uri: The image URI.
+
+ Returns:
+ True if the image exists, False otherwise.
+ """
+ _logger.info(f"Checking if image {image_uri} exists")
+ repo_uri, tag = image_uri.split(":")
+ self_repo_uri = await self.get_repo_uri()
+ if repo_uri != self_repo_uri:
+ raise LaunchError(
+ f"The image {image_uri} does not match to the image uri "
+ f"repository {self.uri}."
+ )
+ parent = f"projects/{self.project}/locations/{self.region}/repositories/{self.repository}"
+ artifact_registry_client = event_loop_thread_exec(
+ google.cloud.artifactregistry.ArtifactRegistryClient
+ )
+ client = await artifact_registry_client(credentials=self.credentials)
+ list_images = event_loop_thread_exec(client.list_docker_images)
+ try:
+ for image in await list_images(request={"parent": parent}):
+ if tag in image.tags:
+ return True
+ except google.api_core.exceptions.NotFound as e: # type: ignore[attr-defined]
+ raise LaunchError(
+ f"The Google Artifact Registry repository {self.repository} "
+ f"does not exist. Please create it or modify your registry configuration."
+ ) from e
+ return False
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/registry/local_registry.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/registry/local_registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e17369237662d87225ea7c04ab40095329b69c4
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/registry/local_registry.py
@@ -0,0 +1,65 @@
+"""Local registry implementation."""
+
+import logging
+from typing import Tuple
+
+from wandb.docker import is_docker_installed
+from wandb.sdk.launch.errors import LaunchError
+from wandb.sdk.launch.utils import docker_image_exists
+
+from .abstract import AbstractRegistry
+
+_logger = logging.getLogger(__name__)
+
+
+class LocalRegistry(AbstractRegistry):
+ """A local registry.
+
+ This is a dummy registry that is used when no registry is configured.
+ """
+
+ def __init__(self) -> None:
+ """Initialize a local registry."""
+
+ @classmethod
+ def from_config(
+ cls,
+ config: dict,
+ ) -> "LocalRegistry":
+ """Create a local registry from a config.
+
+ Arguments:
+ config (dict): The config. This is ignored.
+ environment (AbstractEnvironment): The environment. This is ignored.
+
+ Returns:
+ LocalRegistry: The local registry.
+ """
+ return cls()
+
+ async def verify(self) -> None:
+ """Verify the local registry by doing nothing."""
+
+ async def get_username_password(self) -> Tuple[str, str]:
+ """Get the username and password of the local registry."""
+ raise LaunchError("Attempted to get username and password for LocalRegistry.")
+
+ async def get_repo_uri(self) -> str:
+ """Get the uri of the local registry.
+
+ Returns: An empty string.
+ """
+ return ""
+
+ async def check_image_exists(self, image_uri: str) -> bool:
+ """Check if an image exists in the local registry.
+
+ Arguments:
+ image_uri (str): The uri of the image.
+
+ Returns:
+ bool: True.
+ """
+ if is_docker_installed():
+ return docker_image_exists(image_uri)
+ return False
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/abstract.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/abstract.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1f42e6b80dd60f933e396f94424b88e8c985786
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/abstract.py
@@ -0,0 +1,185 @@
+"""Implementation of the abstract runner class.
+
+This class defines the interface that the W&B launch runner uses to manage the lifecycle
+of runs launched in different environments (e.g. runs launched locally or in a cluster).
+"""
+
+import logging
+import os
+import shutil
+import subprocess
+import sys
+from abc import ABC, abstractmethod
+from typing import Any, Dict, List, Literal, Optional, Union
+
+import wandb
+from wandb.apis.internal import Api
+from wandb.sdk.lib import runid
+
+from .._project_spec import LaunchProject
+
+_logger = logging.getLogger(__name__)
+
+
+State = Literal[
+ "unknown",
+ "starting",
+ "running",
+ "failed",
+ "finished",
+ "stopping",
+ "stopped",
+ "preempted",
+]
+
+
+class Status:
+ def __init__(self, state: "State" = "unknown", messages: List[str] = None): # type: ignore
+ self.state = state
+ self.messages = messages or []
+
+ def __repr__(self) -> "State":
+ return self.state
+
+ def __str__(self) -> str:
+ return self.state
+
+ def __eq__(self, __value: object) -> bool:
+ if isinstance(__value, Status):
+ return self.state == __value.state
+ else:
+ return self.state == __value
+
+ def __hash__(self) -> int:
+ return hash(self.state)
+
+
+class AbstractRun(ABC):
+ """Wrapper around a W&B launch run.
+
+ A launched run is a subprocess running an entry point
+ command, that exposes methods for waiting on and cancelling the run.
+ This class defines the interface that the W&B launch runner uses to manage the lifecycle
+ of runs launched in different environments (e.g. runs launched locally or in a cluster).
+ ``AbstractRun`` is not thread-safe. That is, concurrent calls to wait() / cancel()
+ from multiple threads may inadvertently kill resources (e.g. local processes) unrelated to the
+ run.
+ """
+
+ def __init__(self) -> None:
+ self._status = Status()
+
+ @property
+ def status(self) -> Status:
+ return self._status
+
+ @abstractmethod
+ async def get_logs(self) -> Optional[str]:
+ """Return the logs associated with the run."""
+
+ def _run_cmd(
+ self, cmd: List[str], output_only: Optional[bool] = False
+ ) -> Optional[Union["subprocess.Popen[bytes]", bytes]]:
+ """Run the command and returns a popen object or the stdout of the command.
+
+ Arguments:
+ cmd: The command to run
+ output_only: If true just return the stdout bytes
+ """
+ try:
+ env = os.environ
+ popen = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE)
+ if output_only:
+ popen.wait()
+ if popen.stdout is not None:
+ return popen.stdout.read()
+ return popen
+ except subprocess.CalledProcessError as e:
+ wandb.termerror(f"Command failed: {e}")
+ return None
+
+ @abstractmethod
+ async def wait(self) -> bool:
+ """Wait for the run to finish, returning True if the run succeeded and false otherwise.
+
+ Note that in some cases, we may wait until the remote job completes rather than until the W&B run completes.
+ """
+
+ @abstractmethod
+ async def get_status(self) -> Status:
+ """Get status of the run."""
+
+ @abstractmethod
+ async def cancel(self) -> None:
+ """Cancel the run (interrupts the command subprocess, cancels the run, etc).
+
+ Cancels the run and waits for it to terminate. The W&B run status may not be
+ set correctly upon run cancellation.
+ """
+
+ @property
+ @abstractmethod
+ def id(self) -> Optional[str]:
+ pass
+
+
+class AbstractRunner(ABC):
+ """Abstract plugin class defining the interface needed to execute W&B Launches.
+
+ You can define subclasses of ``AbstractRunner`` and expose them as third-party
+ plugins to enable running W&B projects against custom execution backends
+ (e.g. to run projects against your team's in-house cluster or job scheduler).
+ """
+
+ _type: str
+
+ def __init__(
+ self,
+ api: Api,
+ backend_config: Dict[str, Any],
+ ) -> None:
+ self._api = api
+ self.backend_config = backend_config
+ self._cwd = os.getcwd()
+ self._namespace = runid.generate_id()
+
+ def find_executable(
+ self,
+ cmd: str,
+ ) -> Union[str, None]:
+ """Cross platform utility for checking if a program is available."""
+ return shutil.which(cmd)
+
+ @property
+ def api_key(self) -> Any:
+ return self._api.api_key
+
+ def verify(self) -> bool:
+ """This is called on first boot to verify the needed commands, and permissions are available.
+
+ For now just call `wandb.termerror` and `sys.exit(1)`
+ """
+ if self._api.api_key is None:
+ wandb.termerror(
+ "Couldn't find W&B api key, run wandb login or set WANDB_API_KEY"
+ )
+ sys.exit(1)
+ return True
+
+ @abstractmethod
+ async def run(
+ self,
+ launch_project: LaunchProject,
+ image_uri: str,
+ ) -> Optional[AbstractRun]:
+ """Submit an LaunchProject to be run.
+
+ Returns a SubmittedRun object to track the execution
+ Arguments:
+ launch_project: Object of _project_spec.LaunchProject class representing a wandb launch project
+
+ Returns:
+ A :py:class:`wandb.sdk.launch.runners.SubmittedRun`. This function is expected to run
+ the project asynchronously, i.e. it should trigger project execution and then
+ immediately return a `SubmittedRun` to track execution status.
+ """
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/kubernetes_monitor.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/kubernetes_monitor.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8a4b8cb20e795889ccd8e2a579a723b5da4d448
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/kubernetes_monitor.py
@@ -0,0 +1,473 @@
+"""Monitors kubernetes resources managed by the launch agent."""
+
+import asyncio
+import logging
+import traceback
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import kubernetes_asyncio # type: ignore
+import urllib3
+from kubernetes_asyncio import watch
+from kubernetes_asyncio.client import ( # type: ignore
+ ApiException,
+ BatchV1Api,
+ CoreV1Api,
+ CustomObjectsApi,
+ V1Pod,
+ V1PodStatus,
+)
+
+import wandb
+from wandb.sdk.launch.agent import LaunchAgent
+from wandb.sdk.launch.errors import LaunchError
+from wandb.sdk.launch.runner.abstract import State, Status
+from wandb.sdk.launch.utils import get_kube_context_and_api_client
+
+WANDB_K8S_LABEL_NAMESPACE = "wandb.ai"
+WANDB_K8S_RUN_ID = f"{WANDB_K8S_LABEL_NAMESPACE}/run-id"
+WANDB_K8S_LABEL_AGENT = f"{WANDB_K8S_LABEL_NAMESPACE}/agent"
+WANDB_K8S_LABEL_MONITOR = f"{WANDB_K8S_LABEL_NAMESPACE}/monitor"
+WANDB_K8S_LABEL_AUXILIARY_RESOURCE = f"{WANDB_K8S_LABEL_NAMESPACE}/auxiliary-resource"
+
+
+class Resources:
+ JOBS = "jobs"
+ PODS = "pods"
+
+
+class CustomResource:
+ """Class for custom resources."""
+
+ def __init__(self, group: str, version: str, plural: str) -> None:
+ """Initialize the CustomResource."""
+ self.group = group
+ self.version = version
+ self.plural = plural
+
+ def __str__(self) -> str:
+ """Return a string representation of the CustomResource."""
+ return f"{self.group}/{self.version}/{self.plural}"
+
+ def __hash__(self) -> int:
+ """Return a hash of the CustomResource."""
+ return hash(str(self))
+
+
+# Maps phases and conditions of custom objects to agent's internal run states.
+CRD_STATE_DICT: Dict[str, State] = {
+ "created": "starting",
+ "pending": "starting",
+ "running": "running",
+ "completing": "running",
+ "succeeded": "finished",
+ "completed": "finished",
+ "failed": "failed",
+ "aborted": "failed",
+ "timeout": "failed",
+ "terminated": "failed",
+ "terminating": "stopping",
+}
+
+_logger = logging.getLogger(__name__)
+
+
+def create_named_task(name: str, coro: Any, *args: Any, **kwargs: Any) -> asyncio.Task:
+ """Create a named task."""
+ task = asyncio.create_task(coro(*args, **kwargs))
+ task.set_name(name)
+ task.add_done_callback(_log_err_task_callback)
+ return task
+
+
+def _log_err_task_callback(task: asyncio.Task) -> None:
+ """Callback to log exceptions from tasks."""
+ exec = task.exception()
+ if exec is not None:
+ if isinstance(exec, asyncio.CancelledError):
+ wandb.termlog(f"Task {task.get_name()} was cancelled")
+ return
+ name = task.get_name()
+ wandb.termerror(f"Exception in task {name}")
+ tb = exec.__traceback__
+ tb_str = "".join(traceback.format_tb(tb))
+ wandb.termerror(tb_str)
+
+
+def _is_preempted(status: "V1PodStatus") -> bool:
+ """Check if this pod has been preempted."""
+ if hasattr(status, "conditions") and status.conditions is not None:
+ for condition in status.conditions:
+ if condition.type == "DisruptionTarget" and condition.reason in [
+ "EvictionByEvictionAPI",
+ "PreemptionByScheduler",
+ "TerminationByKubelet",
+ ]:
+ return True
+ return False
+
+
+def _is_container_creating(status: "V1PodStatus") -> bool:
+ """Check if this pod has started creating containers."""
+ for container_status in status.container_statuses or []:
+ if (
+ container_status.state
+ and container_status.state.waiting
+ and container_status.state.waiting.reason == "ContainerCreating"
+ ):
+ return True
+ return False
+
+
+def _is_pod_unschedulable(status: "V1PodStatus") -> Tuple[bool, str]:
+ """Return whether the pod is unschedulable along with the reason message."""
+ if not status.conditions:
+ return False, ""
+ for condition in status.conditions:
+ if (
+ condition.type == "PodScheduled"
+ and condition.status == "False"
+ and condition.reason == "Unschedulable"
+ ):
+ return True, condition.message
+ return False, ""
+
+
+def _get_crd_job_name(object: "V1Pod") -> Optional[str]:
+ refs = object.metadata.owner_references
+ if refs:
+ return refs[0].name
+ return None
+
+
+def _state_from_conditions(conditions: List[Dict[str, Any]]) -> Optional[State]:
+ """Get the status from the pod conditions."""
+ true_conditions = [
+ c.get("type", "").lower() for c in conditions if c.get("status") == "True"
+ ]
+ detected_states = {
+ CRD_STATE_DICT[c] for c in true_conditions if c in CRD_STATE_DICT
+ }
+ # The list below is ordered so that returning the first state detected
+ # will accurately reflect the state of the job.
+ states_in_order: List[State] = [
+ "finished",
+ "failed",
+ "stopping",
+ "running",
+ "starting",
+ ]
+ for state in states_in_order:
+ if state in detected_states:
+ return state
+ return None
+
+
+def _state_from_replicated_status(status_dict: Dict[str, int]) -> Optional[State]:
+ """Infer overall job status from replicated job status for jobsets.
+
+ More info on jobset:
+ https://github.com/kubernetes-sigs/jobset/blob/main/docs/concepts/README.md
+
+ This is useful for detecting when jobsets are starting.
+ """
+ pods_ready = status_dict.get("ready", 0)
+ pods_active = status_dict.get("active", 0)
+ if pods_ready >= 1:
+ return "running"
+ elif pods_active >= 1:
+ return "starting"
+ return None
+
+
+class LaunchKubernetesMonitor:
+ """Monitors kubernetes resources managed by the launch agent.
+
+ Note: this class is forced to be a singleton in order to prevent multiple
+ threads from being created that monitor the same kubernetes resources.
+ """
+
+ _instance = None # This is used to ensure only one instance is created.
+
+ def __new__(cls, *args: Any, **kwargs: Any) -> "LaunchKubernetesMonitor":
+ """Create a new instance of the LaunchKubernetesMonitor.
+
+ This method ensures that only one instance of the LaunchKubernetesMonitor
+ is created. This is done to prevent multiple threads from being created
+ that monitor the same kubernetes resources.
+ """
+ if cls._instance is None:
+ cls._instance = super().__new__(cls)
+ return cls._instance
+
+ def __init__(
+ self,
+ core_api: CoreV1Api,
+ batch_api: BatchV1Api,
+ custom_api: CustomObjectsApi,
+ label_selector: str,
+ ):
+ """Initialize the LaunchKubernetesMonitor."""
+ self._core_api: CoreV1Api = core_api
+ self._batch_api: BatchV1Api = batch_api
+ self._custom_api: CustomObjectsApi = custom_api
+
+ self._label_selector: str = label_selector
+
+ # Dict mapping a tuple of (namespace, resource_type) to an
+ # asyncio.Task that is monitoring that resource type in that namespace.
+ self._monitor_tasks: Dict[
+ Tuple[str, Union[str, CustomResource]], asyncio.Task
+ ] = dict()
+
+ # Map from job name to job state.
+ self._job_states: Dict[str, Status] = dict()
+
+ @classmethod
+ async def ensure_initialized(
+ cls,
+ ) -> None:
+ """Initialize the LaunchKubernetesMonitor."""
+ if cls._instance is None:
+ _, api_client = await get_kube_context_and_api_client(
+ kubernetes_asyncio, {}
+ )
+ core_api = CoreV1Api(api_client)
+ batch_api = BatchV1Api(api_client)
+ custom_api = CustomObjectsApi(api_client)
+ label_selector = f"{WANDB_K8S_LABEL_MONITOR}=true"
+ if LaunchAgent.initialized():
+ label_selector += f",{WANDB_K8S_LABEL_AGENT}={LaunchAgent.name()}"
+ cls(
+ core_api=core_api,
+ batch_api=batch_api,
+ custom_api=custom_api,
+ label_selector=label_selector,
+ )
+
+ @classmethod
+ def monitor_namespace(
+ cls, namespace: str, custom_resource: Optional[CustomResource] = None
+ ) -> None:
+ """Start monitoring a namespaces for resources."""
+ if cls._instance is None:
+ raise LaunchError(
+ "LaunchKubernetesMonitor not initialized, cannot monitor namespace."
+ )
+ cls._instance.__monitor_namespace(namespace, custom_resource=custom_resource)
+
+ @classmethod
+ def get_status(cls, job_name: str) -> Status:
+ """Get the status of a job."""
+ if cls._instance is None:
+ raise LaunchError(
+ "LaunchKubernetesMonitor not initialized, cannot get status."
+ )
+ return cls._instance.__get_status(job_name)
+
+ @classmethod
+ def status_count(cls) -> Dict[State, int]:
+ """Get a dictionary mapping statuses to the # monitored jobs with each status."""
+ if cls._instance is None:
+ raise ValueError(
+ "LaunchKubernetesMonitor not initialized, cannot get status counts."
+ )
+ return cls._instance.__status_count()
+
+ def __monitor_namespace(
+ self, namespace: str, custom_resource: Optional[CustomResource] = None
+ ) -> None:
+ """Start monitoring a namespaces for resources."""
+ if (namespace, Resources.PODS) not in self._monitor_tasks:
+ self._monitor_tasks[(namespace, Resources.PODS)] = create_named_task(
+ f"monitor_pods_{namespace}",
+ self._monitor_pods,
+ namespace,
+ )
+ # If a custom resource is specified then we will start monitoring
+ # that resource type in the namespace instead of jobs.
+ if custom_resource is not None:
+ if (namespace, custom_resource) not in self._monitor_tasks:
+ self._monitor_tasks[(namespace, custom_resource)] = create_named_task(
+ f"monitor_{custom_resource}_{namespace}",
+ self._monitor_crd,
+ namespace,
+ custom_resource=custom_resource,
+ )
+ else:
+ if (namespace, Resources.JOBS) not in self._monitor_tasks:
+ self._monitor_tasks[(namespace, Resources.JOBS)] = create_named_task(
+ f"monitor_jobs_{namespace}",
+ self._monitor_jobs,
+ namespace,
+ )
+
+ def __get_status(self, job_name: str) -> Status:
+ """Get the status of a job."""
+ if job_name not in self._job_states:
+ return Status("unknown")
+ state = self._job_states[job_name]
+ return state
+
+ def __status_count(self) -> Dict[State, int]:
+ """Get a dictionary mapping statuses to the # monitored jobs with each status."""
+ counts = dict()
+ for _, status in self._job_states.items():
+ state = status.state
+ if state not in counts:
+ counts[state] = 1
+ else:
+ counts[state] += 1
+ return counts
+
+ def _set_status_state(self, job_name: str, state: State) -> None:
+ """Set the status of the run."""
+ if job_name not in self._job_states:
+ self._job_states[job_name] = Status(state)
+ elif self._job_states[job_name].state != state:
+ self._job_states[job_name].state = state
+
+ def _add_status_message(self, job_name: str, message: str) -> None:
+ if job_name not in self._job_states:
+ self._job_states[job_name] = Status("unknown")
+ wandb.termwarn(f"Warning from Kubernetes for job {job_name}: {message}")
+ self._job_states[job_name].messages.append(message)
+
+ async def _monitor_pods(self, namespace: str) -> None:
+ """Monitor a namespace for changes."""
+ watcher = SafeWatch(watch.Watch())
+ async for event in watcher.stream(
+ self._core_api.list_namespaced_pod,
+ namespace=namespace,
+ label_selector=self._label_selector,
+ ):
+ obj = event.get("object")
+ job_name = obj.metadata.labels.get("job-name") or _get_crd_job_name(obj)
+ if job_name is None or not hasattr(obj, "status"):
+ continue
+ if self.__get_status(job_name) in ["finished", "failed"]:
+ continue
+
+ is_unschedulable, reason = _is_pod_unschedulable(obj.status)
+ if is_unschedulable:
+ self._add_status_message(job_name, reason)
+ if obj.status.phase == "Running" or _is_container_creating(obj.status):
+ self._set_status_state(job_name, "running")
+ elif _is_preempted(obj.status):
+ self._set_status_state(job_name, "preempted")
+
+ async def _monitor_jobs(self, namespace: str) -> None:
+ """Monitor a namespace for changes."""
+ watcher = SafeWatch(watch.Watch())
+ async for event in watcher.stream(
+ self._batch_api.list_namespaced_job,
+ namespace=namespace,
+ label_selector=self._label_selector,
+ ):
+ obj = event.get("object")
+ job_name = obj.metadata.name
+
+ if obj.status.succeeded == 1:
+ self._set_status_state(job_name, "finished")
+ elif obj.status.failed is not None and obj.status.failed >= 1:
+ self._set_status_state(job_name, "failed")
+
+ # If the job is deleted and we haven't seen a terminal state
+ # then we will consider the job failed.
+ if event.get("type") == "DELETED":
+ if self._job_states.get(job_name) != Status("finished"):
+ self._set_status_state(job_name, "failed")
+
+ async def _monitor_crd(
+ self, namespace: str, custom_resource: CustomResource
+ ) -> None:
+ """Monitor a namespace for changes."""
+ watcher = SafeWatch(watch.Watch())
+ async for event in watcher.stream(
+ self._custom_api.list_namespaced_custom_object,
+ namespace=namespace,
+ plural=custom_resource.plural,
+ group=custom_resource.group,
+ version=custom_resource.version,
+ label_selector=self._label_selector,
+ ):
+ object = event.get("object")
+ name = object.get("metadata", dict()).get("name")
+ status = object.get("status")
+ state = None
+ if status is None:
+ continue
+ replicated_jobs_status = status.get("ReplicatedJobsStatus")
+ if isinstance(replicated_jobs_status, dict):
+ state = _state_from_replicated_status(replicated_jobs_status)
+ state_dict = status.get("state")
+ if isinstance(state_dict, dict):
+ phase = state_dict.get("phase")
+ if phase:
+ state = CRD_STATE_DICT.get(phase.lower())
+ else:
+ conditions = status.get("conditions")
+ if isinstance(conditions, list):
+ state = _state_from_conditions(conditions)
+ else:
+ # This should never happen.
+ _logger.warning(
+ f"Unexpected conditions type {type(conditions)} "
+ f"for CRD watcher in {namespace}"
+ )
+ if state is None:
+ continue
+ self._set_status_state(name, state)
+
+
+class SafeWatch:
+ """Wrapper for the kubernetes watch class that can recover in more situations."""
+
+ def __init__(self, watcher: watch.Watch) -> None:
+ """Initialize the SafeWatch."""
+ self._watcher = watcher
+ self._last_seen_resource_version: Optional[str] = None
+ self._stopped = False
+
+ async def stream(self, func: Any, *args: Any, **kwargs: Any) -> Any:
+ """Stream the watcher.
+
+ This method will automatically resume the stream if it breaks. It will
+ also save the resource version so that the stream can be resumed from
+ the last seen resource version.
+ """
+ while True:
+ try:
+ async for event in self._watcher.stream(
+ func, *args, **kwargs, timeout_seconds=30
+ ):
+ if self._stopped:
+ break
+ # Save the resource version so that we can resume the stream
+ # if it breaks.
+ object = event.get("object")
+ if isinstance(object, dict):
+ self._last_seen_resource_version = object.get(
+ "metadata", dict()
+ ).get("resourceVersion")
+ else:
+ self._last_seen_resource_version = (
+ object.metadata.resource_version
+ )
+ kwargs["resource_version"] = self._last_seen_resource_version
+ yield event
+ # If stream ends after stop just break
+ if self._stopped:
+ break
+ except urllib3.exceptions.ProtocolError as e:
+ wandb.termwarn(f"Broken event stream: {e}, attempting to recover")
+ except ApiException as e:
+ if e.status == 410:
+ # If resource version is too old we need to start over.
+ del kwargs["resource_version"]
+ self._last_seen_resource_version = None
+ except Exception as E:
+ exc_type = type(E).__name__
+ stack_trace = traceback.format_exc()
+ wandb.termerror(
+ f"Unknown exception in event stream of type {exc_type}: {E}, attempting to recover. Stack trace: {stack_trace}"
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/kubernetes_runner.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/kubernetes_runner.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a1ca13cd7ee961ee93fc7d87a074dbfafab496e
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/kubernetes_runner.py
@@ -0,0 +1,1290 @@
+"""Implementation of KubernetesRunner class for wandb launch."""
+
+import asyncio
+import base64
+import datetime
+import json
+import logging
+import os
+import time
+from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
+
+import yaml
+
+import wandb
+from wandb.apis.internal import Api
+from wandb.sdk.launch.agent.agent import LaunchAgent
+from wandb.sdk.launch.environment.abstract import AbstractEnvironment
+from wandb.sdk.launch.registry.abstract import AbstractRegistry
+from wandb.sdk.launch.registry.azure_container_registry import AzureContainerRegistry
+from wandb.sdk.launch.registry.local_registry import LocalRegistry
+from wandb.sdk.launch.runner.abstract import Status
+from wandb.sdk.launch.runner.kubernetes_monitor import (
+ WANDB_K8S_LABEL_AGENT,
+ WANDB_K8S_LABEL_AUXILIARY_RESOURCE,
+ WANDB_K8S_LABEL_MONITOR,
+ WANDB_K8S_RUN_ID,
+ CustomResource,
+ LaunchKubernetesMonitor,
+)
+from wandb.sdk.launch.utils import (
+ recursive_macro_sub,
+ sanitize_identifiers_for_k8s,
+ yield_containers,
+)
+from wandb.sdk.lib.retry import ExponentialBackoff, retry_async
+from wandb.util import get_module
+
+from .._project_spec import EntryPoint, LaunchProject
+from ..errors import LaunchError
+from ..utils import (
+ CODE_MOUNT_DIR,
+ LOG_PREFIX,
+ MAX_ENV_LENGTHS,
+ PROJECT_SYNCHRONOUS,
+ get_kube_context_and_api_client,
+ make_k8s_label_safe,
+ make_name_dns_safe,
+)
+from .abstract import AbstractRun, AbstractRunner
+
+get_module(
+ "kubernetes_asyncio",
+ required="Kubernetes runner requires the kubernetes package. Please install it with `pip install wandb[launch]`.",
+)
+
+import kubernetes_asyncio # type: ignore # noqa: E402
+from kubernetes_asyncio import client # noqa: E402
+from kubernetes_asyncio.client.api.apps_v1_api import ( # type: ignore # noqa: E402
+ AppsV1Api,
+)
+from kubernetes_asyncio.client.api.batch_v1_api import ( # type: ignore # noqa: E402
+ BatchV1Api,
+)
+from kubernetes_asyncio.client.api.core_v1_api import ( # type: ignore # noqa: E402
+ CoreV1Api,
+)
+from kubernetes_asyncio.client.api.custom_objects_api import ( # type: ignore # noqa: E402
+ CustomObjectsApi,
+)
+from kubernetes_asyncio.client.api.networking_v1_api import ( # type: ignore # noqa: E402
+ NetworkingV1Api,
+)
+from kubernetes_asyncio.client.models.v1_secret import ( # type: ignore # noqa: E402
+ V1Secret,
+)
+from kubernetes_asyncio.client.rest import ApiException # type: ignore # noqa: E402
+
+TIMEOUT = 5
+API_KEY_SECRET_MAX_RETRIES = 5
+
+_logger = logging.getLogger(__name__)
+
+
+SOURCE_CODE_PVC_MOUNT_PATH = os.environ.get("WANDB_LAUNCH_CODE_PVC_MOUNT_PATH")
+SOURCE_CODE_PVC_NAME = os.environ.get("WANDB_LAUNCH_CODE_PVC_NAME")
+
+
+class KubernetesSubmittedRun(AbstractRun):
+ """Wrapper for a launched run on Kubernetes."""
+
+ def __init__(
+ self,
+ batch_api: "BatchV1Api",
+ core_api: "CoreV1Api",
+ apps_api: "AppsV1Api",
+ network_api: "NetworkingV1Api",
+ name: str,
+ namespace: Optional[str] = "default",
+ secret: Optional["V1Secret"] = None,
+ auxiliary_resource_label_key: Optional[str] = None,
+ ) -> None:
+ """Initialize a KubernetesSubmittedRun.
+
+ Other implementations of the AbstractRun interface poll on the run
+ when `get_status` is called, but KubernetesSubmittedRun uses
+ Kubernetes watch streams to update the run status. One thread handles
+ events from the job object and another thread handles events from the
+ rank 0 pod. These threads updated the `_status` attributed of the
+ KubernetesSubmittedRun object. When `get_status` is called, the
+ `_status` attribute is returned.
+
+ Arguments:
+ batch_api: Kubernetes BatchV1Api object.
+ core_api: Kubernetes CoreV1Api object.
+ network_api: Kubernetes NetworkV1Api object.
+ name: Name of the job.
+ namespace: Kubernetes namespace.
+ secret: Kubernetes secret.
+
+ Returns:
+ None.
+ """
+ self.batch_api = batch_api
+ self.core_api = core_api
+ self.apps_api = apps_api
+ self.network_api = network_api
+ self.name = name
+ self.namespace = namespace
+ self._fail_count = 0
+ self.secret = secret
+ self.auxiliary_resource_label_key = auxiliary_resource_label_key
+
+ @property
+ def id(self) -> str:
+ """Return the run id."""
+ return self.name
+
+ async def get_logs(self) -> Optional[str]:
+ try:
+ pods = await self.core_api.list_namespaced_pod(
+ label_selector=f"job-name={self.name}", namespace=self.namespace
+ )
+ pod_names = [pi.metadata.name for pi in pods.items]
+ if not pod_names:
+ wandb.termwarn(f"Found no pods for kubernetes job: {self.name}")
+ return None
+ logs = await self.core_api.read_namespaced_pod_log(
+ name=pod_names[0], namespace=self.namespace
+ )
+ if logs:
+ return str(logs)
+ else:
+ wandb.termwarn(f"No logs for kubernetes pod(s): {pod_names}")
+ return None
+ except Exception as e:
+ wandb.termerror(f"{LOG_PREFIX}Failed to get pod logs: {e}")
+ return None
+
+ async def wait(self) -> bool:
+ """Wait for the run to finish.
+
+ Returns:
+ True if the run finished successfully, False otherwise.
+ """
+ while True:
+ status = await self.get_status()
+ wandb.termlog(f"{LOG_PREFIX}Job {self.name} status: {status.state}")
+ if status.state in ["finished", "failed", "preempted"]:
+ break
+ await asyncio.sleep(5)
+
+ await self._delete_secret()
+ await self._delete_auxiliary_resources_by_label()
+ return (
+ status.state == "finished"
+ ) # todo: not sure if this (copied from aws runner) is the right approach? should we return false on failure
+
+ async def get_status(self) -> Status:
+ status = LaunchKubernetesMonitor.get_status(self.name)
+ if status in ["stopped", "failed", "finished", "preempted"]:
+ await self._delete_secret()
+ await self._delete_auxiliary_resources_by_label()
+ return status
+
+ async def cancel(self) -> None:
+ """Cancel the run."""
+ try:
+ await self.batch_api.delete_namespaced_job(
+ namespace=self.namespace,
+ name=self.name,
+ )
+ await self._delete_secret()
+ await self._delete_auxiliary_resources_by_label()
+ except ApiException as e:
+ raise LaunchError(
+ f"Failed to delete Kubernetes Job {self.name} in namespace {self.namespace}: {str(e)}"
+ ) from e
+
+ async def _delete_secret(self) -> None:
+ # Cleanup secret if not running in a helm-managed context
+ if not os.environ.get("WANDB_RELEASE_NAME") and self.secret:
+ await self.core_api.delete_namespaced_secret(
+ name=self.secret.metadata.name,
+ namespace=self.secret.metadata.namespace,
+ )
+ self.secret = None
+
+ async def _delete_auxiliary_resources_by_label(self) -> None:
+ if self.auxiliary_resource_label_key is None:
+ return
+
+ label_selector = (
+ f"{WANDB_K8S_LABEL_AUXILIARY_RESOURCE}={self.auxiliary_resource_label_key}"
+ )
+
+ try:
+ resource_cleanups = [
+ (self.core_api, "service"),
+ (self.batch_api, "job"),
+ (self.core_api, "pod"),
+ (self.core_api, "secret"),
+ (self.apps_api, "deployment"),
+ (self.network_api, "network_policy"),
+ ]
+
+ for api_client, resource_type in resource_cleanups:
+ try:
+ list_method = getattr(
+ api_client, f"list_namespaced_{resource_type}"
+ )
+ delete_method = getattr(
+ api_client, f"delete_namespaced_{resource_type}"
+ )
+
+ # List resources with our label
+ resources = await list_method(
+ namespace=self.namespace, label_selector=label_selector
+ )
+
+ # Delete each resource
+ for resource in resources.items:
+ await delete_method(
+ name=resource.metadata.name, namespace=self.namespace
+ )
+
+ except (AttributeError, ApiException) as e:
+ wandb.termwarn(f"Could not clean up {resource_type}: {e}")
+
+ except Exception as e:
+ wandb.termwarn(f"Failed to clean up some auxiliary resources: {e}")
+
+
+class CrdSubmittedRun(AbstractRun):
+ """Run submitted to a CRD backend, e.g. Volcano."""
+
+ def __init__(
+ self,
+ group: str,
+ version: str,
+ plural: str,
+ name: str,
+ namespace: str,
+ core_api: CoreV1Api,
+ custom_api: CustomObjectsApi,
+ ) -> None:
+ """Create a run object for tracking the progress of a CRD.
+
+ Arguments:
+ group: The API group of the CRD.
+ version: The API version of the CRD.
+ plural: The plural name of the CRD.
+ name: The name of the CRD instance.
+ namespace: The namespace of the CRD instance.
+ core_api: The Kubernetes core API client.
+ custom_api: The Kubernetes custom object API client.
+
+ Raises:
+ LaunchError: If the CRD instance does not exist.
+ """
+ self.group = group
+ self.version = version
+ self.plural = plural
+ self.name = name
+ self.namespace = namespace
+ self.core_api = core_api
+ self.custom_api = custom_api
+ self._fail_count = 0
+
+ @property
+ def id(self) -> str:
+ """Get the name of the custom object."""
+ return self.name
+
+ async def get_logs(self) -> Optional[str]:
+ """Get logs for custom object."""
+ # TODO: test more carefully once we release multi-node support
+ logs: Dict[str, Optional[str]] = {}
+ try:
+ pods = await self.core_api.list_namespaced_pod(
+ label_selector=f"wandb/run-id={self.name}", namespace=self.namespace
+ )
+ pod_names = [pi.metadata.name for pi in pods.items]
+ for pod_name in pod_names:
+ logs[pod_name] = await self.core_api.read_namespaced_pod_log(
+ name=pod_name, namespace=self.namespace
+ )
+ except ApiException as e:
+ wandb.termwarn(f"Failed to get logs for {self.name}: {str(e)}")
+ return None
+ if not logs:
+ return None
+ logs_as_array = [f"Pod {pod_name}:\n{log}" for pod_name, log in logs.items()]
+ return "\n".join(logs_as_array)
+
+ async def get_status(self) -> Status:
+ """Get status of custom object."""
+ return LaunchKubernetesMonitor.get_status(self.name)
+
+ async def cancel(self) -> None:
+ """Cancel the custom object."""
+ try:
+ await self.custom_api.delete_namespaced_custom_object(
+ group=self.group,
+ version=self.version,
+ namespace=self.namespace,
+ plural=self.plural,
+ name=self.name,
+ )
+ except ApiException as e:
+ raise LaunchError(
+ f"Failed to delete CRD {self.name} in namespace {self.namespace}: {str(e)}"
+ ) from e
+
+ async def wait(self) -> bool:
+ """Wait for this custom object to finish running."""
+ while True:
+ status = await self.get_status()
+ wandb.termlog(f"{LOG_PREFIX}Job {self.name} status: {status}")
+ if status.state in ["finished", "failed", "preempted"]:
+ return status.state == "finished"
+ await asyncio.sleep(5)
+
+
+class KubernetesRunner(AbstractRunner):
+ """Launches runs onto kubernetes."""
+
+ def __init__(
+ self,
+ api: Api,
+ backend_config: Dict[str, Any],
+ environment: AbstractEnvironment,
+ registry: AbstractRegistry,
+ ) -> None:
+ """Create a Kubernetes runner.
+
+ Arguments:
+ api: The API client object.
+ backend_config: The backend configuration.
+ environment: The environment to launch runs into.
+
+ Raises:
+ LaunchError: If the Kubernetes configuration is invalid.
+ """
+ super().__init__(api, backend_config)
+ self.environment = environment
+ self.registry = registry
+
+ def get_namespace(
+ self, resource_args: Dict[str, Any], context: Dict[str, Any]
+ ) -> str:
+ """Get the namespace to launch into.
+
+ Arguments:
+ resource_args: The resource args to launch.
+ context: The k8s config context.
+
+ Returns:
+ The namespace to launch into.
+ """
+ default_namespace = (
+ context["context"].get("namespace", "default") if context else "default"
+ )
+ return ( # type: ignore[no-any-return]
+ resource_args.get("metadata", {}).get("namespace")
+ or resource_args.get(
+ "namespace"
+ ) # continue support for malformed namespace
+ or self.backend_config.get("runner", {}).get("namespace")
+ or default_namespace
+ )
+
+ async def _inject_defaults(
+ self,
+ resource_args: Dict[str, Any],
+ launch_project: LaunchProject,
+ image_uri: str,
+ namespace: str,
+ core_api: "CoreV1Api",
+ ) -> Tuple[Dict[str, Any], Optional["V1Secret"]]:
+ """Apply our default values, return job dict and api key secret.
+
+ Arguments:
+ resource_args (Dict[str, Any]): The resource args to launch.
+ launch_project (LaunchProject): The launch project.
+ builder (Optional[AbstractBuilder]): The builder.
+ namespace (str): The namespace.
+ core_api (CoreV1Api): The core api.
+
+ Returns:
+ Tuple[Dict[str, Any], Optional["V1Secret"]]: The resource args and api key secret.
+ """
+ job: Dict[str, Any] = {
+ "apiVersion": "batch/v1",
+ "kind": "Job",
+ }
+ job.update(resource_args)
+
+ job_metadata: Dict[str, Any] = job.get("metadata", {})
+ job_spec: Dict[str, Any] = {"backoffLimit": 0, "ttlSecondsAfterFinished": 60}
+ job_spec.update(job.get("spec", {}))
+ pod_template: Dict[str, Any] = job_spec.get("template", {})
+ pod_spec: Dict[str, Any] = {"restartPolicy": "Never"}
+ pod_spec.update(pod_template.get("spec", {}))
+ containers: List[Dict[str, Any]] = pod_spec.get("containers", [{}])
+
+ # Add labels to job metadata
+ job_metadata.setdefault("labels", {})
+ job_metadata["labels"][WANDB_K8S_RUN_ID] = launch_project.run_id
+ job_metadata["labels"][WANDB_K8S_LABEL_MONITOR] = "true"
+ if LaunchAgent.initialized():
+ job_metadata["labels"][WANDB_K8S_LABEL_AGENT] = LaunchAgent.name()
+ # name precedence: name in spec > generated name
+ if not job_metadata.get("name"):
+ job_metadata["generateName"] = make_name_dns_safe(
+ f"launch-{launch_project.target_entity}-{launch_project.target_project}-"
+ )
+ job_metadata["namespace"] = namespace
+
+ for i, cont in enumerate(containers):
+ if "name" not in cont:
+ cont["name"] = cont.get("name", "launch" + str(i))
+ if "securityContext" not in cont:
+ cont["securityContext"] = {
+ "allowPrivilegeEscalation": False,
+ "capabilities": {"drop": ["ALL"]},
+ "seccompProfile": {"type": "RuntimeDefault"},
+ }
+
+ entry_point = (
+ launch_project.override_entrypoint or launch_project.get_job_entry_point()
+ )
+ if launch_project.docker_image:
+ # dont specify run id if user provided image, could have multiple runs
+ containers[0]["image"] = image_uri
+ # TODO: handle secret pulling image from registry
+ elif not any(["image" in cont for cont in containers]):
+ assert entry_point is not None
+ # in the non instance case we need to make an imagePullSecret
+ # so the new job can pull the image
+ containers[0]["image"] = image_uri
+ secret = await maybe_create_imagepull_secret(
+ core_api, self.registry, launch_project.run_id, namespace
+ )
+ if secret is not None:
+ pod_spec["imagePullSecrets"] = [
+ {"name": f"regcred-{launch_project.run_id}"}
+ ]
+
+ inject_entrypoint_and_args(
+ containers,
+ entry_point,
+ launch_project.override_args,
+ launch_project.override_entrypoint is not None,
+ )
+
+ env_vars = launch_project.get_env_vars_dict(
+ self._api, MAX_ENV_LENGTHS[self.__class__.__name__]
+ )
+ api_key_secret = None
+ for cont in containers:
+ # Add our env vars to user supplied env vars
+ env = cont.get("env") or []
+ for key, value in env_vars.items():
+ if (
+ key == "WANDB_API_KEY"
+ and value
+ and (
+ LaunchAgent.initialized()
+ or self.backend_config[PROJECT_SYNCHRONOUS]
+ )
+ ):
+ # Override API key with secret. TODO: Do the same for other runners
+ release_name = os.environ.get("WANDB_RELEASE_NAME")
+ secret_name = "wandb-api-key"
+ if release_name:
+ secret_name += f"-{release_name}"
+ else:
+ secret_name += f"-{launch_project.run_id}"
+
+ def handle_exception(e):
+ wandb.termwarn(
+ f"Exception when ensuring Kubernetes API key secret: {e}. Retrying..."
+ )
+
+ api_key_secret = await retry_async(
+ backoff=ExponentialBackoff(
+ initial_sleep=datetime.timedelta(seconds=1),
+ max_sleep=datetime.timedelta(minutes=1),
+ max_retries=API_KEY_SECRET_MAX_RETRIES,
+ ),
+ fn=ensure_api_key_secret,
+ on_exc=handle_exception,
+ core_api=core_api,
+ secret_name=secret_name,
+ namespace=namespace,
+ api_key=value,
+ )
+ env.append(
+ {
+ "name": key,
+ "valueFrom": {
+ "secretKeyRef": {
+ "name": secret_name,
+ "key": "password",
+ }
+ },
+ }
+ )
+ else:
+ env.append({"name": key, "value": value})
+ cont["env"] = env
+
+ pod_spec["containers"] = containers
+ pod_template["spec"] = pod_spec
+ job_spec["template"] = pod_template
+ job["spec"] = job_spec
+ job["metadata"] = job_metadata
+
+ add_label_to_pods(
+ job,
+ WANDB_K8S_LABEL_MONITOR,
+ "true",
+ )
+
+ if launch_project.job_base_image:
+ apply_code_mount_configuration(
+ job,
+ launch_project,
+ )
+
+ # Add wandb.ai/agent: current agent label on all pods
+ if LaunchAgent.initialized():
+ add_label_to_pods(
+ job,
+ WANDB_K8S_LABEL_AGENT,
+ LaunchAgent.name(),
+ )
+
+ return job, api_key_secret
+
+ async def _wait_for_resource_ready(
+ self,
+ api_client: kubernetes_asyncio.client.ApiClient,
+ config: Dict[str, Any],
+ namespace: str,
+ timeout_seconds: int = 300,
+ ) -> None:
+ """Wait for a Kubernetes resource to be ready.
+
+ Arguments:
+ api_client: The Kubernetes API client.
+ config: The resource configuration.
+ namespace: The namespace where the resource was created.
+ timeout_seconds: Maximum time to wait for readiness.
+ """
+ resource_kind = config.get("kind")
+ resource_name = config.get("metadata", {}).get("name")
+
+ if not resource_kind or not resource_name:
+ wandb.termerror(
+ f"{LOG_PREFIX}Cannot wait for resource without kind or name"
+ )
+ return
+
+ wandb.termlog(
+ f"{LOG_PREFIX}Waiting for {resource_kind} '{resource_name}' to be ready..."
+ )
+
+ start_time = time.time()
+
+ if resource_kind == "Deployment":
+ await self._wait_for_deployment_ready(
+ api_client, resource_name, namespace, timeout_seconds
+ )
+ elif resource_kind == "Service":
+ await self._wait_for_service_ready(
+ api_client, resource_name, namespace, timeout_seconds
+ )
+ elif resource_kind == "Pod":
+ await self._wait_for_pod_ready(
+ api_client, resource_name, namespace, timeout_seconds
+ )
+ else:
+ wandb.termlog(
+ f"{LOG_PREFIX}No specific readiness check for {resource_kind}, waiting 5 seconds..."
+ )
+ await asyncio.sleep(5)
+
+ elapsed = time.time() - start_time
+ wandb.termlog(
+ f"{LOG_PREFIX}{resource_kind} '{resource_name}' is ready after {elapsed:.1f}s"
+ )
+
+ async def _wait_for_deployment_ready(
+ self,
+ api_client: kubernetes_asyncio.client.ApiClient,
+ name: str,
+ namespace: str,
+ timeout_seconds: int,
+ ) -> None:
+ """Wait for a Deployment to be ready."""
+ apps_api = kubernetes_asyncio.client.AppsV1Api(api_client)
+
+ async def check_deployment_ready():
+ deployment = await apps_api.read_namespaced_deployment(
+ name=name, namespace=namespace
+ )
+ status = deployment.status
+
+ if status.ready_replicas and status.replicas:
+ return status.ready_replicas >= status.replicas
+
+ return False
+
+ await self._wait_with_timeout(check_deployment_ready, timeout_seconds, name)
+
+ async def _wait_for_service_ready(
+ self,
+ api_client: kubernetes_asyncio.client.ApiClient,
+ name: str,
+ namespace: str,
+ timeout_seconds: int,
+ ) -> None:
+ """Wait for a Service to have endpoints."""
+ core_api = kubernetes_asyncio.client.CoreV1Api(api_client)
+
+ async def check_service_ready():
+ endpoints = await core_api.read_namespaced_endpoints(
+ name=name, namespace=namespace
+ )
+ if endpoints.subsets:
+ for subset in endpoints.subsets:
+ if subset.addresses: # These are ready pod addresses
+ return True
+ return False
+
+ await self._wait_with_timeout(check_service_ready, timeout_seconds, name)
+
+ async def _wait_for_pod_ready(
+ self,
+ api_client: kubernetes_asyncio.client.ApiClient,
+ name: str,
+ namespace: str,
+ timeout_seconds: int,
+ ) -> None:
+ """Wait for a Pod to be ready."""
+ core_api = kubernetes_asyncio.client.CoreV1Api(api_client)
+
+ async def check_pod_ready():
+ pod = await core_api.read_namespaced_pod(name=name, namespace=namespace)
+ if pod.status.phase == "Running":
+ if pod.status.container_statuses:
+ return all(status.ready for status in pod.status.container_statuses)
+ return True
+ return False
+
+ await self._wait_with_timeout(check_pod_ready, timeout_seconds, name)
+
+ async def _wait_with_timeout(
+ self, check_func, timeout_seconds: int, name: str
+ ) -> None:
+ """Generic timeout wrapper for readiness checks."""
+ start_time = time.time()
+
+ while time.time() - start_time < timeout_seconds:
+ try:
+ if await check_func():
+ return
+ except kubernetes_asyncio.client.ApiException as e:
+ if e.status == 404:
+ pass
+ else:
+ wandb.termerror(
+ f"{LOG_PREFIX}Error waiting for resource '{name}': {e}"
+ )
+ raise
+ except Exception as e:
+ wandb.termerror(f"{LOG_PREFIX}Error waiting for resource '{name}': {e}")
+ raise
+ await asyncio.sleep(2)
+
+ raise LaunchError(
+ f"Resource '{name}' not ready within {timeout_seconds} seconds"
+ )
+
+ async def _prepare_resource(
+ self,
+ api_client: kubernetes_asyncio.client.ApiClient,
+ config: Dict[str, Any],
+ namespace: str,
+ run_id: str,
+ launch_project: LaunchProject,
+ api_key_secret: Optional["V1Secret"] = None,
+ wait_for_ready: bool = True,
+ wait_timeout: int = 300,
+ auxiliary_resource_label_value: Optional[str] = None,
+ ) -> None:
+ """Prepare a service for launch.
+
+ Arguments:
+ api_client: The Kubernetes API client.
+ config: The resource configuration to prepare.
+ namespace: The namespace to create the resource in.
+ run_id: The run ID to label the resource with.
+ launch_project: The launch project to get environment variables from.
+ api_key_secret: The API key secret to inject.
+ wait_for_ready: Whether to wait for the resource to be ready after creation.
+ wait_timeout: Maximum time in seconds to wait for resource readiness.
+ """
+ config.setdefault("metadata", {})
+ config["metadata"].setdefault("labels", {})
+ config["metadata"]["labels"][WANDB_K8S_RUN_ID] = run_id
+ config["metadata"]["labels"]["wandb.ai/created-by"] = "launch-agent"
+ if auxiliary_resource_label_value:
+ config["metadata"]["labels"][WANDB_K8S_LABEL_AUXILIARY_RESOURCE] = (
+ auxiliary_resource_label_value
+ )
+
+ env_vars = launch_project.get_env_vars_dict(
+ self._api, MAX_ENV_LENGTHS[self.__class__.__name__]
+ )
+ wandb_config_env = {
+ "WANDB_CONFIG": env_vars.get("WANDB_CONFIG", "{}"),
+ }
+ add_wandb_env(config, wandb_config_env)
+
+ if auxiliary_resource_label_value:
+ add_label_to_pods(
+ config,
+ WANDB_K8S_LABEL_AUXILIARY_RESOURCE,
+ auxiliary_resource_label_value,
+ )
+
+ if api_key_secret:
+ for cont in yield_containers(config):
+ env = cont.setdefault("env", [])
+ env.append(
+ {
+ "name": "WANDB_API_KEY",
+ "valueFrom": {
+ "secretKeyRef": {
+ "name": api_key_secret.metadata.name,
+ "key": "password",
+ }
+ },
+ }
+ )
+ cont["env"] = env
+
+ try:
+ sanitize_identifiers_for_k8s(config)
+
+ await kubernetes_asyncio.utils.create_from_dict(
+ api_client, config, namespace=namespace
+ )
+
+ if wait_for_ready:
+ await self._wait_for_resource_ready(
+ api_client, config, namespace, wait_timeout
+ )
+ except Exception as e:
+ wandb.termerror(f"{LOG_PREFIX}Failed to create Kubernetes resource: {e}")
+ raise LaunchError(f"Failed to create Kubernetes resource: {e}")
+
+ async def run(
+ self, launch_project: LaunchProject, image_uri: str
+ ) -> Optional[AbstractRun]:
+ """Execute a launch project on Kubernetes.
+
+ Arguments:
+ launch_project: The launch project to execute.
+ builder: The builder to use to build the image.
+
+ Returns:
+ The run object if the run was successful, otherwise None.
+ """
+ await LaunchKubernetesMonitor.ensure_initialized()
+ resource_args = launch_project.fill_macros(image_uri).get("kubernetes", {})
+ if not resource_args:
+ wandb.termlog(
+ f"{LOG_PREFIX}Note: no resource args specified. Add a "
+ "Kubernetes yaml spec or other options in a json file "
+ "with --resource-args ."
+ )
+ _logger.info(f"Running Kubernetes job with resource args: {resource_args}")
+
+ context, api_client = await get_kube_context_and_api_client(
+ kubernetes_asyncio, resource_args
+ )
+
+ # If using pvc for code mount, move code there.
+ if launch_project.job_base_image is not None:
+ if SOURCE_CODE_PVC_NAME is None or SOURCE_CODE_PVC_MOUNT_PATH is None:
+ raise LaunchError(
+ "WANDB_LAUNCH_SOURCE_CODE_PVC_ environment variables not set. "
+ "Unable to mount source code PVC into base image. "
+ "Use the `codeMountPvcName` variable in the agent helm chart "
+ "to enable base image jobs for this agent. See "
+ "https://github.com/wandb/helm-charts/tree/main/charts/launch-agent "
+ "for more information."
+ )
+ code_subdir = launch_project.get_image_source_string()
+ launch_project.change_project_dir(
+ os.path.join(SOURCE_CODE_PVC_MOUNT_PATH, code_subdir)
+ )
+
+ # If the user specified an alternate api, we need will execute this
+ # run by creating a custom object.
+ api_version = resource_args.get("apiVersion", "batch/v1")
+
+ if api_version not in ["batch/v1", "batch/v1beta1"]:
+ env_vars = launch_project.get_env_vars_dict(
+ self._api, MAX_ENV_LENGTHS[self.__class__.__name__]
+ )
+ # Crawl the resource args and add our env vars to the containers.
+ add_wandb_env(resource_args, env_vars)
+
+ # Add our labels to the resource args. This is necessary for the
+ # agent to find the custom object later on.
+ resource_args["metadata"] = resource_args.get("metadata", {})
+ resource_args["metadata"]["labels"] = resource_args["metadata"].get(
+ "labels", {}
+ )
+ resource_args["metadata"]["labels"][WANDB_K8S_LABEL_MONITOR] = "true"
+
+ # Crawl the resource arsg and add our labels to the pods. This is
+ # necessary for the agent to find the pods later on.
+ add_label_to_pods(
+ resource_args,
+ WANDB_K8S_LABEL_MONITOR,
+ "true",
+ )
+
+ # Add wandb.ai/agent: current agent label on all pods
+ if LaunchAgent.initialized():
+ add_label_to_pods(
+ resource_args,
+ WANDB_K8S_LABEL_AGENT,
+ LaunchAgent.name(),
+ )
+ resource_args["metadata"]["labels"][WANDB_K8S_LABEL_AGENT] = (
+ LaunchAgent.name()
+ )
+
+ if launch_project.job_base_image:
+ apply_code_mount_configuration(resource_args, launch_project)
+
+ overrides = {}
+ if launch_project.override_args:
+ overrides["args"] = launch_project.override_args
+ if launch_project.override_entrypoint:
+ overrides["command"] = launch_project.override_entrypoint.command
+ add_entrypoint_args_overrides(
+ resource_args,
+ overrides,
+ )
+ api = client.CustomObjectsApi(api_client)
+ # Infer the attributes of a custom object from the apiVersion and/or
+ # a kind: attribute in the resource args.
+ namespace = self.get_namespace(resource_args, context)
+ group, version, *_ = api_version.split("/")
+ group = resource_args.get("group", group)
+ version = resource_args.get("version", version)
+ kind = resource_args.get("kind", version)
+ plural = f"{kind.lower()}s"
+ custom_resource = CustomResource(
+ group=group,
+ version=version,
+ plural=plural,
+ )
+ LaunchKubernetesMonitor.monitor_namespace(
+ namespace, custom_resource=custom_resource
+ )
+
+ try:
+ response = await api.create_namespaced_custom_object(
+ group=group,
+ version=version,
+ namespace=namespace,
+ plural=plural,
+ body=resource_args,
+ )
+ except ApiException as e:
+ body = json.loads(e.body)
+ body_yaml = yaml.dump(body)
+ raise LaunchError(
+ f"Error creating CRD of kind {kind}: {e.status} {e.reason}\n{body_yaml}"
+ ) from e
+ name = response.get("metadata", {}).get("name")
+ _logger.info(f"Created {kind} {response['metadata']['name']}")
+ submitted_run = CrdSubmittedRun(
+ name=name,
+ group=group,
+ version=version,
+ namespace=namespace,
+ plural=plural,
+ core_api=client.CoreV1Api(api_client),
+ custom_api=api,
+ )
+ if self.backend_config[PROJECT_SYNCHRONOUS]:
+ await submitted_run.wait()
+ return submitted_run
+
+ batch_api = kubernetes_asyncio.client.BatchV1Api(api_client)
+ core_api = kubernetes_asyncio.client.CoreV1Api(api_client)
+ apps_api = kubernetes_asyncio.client.AppsV1Api(api_client)
+ network_api = kubernetes_asyncio.client.NetworkingV1Api(api_client)
+
+ namespace = self.get_namespace(resource_args, context)
+ job, secret = await self._inject_defaults(
+ resource_args, launch_project, image_uri, namespace, core_api
+ )
+
+ update_dict = {
+ "project_name": launch_project.target_project,
+ "entity_name": launch_project.target_entity,
+ "run_id": launch_project.run_id,
+ "run_name": launch_project.name,
+ "image_uri": image_uri,
+ "author": launch_project.author,
+ }
+ update_dict.update(os.environ)
+ additional_services: List[Dict[str, Any]] = recursive_macro_sub(
+ launch_project.launch_spec.get("additional_services", []), update_dict
+ )
+ auxiliary_resource_label_value = make_k8s_label_safe(
+ f"aux-{launch_project.target_entity}-{launch_project.target_project}-{launch_project.run_id}"
+ )
+ if additional_services:
+ wandb.termlog(
+ f"{LOG_PREFIX}Creating additional services: {additional_services}"
+ )
+
+ wait_for_ready = resource_args.get("wait_for_ready", True)
+ wait_timeout = resource_args.get("wait_timeout", 300)
+
+ await asyncio.gather(
+ *[
+ self._prepare_resource(
+ api_client,
+ resource.get("config", {}),
+ namespace,
+ launch_project.run_id,
+ launch_project,
+ secret,
+ wait_for_ready,
+ wait_timeout,
+ auxiliary_resource_label_value,
+ )
+ for resource in additional_services
+ if resource.get("config", {})
+ ]
+ )
+
+ msg = "Creating Kubernetes job"
+ if "name" in resource_args:
+ msg += f": {resource_args['name']}"
+ _logger.info(msg)
+ try:
+ response = await kubernetes_asyncio.utils.create_from_dict(
+ api_client, job, namespace=namespace
+ )
+ except kubernetes_asyncio.utils.FailToCreateError as e:
+ for exc in e.api_exceptions:
+ resp = json.loads(exc.body)
+ msg = resp.get("message")
+ code = resp.get("code")
+ raise LaunchError(
+ f"Failed to create Kubernetes job for run {launch_project.run_id} ({code} {exc.reason}): {msg}"
+ )
+ except Exception as e:
+ raise LaunchError(
+ f"Unexpected exception when creating Kubernetes job: {str(e)}\n"
+ )
+ job_response = response[0]
+ job_name = job_response.metadata.name
+ LaunchKubernetesMonitor.monitor_namespace(namespace)
+ submitted_job = KubernetesSubmittedRun(
+ batch_api,
+ core_api,
+ apps_api,
+ network_api,
+ job_name,
+ namespace,
+ secret,
+ auxiliary_resource_label_value,
+ )
+ if self.backend_config[PROJECT_SYNCHRONOUS]:
+ await submitted_job.wait()
+
+ return submitted_job
+
+
+def inject_entrypoint_and_args(
+ containers: List[dict],
+ entry_point: Optional[EntryPoint],
+ override_args: List[str],
+ should_override_entrypoint: bool,
+) -> None:
+ """Inject the entrypoint and args into the containers.
+
+ Arguments:
+ containers: The containers to inject the entrypoint and args into.
+ entry_point: The entrypoint to inject.
+ override_args: The args to inject.
+ should_override_entrypoint: Whether to override the entrypoint.
+
+ Returns:
+ None
+ """
+ for i in range(len(containers)):
+ if override_args:
+ containers[i]["args"] = override_args
+ if entry_point and (
+ not containers[i].get("command") or should_override_entrypoint
+ ):
+ containers[i]["command"] = entry_point.command
+
+
+async def ensure_api_key_secret(
+ core_api: "CoreV1Api",
+ secret_name: str,
+ namespace: str,
+ api_key: str,
+) -> "V1Secret":
+ """Create a secret containing a user's wandb API key.
+
+ Arguments:
+ core_api: The Kubernetes CoreV1Api object.
+ secret_name: The name to use for the secret.
+ namespace: The namespace to create the secret in.
+ api_key: The user's wandb API key
+
+ Returns:
+ The created secret
+ """
+ secret_data = {"password": base64.b64encode(api_key.encode()).decode()}
+ labels = {"wandb.ai/created-by": "launch-agent"}
+ secret = client.V1Secret(
+ data=secret_data,
+ metadata=client.V1ObjectMeta(
+ name=secret_name, namespace=namespace, labels=labels
+ ),
+ kind="Secret",
+ type="kubernetes.io/basic-auth",
+ )
+
+ try:
+ try:
+ return await core_api.create_namespaced_secret(namespace, secret)
+ except ApiException as e:
+ # 409 = conflict = secret already exists
+ if e.status == 409:
+ existing_secret = await core_api.read_namespaced_secret(
+ name=secret_name, namespace=namespace
+ )
+ if existing_secret.data != secret_data:
+ # If it's a previous secret made by launch agent, clean it up
+ if (
+ existing_secret.metadata.labels.get("wandb.ai/created-by")
+ == "launch-agent"
+ ):
+ await core_api.delete_namespaced_secret(
+ name=secret_name, namespace=namespace
+ )
+ return await core_api.create_namespaced_secret(
+ namespace, secret
+ )
+ else:
+ raise LaunchError(
+ f"Kubernetes secret already exists in namespace {namespace} with incorrect data: {secret_name}"
+ )
+ return existing_secret
+ raise
+ except Exception as e:
+ raise LaunchError(
+ f"Exception when ensuring Kubernetes API key secret: {str(e)}\n"
+ )
+
+
+async def maybe_create_imagepull_secret(
+ core_api: "CoreV1Api",
+ registry: AbstractRegistry,
+ run_id: str,
+ namespace: str,
+) -> Optional["V1Secret"]:
+ """Create a secret for pulling images from a private registry.
+
+ Arguments:
+ core_api: The Kubernetes CoreV1Api object.
+ registry: The registry to pull from.
+ run_id: The run id.
+ namespace: The namespace to create the secret in.
+
+ Returns:
+ A secret if one was created, otherwise None.
+ """
+ secret = None
+ if isinstance(registry, LocalRegistry) or isinstance(
+ registry, AzureContainerRegistry
+ ):
+ # Secret not required
+ return None
+ uname, token = await registry.get_username_password()
+ creds_info = {
+ "auths": {
+ registry.uri: {
+ "auth": base64.b64encode(f"{uname}:{token}".encode()).decode(),
+ # need an email but the use is deprecated
+ "email": "deprecated@wandblaunch.com",
+ }
+ }
+ }
+ secret_data = {
+ ".dockerconfigjson": base64.b64encode(json.dumps(creds_info).encode()).decode()
+ }
+ secret = client.V1Secret(
+ data=secret_data,
+ metadata=client.V1ObjectMeta(name=f"regcred-{run_id}", namespace=namespace),
+ kind="Secret",
+ type="kubernetes.io/dockerconfigjson",
+ )
+ try:
+ try:
+ return await core_api.create_namespaced_secret(namespace, secret)
+ except ApiException as e:
+ # 409 = conflict = secret already exists
+ if e.status == 409:
+ return await core_api.read_namespaced_secret(
+ name=f"regcred-{run_id}", namespace=namespace
+ )
+ raise
+ except Exception as e:
+ raise LaunchError(f"Exception when creating Kubernetes secret: {str(e)}\n")
+
+
+def add_wandb_env(root: Union[dict, list], env_vars: Dict[str, str]) -> None:
+ """Injects wandb environment variables into specs.
+
+ Recursively walks the spec and injects the environment variables into
+ every container spec. Containers are identified by the "containers" key.
+
+ This function treats the WANDB_RUN_ID and WANDB_GROUP_ID environment variables
+ specially. If they are present in the spec, they will be overwritten. If a setting
+ for WANDB_RUN_ID is provided in env_vars, then that environment variable will only be
+ set in the first container modified by this function.
+
+ Arguments:
+ root: The spec to modify.
+ env_vars: The environment variables to inject.
+
+ Returns: None.
+ """
+ for cont in yield_containers(root):
+ env = cont.setdefault("env", [])
+ env.extend([{"name": key, "value": value} for key, value in env_vars.items()])
+ cont["env"] = env
+ # After we have set WANDB_RUN_ID once, we don't want to set it again
+ if "WANDB_RUN_ID" in env_vars:
+ env_vars.pop("WANDB_RUN_ID")
+
+
+def yield_pods(manifest: Any) -> Iterator[dict]:
+ """Yield all pod specs in a manifest.
+
+ Recursively traverses the manifest and yields all pod specs. Pod specs are
+ identified by the presence of a "spec" key with a "containers" key in the
+ value.
+ """
+ if isinstance(manifest, list):
+ for item in manifest:
+ yield from yield_pods(item)
+ elif isinstance(manifest, dict):
+ if "spec" in manifest and "containers" in manifest["spec"]:
+ yield manifest
+ for value in manifest.values():
+ if isinstance(value, (dict, list)):
+ yield from yield_pods(value)
+
+
+def add_label_to_pods(
+ manifest: Union[dict, list], label_key: str, label_value: str
+) -> None:
+ """Add a label to all pod specs in a manifest.
+
+ Recursively traverses the manifest and adds the label to all pod specs.
+ Pod specs are identified by the presence of a "spec" key with a "containers"
+ key in the value.
+
+ Arguments:
+ manifest: The manifest to modify.
+ label_key: The label key to add.
+ label_value: The label value to add.
+
+ Returns: None.
+ """
+ for pod in yield_pods(manifest):
+ metadata = pod.setdefault("metadata", {})
+ labels = metadata.setdefault("labels", {})
+ labels[label_key] = label_value
+
+
+def add_entrypoint_args_overrides(manifest: Union[dict, list], overrides: dict) -> None:
+ """Add entrypoint and args overrides to all containers in a manifest.
+
+ Recursively traverses the manifest and adds the entrypoint and args overrides
+ to all containers. Containers are identified by the presence of a "spec" key
+ with a "containers" key in the value.
+
+ Arguments:
+ manifest: The manifest to modify.
+ overrides: Dictionary with args and entrypoint keys.
+
+ Returns: None.
+ """
+ if isinstance(manifest, list):
+ for item in manifest:
+ add_entrypoint_args_overrides(item, overrides)
+ elif isinstance(manifest, dict):
+ if "spec" in manifest and "containers" in manifest["spec"]:
+ containers = manifest["spec"]["containers"]
+ for container in containers:
+ if "command" in overrides:
+ container["command"] = overrides["command"]
+ if "args" in overrides:
+ container["args"] = overrides["args"]
+ for value in manifest.values():
+ add_entrypoint_args_overrides(value, overrides)
+
+
+def apply_code_mount_configuration(
+ manifest: Union[Dict, list], project: LaunchProject
+) -> None:
+ """Apply code mount configuration to all containers in a manifest.
+
+ Recursively traverses the manifest and adds the code mount configuration to
+ all containers. Containers are identified by the presence of a "spec" key
+ with a "containers" key in the value.
+
+ Arguments:
+ manifest: The manifest to modify.
+ project: The launch project.
+
+ Returns: None.
+ """
+ assert SOURCE_CODE_PVC_NAME is not None
+ source_dir = project.get_image_source_string()
+ for pod in yield_pods(manifest):
+ for container in yield_containers(pod):
+ if "volumeMounts" not in container:
+ container["volumeMounts"] = []
+ container["volumeMounts"].append(
+ {
+ "name": "wandb-source-code-volume",
+ "mountPath": CODE_MOUNT_DIR,
+ "subPath": source_dir,
+ }
+ )
+ container["workingDir"] = CODE_MOUNT_DIR
+ spec = pod["spec"]
+ if "volumes" not in spec:
+ spec["volumes"] = []
+ spec["volumes"].append(
+ {
+ "name": "wandb-source-code-volume",
+ "persistentVolumeClaim": {
+ "claimName": SOURCE_CODE_PVC_NAME,
+ },
+ }
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/local_container.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/local_container.py
new file mode 100644
index 0000000000000000000000000000000000000000..e831467a5c1967d0258231cfbe305d32936e29e5
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/local_container.py
@@ -0,0 +1,301 @@
+import asyncio
+import logging
+import os
+import shlex
+import subprocess
+import sys
+import threading
+from typing import TYPE_CHECKING, Any, Dict, List, Optional
+
+import wandb
+from wandb.sdk.launch.environment.abstract import AbstractEnvironment
+from wandb.sdk.launch.registry.abstract import AbstractRegistry
+
+from .._project_spec import LaunchProject
+from ..errors import LaunchError
+from ..utils import (
+ CODE_MOUNT_DIR,
+ LOG_PREFIX,
+ MAX_ENV_LENGTHS,
+ PROJECT_SYNCHRONOUS,
+ _is_wandb_dev_uri,
+ _is_wandb_local_uri,
+ docker_image_exists,
+ event_loop_thread_exec,
+ pull_docker_image,
+ sanitize_wandb_api_key,
+)
+from .abstract import AbstractRun, AbstractRunner, Status
+
+if TYPE_CHECKING:
+ from wandb.apis.internal import Api
+
+_logger = logging.getLogger(__name__)
+
+
+class LocalSubmittedRun(AbstractRun):
+ """Instance of ``AbstractRun`` corresponding to a subprocess launched to run an entry point command locally."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self._command_proc: Optional[subprocess.Popen] = None
+ self._stdout: Optional[str] = None
+ self._terminate_flag: bool = False
+ self._thread: Optional[threading.Thread] = None
+
+ def set_command_proc(self, command_proc: subprocess.Popen) -> None:
+ self._command_proc = command_proc
+
+ def set_thread(self, thread: threading.Thread) -> None:
+ self._thread = thread
+
+ @property
+ def id(self) -> Optional[str]:
+ if self._command_proc is None:
+ return None
+ return str(self._command_proc.pid)
+
+ async def wait(self) -> bool:
+ assert self._thread is not None
+ # if command proc is not set
+ # wait for thread to set it
+ if self._command_proc is None:
+ while self._thread.is_alive():
+ await asyncio.sleep(5)
+ # command proc can be updated by another thread
+ if self._command_proc is not None:
+ break # type: ignore # mypy thinks this is unreachable
+ else:
+ return False
+ wait = event_loop_thread_exec(self._command_proc.wait)
+ return int(await wait()) == 0
+
+ async def get_logs(self) -> Optional[str]:
+ return self._stdout
+
+ async def cancel(self) -> None:
+ # thread is set immediately after starting, should always exist
+ assert self._thread is not None
+
+ # cancel called before the thread subprocess has started
+ # indicates to thread to not start command proc if not already started
+ self._terminate_flag = True
+
+ async def get_status(self) -> Status:
+ assert self._thread is not None, "Failed to get status, self._thread = None"
+ if self._command_proc is None:
+ if self._thread.is_alive():
+ return Status("running")
+ return Status("stopped")
+ exit_code = self._command_proc.poll()
+ if exit_code is None:
+ return Status("running")
+ if exit_code == 0:
+ return Status("finished")
+ return Status("failed")
+
+
+class LocalContainerRunner(AbstractRunner):
+ """Runner class, uses a project to create a LocallySubmittedRun."""
+
+ def __init__(
+ self,
+ api: "Api",
+ backend_config: Dict[str, Any],
+ environment: AbstractEnvironment,
+ registry: AbstractRegistry,
+ ) -> None:
+ super().__init__(api, backend_config)
+ self.environment = environment
+ self.registry = registry
+
+ def _populate_docker_args(
+ self, launch_project: LaunchProject, image_uri: str
+ ) -> Dict[str, Any]:
+ docker_args: Dict[str, Any] = launch_project.fill_macros(image_uri).get(
+ "local-container", {}
+ )
+ if _is_wandb_local_uri(self._api.settings("base_url")):
+ if sys.platform == "win32":
+ docker_args["net"] = "host"
+ else:
+ docker_args["network"] = "host"
+ if sys.platform == "linux" or sys.platform == "linux2":
+ docker_args["add-host"] = "host.docker.internal:host-gateway"
+ base_image = launch_project.job_base_image
+ if base_image is not None:
+ # Mount code into the container and set the working directory.
+ if "volume" not in docker_args:
+ docker_args["volume"] = []
+ docker_args["volume"].append(
+ f"{launch_project.project_dir}:{CODE_MOUNT_DIR}"
+ )
+ docker_args["workdir"] = CODE_MOUNT_DIR
+ return docker_args
+
+ async def run(
+ self,
+ launch_project: LaunchProject,
+ image_uri: str,
+ ) -> Optional[AbstractRun]:
+ docker_args = self._populate_docker_args(launch_project, image_uri)
+ synchronous: bool = self.backend_config[PROJECT_SYNCHRONOUS]
+
+ env_vars = launch_project.get_env_vars_dict(
+ self._api, MAX_ENV_LENGTHS[self.__class__.__name__]
+ )
+
+ # When running against local port, need to swap to local docker host
+ if (
+ _is_wandb_local_uri(self._api.settings("base_url"))
+ and sys.platform == "darwin"
+ ):
+ _, _, port = self._api.settings("base_url").split(":")
+ env_vars["WANDB_BASE_URL"] = f"http://host.docker.internal:{port}"
+ elif _is_wandb_dev_uri(self._api.settings("base_url")):
+ env_vars["WANDB_BASE_URL"] = "http://host.docker.internal:9001"
+
+ if launch_project.docker_image or launch_project.job_base_image:
+ try:
+ pull_docker_image(image_uri)
+ except Exception as e:
+ wandb.termwarn(f"Error attempting to pull docker image {image_uri}")
+ if not docker_image_exists(image_uri):
+ raise LaunchError(
+ f"Failed to pull docker image {image_uri} with error: {e}"
+ )
+
+ entrypoint = launch_project.get_job_entry_point()
+ entry_cmd = None if entrypoint is None else entrypoint.command
+ command_str = " ".join(
+ get_docker_command(
+ image_uri,
+ env_vars,
+ docker_args=docker_args,
+ entry_cmd=entry_cmd,
+ additional_args=launch_project.override_args,
+ )
+ ).strip()
+ sanitized_cmd_str = sanitize_wandb_api_key(command_str)
+ _msg = f"{LOG_PREFIX}Launching run in docker with command: {sanitized_cmd_str}"
+ wandb.termlog(_msg)
+ run = _run_entry_point(command_str, launch_project.project_dir)
+ if synchronous:
+ await run.wait()
+ return run
+
+
+def _run_entry_point(command: str, work_dir: Optional[str]) -> AbstractRun:
+ """Run an entry point command in a subprocess.
+
+ Arguments:
+ command: Entry point command to run
+ work_dir: Working directory in which to run the command
+
+ Returns:
+ An instance of `LocalSubmittedRun`
+ """
+ if work_dir is None:
+ work_dir = os.getcwd()
+ env = os.environ.copy()
+ run = LocalSubmittedRun()
+ thread = threading.Thread(
+ target=_thread_process_runner,
+ args=(run, ["bash", "-c", command], work_dir, env),
+ )
+ run.set_thread(thread)
+ thread.start()
+ return run
+
+
+def _thread_process_runner(
+ run: LocalSubmittedRun, args: List[str], work_dir: str, env: Dict[str, str]
+) -> None:
+ # cancel was called before we started the subprocess
+ if run._terminate_flag:
+ return
+ # TODO: Make this async
+ process = subprocess.Popen(
+ args,
+ close_fds=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ universal_newlines=True,
+ bufsize=1,
+ cwd=work_dir,
+ env=env,
+ )
+ run.set_command_proc(process)
+ run._stdout = ""
+ while True:
+ # the agent thread could set the terminate flag
+ if run._terminate_flag:
+ process.terminate() # type: ignore
+ chunk = os.read(process.stdout.fileno(), 4096) # type: ignore
+ if not chunk:
+ break
+ index = chunk.find(b"\r")
+ decoded_chunk = None
+ while not decoded_chunk:
+ try:
+ decoded_chunk = chunk.decode()
+ except UnicodeDecodeError:
+ # Multi-byte character cut off, try to get the rest of it
+ chunk += os.read(process.stdout.fileno(), 1) # type: ignore
+ if index != -1:
+ run._stdout += decoded_chunk
+ print(chunk.decode(), end="")
+ else:
+ run._stdout += decoded_chunk + "\r"
+ print(chunk.decode(), end="\r")
+
+
+def get_docker_command(
+ image: str,
+ env_vars: Dict[str, str],
+ entry_cmd: Optional[List[str]] = None,
+ docker_args: Optional[Dict[str, Any]] = None,
+ additional_args: Optional[List[str]] = None,
+) -> List[str]:
+ """Construct the docker command using the image and docker args.
+
+ Arguments:
+ image: a Docker image to be run
+ env_vars: a dictionary of environment variables for the command
+ entry_cmd: the entry point command to run
+ docker_args: a dictionary of additional docker args for the command
+ """
+ docker_path = "docker"
+ cmd: List[Any] = [docker_path, "run", "--rm"]
+
+ # hacky handling of env vars, needs to be improved
+ for env_key, env_value in env_vars.items():
+ cmd += ["-e", f"{shlex.quote(env_key)}={shlex.quote(env_value)}"]
+
+ if docker_args:
+ for name, value in docker_args.items():
+ if len(name) == 1:
+ prefix = "-" + shlex.quote(name)
+ else:
+ prefix = "--" + shlex.quote(name)
+ if isinstance(value, list):
+ for v in value:
+ cmd += [prefix, shlex.quote(str(v))]
+ elif isinstance(value, bool) and value:
+ cmd += [prefix]
+ else:
+ cmd += [prefix, shlex.quote(str(value))]
+
+ if entry_cmd:
+ cmd += ["--entrypoint", entry_cmd[0]]
+ cmd += [shlex.quote(image)]
+ if entry_cmd and len(entry_cmd) > 1:
+ cmd += entry_cmd[1:]
+ if additional_args:
+ cmd += additional_args
+ return cmd
+
+
+def join(split_command: List[str]) -> str:
+ """Return a shell-escaped string from *split_command*."""
+ return " ".join(shlex.quote(arg) for arg in split_command)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/local_process.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/local_process.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b04361dc2501862f93eea3b8ef7c68807dcbf9f
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/local_process.py
@@ -0,0 +1,78 @@
+import logging
+import shlex
+from typing import Any, List, Optional
+
+import wandb
+
+from .._project_spec import LaunchProject
+from ..errors import LaunchError
+from ..utils import (
+ LOG_PREFIX,
+ MAX_ENV_LENGTHS,
+ PROJECT_SYNCHRONOUS,
+ sanitize_wandb_api_key,
+ validate_wandb_python_deps,
+)
+from .abstract import AbstractRun, AbstractRunner
+from .local_container import _run_entry_point
+
+_logger = logging.getLogger(__name__)
+
+
+class LocalProcessRunner(AbstractRunner):
+ """Runner class, uses a project to create a LocallySubmittedRun.
+
+ LocalProcessRunner is very similar to a LocalContainerRunner, except it does not
+ run the command inside a docker container. Instead, it runs the
+ command specified as a process directly on the bare metal machine.
+
+ """
+
+ async def run( # type: ignore
+ self,
+ launch_project: LaunchProject,
+ *args,
+ **kwargs,
+ ) -> Optional[AbstractRun]:
+ if args is not None:
+ _msg = f"{LOG_PREFIX}LocalProcessRunner.run received unused args {args}"
+ _logger.warning(_msg)
+ if kwargs is not None:
+ _msg = f"{LOG_PREFIX}LocalProcessRunner.run received unused kwargs {kwargs}"
+ _logger.warning(_msg)
+
+ synchronous: bool = self.backend_config[PROJECT_SYNCHRONOUS]
+ entry_point = (
+ launch_project.override_entrypoint or launch_project.get_job_entry_point()
+ )
+
+ cmd: List[Any] = []
+
+ if launch_project.project_dir is None:
+ raise LaunchError("Launch LocalProcessRunner received empty project dir")
+
+ if launch_project.job:
+ assert launch_project._job_artifact is not None
+ try:
+ validate_wandb_python_deps(
+ "requirements.frozen.txt",
+ launch_project.project_dir,
+ )
+ except Exception:
+ wandb.termwarn("Unable to validate python dependencies")
+ env_vars = launch_project.get_env_vars_dict(
+ self._api, MAX_ENV_LENGTHS[self.__class__.__name__]
+ )
+ for env_key, env_value in env_vars.items():
+ cmd += [f"{shlex.quote(env_key)}={shlex.quote(env_value)}"]
+ if entry_point is not None:
+ cmd += entry_point.command
+ cmd += launch_project.override_args
+
+ command_str = " ".join(cmd).strip()
+ _msg = f"{LOG_PREFIX}Launching run as a local-process with command {sanitize_wandb_api_key(command_str)}"
+ wandb.termlog(_msg)
+ run = _run_entry_point(command_str, launch_project.project_dir)
+ if synchronous:
+ await run.wait()
+ return run
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/sagemaker_runner.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/sagemaker_runner.py
new file mode 100644
index 0000000000000000000000000000000000000000..dfd5947e0d82846773410b2486e3ada46b333558
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/sagemaker_runner.py
@@ -0,0 +1,424 @@
+"""Implementation of the SageMakerRunner class."""
+
+import asyncio
+import logging
+from typing import Any, Dict, List, Optional, cast
+
+if False:
+ import boto3 # type: ignore
+
+import wandb
+from wandb.apis.internal import Api
+from wandb.sdk.launch.environment.aws_environment import AwsEnvironment
+from wandb.sdk.launch.errors import LaunchError
+
+from .._project_spec import EntryPoint, LaunchProject
+from ..registry.abstract import AbstractRegistry
+from ..utils import (
+ LOG_PREFIX,
+ MAX_ENV_LENGTHS,
+ PROJECT_SYNCHRONOUS,
+ event_loop_thread_exec,
+ to_camel_case,
+)
+from .abstract import AbstractRun, AbstractRunner, Status
+
+_logger = logging.getLogger(__name__)
+
+
+class SagemakerSubmittedRun(AbstractRun):
+ """Instance of ``AbstractRun`` corresponding to a subprocess launched to run an entry point command on aws sagemaker."""
+
+ def __init__(
+ self,
+ training_job_name: str,
+ client: "boto3.Client",
+ log_client: Optional["boto3.Client"] = None,
+ ) -> None:
+ super().__init__()
+ self.client = client
+ self.log_client = log_client
+ self.training_job_name = training_job_name
+ self._status = Status("running")
+
+ @property
+ def id(self) -> str:
+ return f"sagemaker-{self.training_job_name}"
+
+ async def get_logs(self) -> Optional[str]:
+ if self.log_client is None:
+ return None
+ try:
+ describe_log_streams = event_loop_thread_exec(
+ self.log_client.describe_log_streams
+ )
+ describe_res = await describe_log_streams(
+ logGroupName="/aws/sagemaker/TrainingJobs",
+ logStreamNamePrefix=self.training_job_name,
+ )
+ if len(describe_res["logStreams"]) == 0:
+ wandb.termwarn(
+ f"Failed to get logs for training job: {self.training_job_name}"
+ )
+ return None
+ log_name = describe_res["logStreams"][0]["logStreamName"]
+ get_log_events = event_loop_thread_exec(self.log_client.get_log_events)
+ res = await get_log_events(
+ logGroupName="/aws/sagemaker/TrainingJobs",
+ logStreamName=log_name,
+ )
+ assert "events" in res
+ return "\n".join(
+ [f"{event['timestamp']}:{event['message']}" for event in res["events"]]
+ )
+ except self.log_client.exceptions.ResourceNotFoundException:
+ wandb.termwarn(
+ f"Failed to get logs for training job: {self.training_job_name}"
+ )
+ return None
+ except Exception as e:
+ wandb.termwarn(
+ f"Failed to handle logs for training job: {self.training_job_name} with error {str(e)}"
+ )
+ return None
+
+ async def wait(self) -> bool:
+ while True:
+ status_state = (await self.get_status()).state
+ wandb.termlog(
+ f"{LOG_PREFIX}Training job {self.training_job_name} status: {status_state}"
+ )
+ if status_state in ["stopped", "failed", "finished"]:
+ break
+ await asyncio.sleep(5)
+ return status_state == "finished"
+
+ async def cancel(self) -> None:
+ # Interrupt child process if it hasn't already exited
+ status = await self.get_status()
+ if status.state == "running":
+ self.client.stop_training_job(TrainingJobName=self.training_job_name)
+ await self.wait()
+
+ async def get_status(self) -> Status:
+ describe_training_job = event_loop_thread_exec(
+ self.client.describe_training_job
+ )
+ job_status = (
+ await describe_training_job(TrainingJobName=self.training_job_name)
+ )["TrainingJobStatus"]
+ if job_status == "Completed" or job_status == "Stopped":
+ self._status = Status("finished")
+ elif job_status == "Failed":
+ self._status = Status("failed")
+ elif job_status == "Stopping":
+ self._status = Status("stopping")
+ elif job_status == "InProgress":
+ self._status = Status("running")
+ return self._status
+
+
+class SageMakerRunner(AbstractRunner):
+ """Runner class, uses a project to create a SagemakerSubmittedRun."""
+
+ def __init__(
+ self,
+ api: Api,
+ backend_config: Dict[str, Any],
+ environment: AwsEnvironment,
+ registry: AbstractRegistry,
+ ) -> None:
+ """Initialize the SagemakerRunner.
+
+ Arguments:
+ api (Api): The API instance.
+ backend_config (Dict[str, Any]): The backend configuration.
+ environment (AwsEnvironment): The AWS environment.
+
+ Raises:
+ LaunchError: If the runner cannot be initialized.
+ """
+ super().__init__(api, backend_config)
+ self.environment = environment
+ self.registry = registry
+
+ async def run(
+ self,
+ launch_project: LaunchProject,
+ image_uri: str,
+ ) -> Optional[AbstractRun]:
+ """Run a project on Amazon Sagemaker.
+
+ Arguments:
+ launch_project (LaunchProject): The project to run.
+
+ Returns:
+ Optional[AbstractRun]: The run instance.
+
+ Raises:
+ LaunchError: If the launch is unsuccessful.
+ """
+ _logger.info("using AWSSagemakerRunner")
+
+ given_sagemaker_args = launch_project.resource_args.get("sagemaker")
+ if given_sagemaker_args is None:
+ raise LaunchError(
+ "No sagemaker args specified. Specify sagemaker args in resource_args"
+ )
+
+ default_output_path = self.backend_config.get("runner", {}).get(
+ "s3_output_path"
+ )
+ if default_output_path is not None and not default_output_path.startswith(
+ "s3://"
+ ):
+ default_output_path = f"s3://{default_output_path}"
+
+ session = await self.environment.get_session()
+ client = await event_loop_thread_exec(session.client)("sts")
+ caller_id = client.get_caller_identity()
+ account_id = caller_id["Account"]
+ _logger.info(f"Using account ID {account_id}")
+ partition = await self.environment.get_partition()
+ role_arn = get_role_arn(
+ given_sagemaker_args, self.backend_config, account_id, partition
+ )
+
+ # Create a sagemaker client to launch the job.
+ sagemaker_client = session.client("sagemaker")
+ log_client = None
+ try:
+ log_client = session.client("logs")
+ except Exception as e:
+ wandb.termwarn(
+ f"Failed to connect to cloudwatch logs with error {str(e)}, logs will not be available"
+ )
+
+ # if the user provided the image they want to use, use that, but warn it won't have swappable artifacts
+ if (
+ given_sagemaker_args.get("AlgorithmSpecification", {}).get("TrainingImage")
+ is not None
+ ):
+ sagemaker_args = build_sagemaker_args(
+ launch_project,
+ self._api,
+ role_arn,
+ launch_project.override_entrypoint,
+ launch_project.override_args,
+ MAX_ENV_LENGTHS[self.__class__.__name__],
+ given_sagemaker_args.get("AlgorithmSpecification", {}).get(
+ "TrainingImage"
+ ),
+ default_output_path,
+ )
+ _logger.info(
+ f"Launching sagemaker job on user supplied image with args: {sagemaker_args}"
+ )
+ run = await launch_sagemaker_job(
+ launch_project, sagemaker_args, sagemaker_client, log_client
+ )
+ if self.backend_config[PROJECT_SYNCHRONOUS]:
+ await run.wait()
+ return run
+
+ _logger.info("Connecting to sagemaker client")
+ entry_point = (
+ launch_project.override_entrypoint or launch_project.get_job_entry_point()
+ )
+ command_args = []
+ if entry_point is not None:
+ command_args += entry_point.command
+ command_args += launch_project.override_args
+ if command_args:
+ command_str = " ".join(command_args)
+ wandb.termlog(
+ f"{LOG_PREFIX}Launching run on sagemaker with entrypoint: {command_str}"
+ )
+ else:
+ wandb.termlog(
+ f"{LOG_PREFIX}Launching run on sagemaker with user-provided entrypoint in image"
+ )
+ sagemaker_args = build_sagemaker_args(
+ launch_project,
+ self._api,
+ role_arn,
+ entry_point,
+ launch_project.override_args,
+ MAX_ENV_LENGTHS[self.__class__.__name__],
+ image_uri,
+ default_output_path,
+ )
+ _logger.info(f"Launching sagemaker job with args: {sagemaker_args}")
+ run = await launch_sagemaker_job(
+ launch_project, sagemaker_args, sagemaker_client, log_client
+ )
+ if self.backend_config[PROJECT_SYNCHRONOUS]:
+ await run.wait()
+ return run
+
+
+def merge_image_uri_with_algorithm_specification(
+ algorithm_specification: Optional[Dict[str, Any]],
+ image_uri: Optional[str],
+ entrypoint_command: List[str],
+ args: Optional[List[str]],
+) -> Dict[str, Any]:
+ """Create an AWS AlgorithmSpecification.
+
+ AWS Sagemaker algorithms require a training image and an input mode. If the user
+ does not specify the specification themselves, define the spec minimally using these
+ two fields. Otherwise, if they specify the AlgorithmSpecification set the training
+ image if it is not set.
+ """
+ if algorithm_specification is None:
+ algorithm_specification = {
+ "TrainingImage": image_uri,
+ "TrainingInputMode": "File",
+ }
+ else:
+ if image_uri:
+ algorithm_specification["TrainingImage"] = image_uri
+ if entrypoint_command:
+ algorithm_specification["ContainerEntrypoint"] = entrypoint_command
+ if args:
+ algorithm_specification["ContainerArguments"] = args
+
+ if algorithm_specification["TrainingImage"] is None:
+ raise LaunchError("Failed determine tag for training image")
+ return algorithm_specification
+
+
+def build_sagemaker_args(
+ launch_project: LaunchProject,
+ api: Api,
+ role_arn: str,
+ entry_point: Optional[EntryPoint],
+ args: Optional[List[str]],
+ max_env_length: int,
+ image_uri: str,
+ default_output_path: Optional[str] = None,
+) -> Dict[str, Any]:
+ sagemaker_args: Dict[str, Any] = {}
+ resource_args = launch_project.fill_macros(image_uri)
+ given_sagemaker_args: Optional[Dict[str, Any]] = resource_args.get("sagemaker")
+
+ if given_sagemaker_args is None:
+ raise LaunchError(
+ "No sagemaker args specified. Specify sagemaker args in resource_args"
+ )
+ if (
+ given_sagemaker_args.get("OutputDataConfig") is None
+ and default_output_path is not None
+ ):
+ sagemaker_args["OutputDataConfig"] = {"S3OutputPath": default_output_path}
+ else:
+ sagemaker_args["OutputDataConfig"] = given_sagemaker_args.get(
+ "OutputDataConfig"
+ )
+
+ if sagemaker_args.get("OutputDataConfig") is None:
+ raise LaunchError(
+ "Sagemaker launcher requires an OutputDataConfig Sagemaker resource argument"
+ )
+ training_job_name = cast(
+ str, (given_sagemaker_args.get("TrainingJobName") or launch_project.run_id)
+ )
+ sagemaker_args["TrainingJobName"] = training_job_name
+ entry_cmd = entry_point.command if entry_point else []
+
+ sagemaker_args["AlgorithmSpecification"] = (
+ merge_image_uri_with_algorithm_specification(
+ given_sagemaker_args.get(
+ "AlgorithmSpecification",
+ given_sagemaker_args.get("algorithm_specification"),
+ ),
+ image_uri,
+ entry_cmd,
+ args,
+ )
+ )
+
+ sagemaker_args["RoleArn"] = role_arn
+
+ camel_case_args = {
+ to_camel_case(key): item for key, item in given_sagemaker_args.items()
+ }
+ sagemaker_args = {
+ **camel_case_args,
+ **sagemaker_args,
+ }
+
+ if sagemaker_args.get("ResourceConfig") is None:
+ raise LaunchError(
+ "Sagemaker launcher requires a ResourceConfig resource argument"
+ )
+
+ if sagemaker_args.get("StoppingCondition") is None:
+ raise LaunchError(
+ "Sagemaker launcher requires a StoppingCondition resource argument"
+ )
+
+ given_env = given_sagemaker_args.get(
+ "Environment", sagemaker_args.get("environment", {})
+ )
+ calced_env = launch_project.get_env_vars_dict(api, max_env_length)
+ total_env = {**calced_env, **given_env}
+ sagemaker_args["Environment"] = total_env
+
+ # Add wandb tag
+ tags = sagemaker_args.get("Tags", [])
+ tags.append({"Key": "WandbRunId", "Value": launch_project.run_id})
+ sagemaker_args["Tags"] = tags
+
+ # remove args that were passed in for launch but not passed to sagemaker
+ sagemaker_args.pop("EcrRepoName", None)
+ sagemaker_args.pop("region", None)
+ sagemaker_args.pop("profile", None)
+
+ # clear the args that are None so they are not passed
+ filtered_args = {k: v for k, v in sagemaker_args.items() if v is not None}
+
+ return filtered_args
+
+
+async def launch_sagemaker_job(
+ launch_project: LaunchProject,
+ sagemaker_args: Dict[str, Any],
+ sagemaker_client: "boto3.Client",
+ log_client: Optional["boto3.Client"] = None,
+) -> SagemakerSubmittedRun:
+ training_job_name = sagemaker_args.get("TrainingJobName") or launch_project.run_id
+ create_training_job = event_loop_thread_exec(sagemaker_client.create_training_job)
+ resp = await create_training_job(**sagemaker_args)
+
+ if resp.get("TrainingJobArn") is None:
+ raise LaunchError("Failed to create training job when submitting to SageMaker")
+
+ run = SagemakerSubmittedRun(training_job_name, sagemaker_client, log_client)
+ wandb.termlog(
+ f"{LOG_PREFIX}Run job submitted with arn: {resp.get('TrainingJobArn')}"
+ )
+ url = f"https://{sagemaker_client.meta.region_name}.console.aws.amazon.com/sagemaker/home?region={sagemaker_client.meta.region_name}#/jobs/{training_job_name}"
+ wandb.termlog(f"{LOG_PREFIX}See training job status at: {url}")
+ return run
+
+
+def get_role_arn(
+ sagemaker_args: Dict[str, Any],
+ backend_config: Dict[str, Any],
+ account_id: str,
+ partition: str,
+) -> str:
+ """Get the role arn from the sagemaker args or the backend config."""
+ role_arn = sagemaker_args.get("RoleArn") or sagemaker_args.get("role_arn")
+ if role_arn is None:
+ role_arn = backend_config.get("runner", {}).get("role_arn")
+ if role_arn is None or not isinstance(role_arn, str):
+ raise LaunchError(
+ "AWS sagemaker require a string RoleArn set this by adding a `RoleArn` key to the sagemaker"
+ "field of resource_args"
+ )
+ if role_arn.startswith(f"arn:{partition}:iam::"):
+ return role_arn # type: ignore
+
+ return f"arn:{partition}:iam::{account_id}:role/{role_arn}"
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/vertex_runner.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/vertex_runner.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3254b92b0c9289329c3b0e64d380a1068d44aae
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/runner/vertex_runner.py
@@ -0,0 +1,225 @@
+import asyncio
+import logging
+from typing import Any, Dict, Optional
+
+if False:
+ from google.cloud import aiplatform # type: ignore # noqa: F401
+
+from wandb.apis.internal import Api
+from wandb.util import get_module
+
+from .._project_spec import LaunchProject
+from ..environment.gcp_environment import GcpEnvironment
+from ..errors import LaunchError
+from ..registry.abstract import AbstractRegistry
+from ..utils import MAX_ENV_LENGTHS, PROJECT_SYNCHRONOUS, event_loop_thread_exec
+from .abstract import AbstractRun, AbstractRunner, Status
+
+GCP_CONSOLE_URI = "https://console.cloud.google.com"
+
+_logger = logging.getLogger(__name__)
+
+
+WANDB_RUN_ID_KEY = "wandb-run-id"
+
+
+class VertexSubmittedRun(AbstractRun):
+ def __init__(self, job: Any) -> None:
+ self._job = job
+
+ @property
+ def id(self) -> str:
+ # numeric ID of the custom training job
+ return self._job.name # type: ignore
+
+ async def get_logs(self) -> Optional[str]:
+ # TODO: implement
+ return None
+
+ @property
+ def name(self) -> str:
+ return self._job.display_name # type: ignore
+
+ @property
+ def gcp_region(self) -> str:
+ return self._job.location # type: ignore
+
+ @property
+ def gcp_project(self) -> str:
+ return self._job.project # type: ignore
+
+ def get_page_link(self) -> str:
+ return f"{GCP_CONSOLE_URI}/vertex-ai/locations/{self.gcp_region}/training/{self.id}?project={self.gcp_project}"
+
+ async def wait(self) -> bool:
+ # TODO: run this in a separate thread.
+ await self._job.wait()
+ return (await self.get_status()).state == "finished"
+
+ async def get_status(self) -> Status:
+ job_state = str(self._job.state) # extract from type PipelineState
+ if job_state == "JobState.JOB_STATE_SUCCEEDED":
+ return Status("finished")
+ if job_state == "JobState.JOB_STATE_FAILED":
+ return Status("failed")
+ if job_state == "JobState.JOB_STATE_RUNNING":
+ return Status("running")
+ if job_state == "JobState.JOB_STATE_PENDING":
+ return Status("starting")
+ return Status("unknown")
+
+ async def cancel(self) -> None:
+ self._job.cancel()
+
+
+class VertexRunner(AbstractRunner):
+ """Runner class, uses a project to create a VertexSubmittedRun."""
+
+ def __init__(
+ self,
+ api: Api,
+ backend_config: Dict[str, Any],
+ environment: GcpEnvironment,
+ registry: AbstractRegistry,
+ ) -> None:
+ """Initialize a VertexRunner instance."""
+ super().__init__(api, backend_config)
+ self.environment = environment
+ self.registry = registry
+
+ async def run(
+ self, launch_project: LaunchProject, image_uri: str
+ ) -> Optional[AbstractRun]:
+ """Run a Vertex job."""
+ full_resource_args = launch_project.fill_macros(image_uri)
+ resource_args = full_resource_args.get("vertex")
+ # We support setting under gcp-vertex for historical reasons.
+ if not resource_args:
+ resource_args = full_resource_args.get("gcp-vertex")
+ if not resource_args:
+ raise LaunchError(
+ "No Vertex resource args specified. Specify args via --resource-args with a JSON file or string under top-level key gcp_vertex"
+ )
+
+ spec_args = resource_args.get("spec", {})
+ run_args = resource_args.get("run", {})
+
+ synchronous: bool = self.backend_config[PROJECT_SYNCHRONOUS]
+
+ entry_point = (
+ launch_project.override_entrypoint or launch_project.get_job_entry_point()
+ )
+
+ # TODO: Set entrypoint in each container
+ entry_cmd = []
+ if entry_point is not None:
+ entry_cmd += entry_point.command
+ entry_cmd += launch_project.override_args
+
+ env_vars = launch_project.get_env_vars_dict(
+ api=self._api,
+ max_env_length=MAX_ENV_LENGTHS[self.__class__.__name__],
+ )
+
+ worker_specs = spec_args.get("worker_pool_specs", [])
+ if not worker_specs:
+ raise LaunchError(
+ "Vertex requires at least one worker pool spec. Please specify "
+ "a worker pool spec in resource arguments under the key "
+ "`vertex.spec.worker_pool_specs`."
+ )
+
+ # TODO: Add entrypoint + args to each worker pool spec
+ for spec in worker_specs:
+ if not spec.get("container_spec"):
+ raise LaunchError(
+ "Vertex requires a container spec for each worker pool spec. "
+ "Please specify a container spec in resource arguments under "
+ "the key `vertex.spec.worker_pool_specs[].container_spec`."
+ )
+ spec["container_spec"]["command"] = entry_cmd
+
+ # Add our env vars to user supplied env vars
+ env = spec["container_spec"].get("env", [])
+ env.extend(
+ [{"name": key, "value": value} for key, value in env_vars.items()]
+ )
+ spec["container_spec"]["env"] = env
+
+ if not spec_args.get("staging_bucket"):
+ raise LaunchError(
+ "Vertex requires a staging bucket. Please specify a staging bucket "
+ "in resource arguments under the key `vertex.spec.staging_bucket`."
+ )
+
+ _logger.info("Launching Vertex job...")
+ submitted_run = await launch_vertex_job(
+ launch_project,
+ spec_args,
+ run_args,
+ self.environment,
+ synchronous,
+ )
+ return submitted_run
+
+
+async def launch_vertex_job(
+ launch_project: LaunchProject,
+ spec_args: Dict[str, Any],
+ run_args: Dict[str, Any],
+ environment: GcpEnvironment,
+ synchronous: bool = False,
+) -> VertexSubmittedRun:
+ try:
+ await environment.verify()
+ aiplatform = get_module(
+ "google.cloud.aiplatform",
+ "VertexRunner requires google.cloud.aiplatform to be installed",
+ )
+ init = event_loop_thread_exec(aiplatform.init)
+ await init(
+ project=environment.project,
+ location=environment.region,
+ staging_bucket=spec_args.get("staging_bucket"),
+ credentials=await environment.get_credentials(),
+ )
+ labels = spec_args.get("labels", {})
+ labels[WANDB_RUN_ID_KEY] = launch_project.run_id
+ job = aiplatform.CustomJob(
+ display_name=launch_project.name,
+ worker_pool_specs=spec_args.get("worker_pool_specs"),
+ base_output_dir=spec_args.get("base_output_dir"),
+ encryption_spec_key_name=spec_args.get("encryption_spec_key_name"),
+ labels=labels,
+ )
+ execution_kwargs = dict(
+ timeout=run_args.get("timeout"),
+ service_account=run_args.get("service_account"),
+ network=run_args.get("network"),
+ enable_web_access=run_args.get("enable_web_access", False),
+ experiment=run_args.get("experiment"),
+ experiment_run=run_args.get("experiment_run"),
+ tensorboard=run_args.get("tensorboard"),
+ restart_job_on_worker_restart=run_args.get(
+ "restart_job_on_worker_restart", False
+ ),
+ )
+ # Unclear if there are exceptions that can be thrown where we should
+ # retry instead of erroring. For now, just catch all exceptions and they
+ # go to the UI for the user to interpret.
+ except Exception as e:
+ raise LaunchError(f"Failed to create Vertex job: {e}")
+
+ if synchronous:
+ run = event_loop_thread_exec(job.run)
+ await run(**execution_kwargs, sync=True)
+ else:
+ submit = event_loop_thread_exec(job.submit)
+ await submit(**execution_kwargs)
+ submitted_run = VertexSubmittedRun(job)
+ interval = 1
+ while not getattr(job._gca_resource, "name", None):
+ # give time for the gcp job object to be created and named, this should only loop a couple times max
+ await asyncio.sleep(interval)
+ interval = min(30, interval * 2)
+ return submitted_run
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/sweeps/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/sweeps/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..98be169a096015729752916d4ac6763cf7a65024
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/sweeps/__init__.py
@@ -0,0 +1,37 @@
+import logging
+from typing import Any, Callable, Dict
+
+log = logging.getLogger(__name__)
+
+
+class SchedulerError(Exception):
+ """Raised when a known error occurs with wandb sweep scheduler."""
+
+
+def _import_sweep_scheduler() -> Any:
+ from .scheduler_sweep import SweepScheduler
+
+ return SweepScheduler
+
+
+_WANDB_SCHEDULERS: Dict[str, Callable] = {
+ "wandb": _import_sweep_scheduler,
+}
+
+
+def load_scheduler(scheduler_type: str) -> Any:
+ scheduler_type = scheduler_type.lower()
+ if scheduler_type not in _WANDB_SCHEDULERS:
+ raise SchedulerError(
+ f"The `scheduler_name` argument must be one of "
+ f"{list(_WANDB_SCHEDULERS.keys())}, got: {scheduler_type}"
+ )
+
+ log.warning(f"Loading dependencies for Scheduler of type: {scheduler_type}")
+ import_func = _WANDB_SCHEDULERS[scheduler_type]
+ return import_func()
+
+
+__all__ = [
+ "load_scheduler",
+]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/sweeps/scheduler.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/sweeps/scheduler.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd3f8e2c64ec6cf725427c9be3c6041faaa6afd2
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/sweeps/scheduler.py
@@ -0,0 +1,739 @@
+"""Abstract Scheduler class."""
+
+import asyncio
+import base64
+import copy
+import logging
+import os
+import socket
+import threading
+import time
+import traceback
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+from enum import Enum
+from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Tuple, Union
+
+import click
+import yaml
+
+import wandb
+from wandb.errors import CommError
+from wandb.sdk.launch._launch_add import launch_add
+from wandb.sdk.launch.errors import LaunchError
+from wandb.sdk.launch.sweeps import SchedulerError
+from wandb.sdk.launch.sweeps.utils import (
+ create_sweep_command_args,
+ make_launch_sweep_entrypoint,
+)
+from wandb.sdk.launch.utils import (
+ event_loop_thread_exec,
+ strip_resource_args_and_template_vars,
+)
+from wandb.sdk.lib.runid import generate_id
+
+if TYPE_CHECKING:
+ import wandb.apis.public as public
+ from wandb.apis.internal import Api
+ from wandb.apis.public import QueuedRun, Run
+
+
+_logger = logging.getLogger(__name__)
+LOG_PREFIX = f"{click.style('sched:', fg='cyan')} "
+
+DEFAULT_POLLING_SLEEP = 5.0
+
+
+class SchedulerState(Enum):
+ PENDING = 0
+ STARTING = 1
+ RUNNING = 2
+ FLUSH_RUNS = 3
+ COMPLETED = 4
+ FAILED = 5
+ STOPPED = 6
+ CANCELLED = 7
+
+
+class RunState(Enum):
+ RUNNING = "running", "alive"
+ PENDING = "pending", "alive"
+ PREEMPTING = "preempting", "alive"
+ CRASHED = "crashed", "dead"
+ FAILED = "failed", "dead"
+ KILLED = "killed", "dead"
+ FINISHED = "finished", "dead"
+ PREEMPTED = "preempted", "dead"
+ # unknown when api.get_run_state fails or returns unexpected state
+ # assumed alive, unless we get unknown 2x then move to failed (dead)
+ UNKNOWN = "unknown", "alive"
+
+ def __new__(cls: Any, *args: List, **kwds: Any) -> "RunState":
+ obj: RunState = object.__new__(cls)
+ obj._value_ = args[0]
+ return obj
+
+ def __init__(self, _: str, life: str = "unknown") -> None:
+ self._life = life
+
+ @property
+ def is_alive(self) -> bool:
+ return self._life == "alive"
+
+
+@dataclass
+class _Worker:
+ agent_config: Dict[str, Any]
+ agent_id: str
+
+
+@dataclass
+class SweepRun:
+ id: str
+ worker_id: int
+ state: RunState = RunState.RUNNING
+ queued_run: Optional["public.QueuedRun"] = None
+ args: Optional[Dict[str, Any]] = None
+ logs: Optional[List[str]] = None
+
+
+class Scheduler(ABC):
+ """A controller/agent that populates a Launch RunQueue from a hyperparameter sweep."""
+
+ PLACEHOLDER_URI = "placeholder-uri-scheduler"
+ SWEEP_JOB_TYPE = "sweep-controller"
+ ENTRYPOINT = ["wandb", "scheduler", "WANDB_SWEEP_ID"]
+
+ def __init__(
+ self,
+ api: "Api",
+ *args: Optional[Any],
+ polling_sleep: Optional[float] = None,
+ sweep_id: Optional[str] = None,
+ entity: Optional[str] = None,
+ project: Optional[str] = None,
+ project_queue: Optional[str] = None,
+ num_workers: Optional[Union[int, str]] = None,
+ **kwargs: Optional[Any],
+ ):
+ from wandb.apis.public import Api as PublicApi
+
+ self._api = api
+ self._public_api = PublicApi()
+ self._entity = (
+ entity
+ or os.environ.get("WANDB_ENTITY")
+ or api.settings("entity")
+ or api.default_entity
+ )
+ self._project = (
+ project or os.environ.get("WANDB_PROJECT") or api.settings("project")
+ )
+ self._sweep_id: str = sweep_id or "empty-sweep-id"
+ self._state: SchedulerState = SchedulerState.PENDING
+
+ # Make sure the provided sweep_id corresponds to a valid sweep
+ try:
+ resp = self._api.sweep(
+ sweep_id, "{}", entity=self._entity, project=self._project
+ )
+ if resp.get("state") == SchedulerState.CANCELLED.name:
+ self._state = SchedulerState.CANCELLED
+ self._sweep_config = yaml.safe_load(resp["config"])
+ self._num_runs_launched: int = self._get_num_runs_launched(resp["runs"])
+ if self._num_runs_launched > 0:
+ wandb.termlog(
+ f"{LOG_PREFIX}Found {self._num_runs_launched} previous valid runs for sweep {self._sweep_id}"
+ )
+ except Exception as e:
+ raise SchedulerError(
+ f"{LOG_PREFIX}Exception when finding sweep ({sweep_id}) {e}"
+ )
+
+ # Scheduler may receive additional kwargs which will be piped into the launch command
+ self._kwargs: Dict[str, Any] = kwargs
+
+ # Dictionary of the runs being managed by the scheduler
+ self._runs: Dict[str, SweepRun] = {}
+ # Threading lock to ensure thread-safe access to the runs dictionary
+ self._threading_lock: threading.Lock = threading.Lock()
+ self._polling_sleep = (
+ polling_sleep if polling_sleep is not None else DEFAULT_POLLING_SLEEP
+ )
+ self._project_queue = project_queue
+ # Optionally run multiple workers in (pseudo-)parallel. Workers do not
+ # actually run training workloads, they simply send heartbeat messages
+ # (emulating a real agent) and add new runs to the launch queue. The
+ # launch agent is the one that actually runs the training workloads.
+ self._workers: Dict[int, _Worker] = {}
+
+ # Init wandb scheduler run
+ self._wandb_run = self._init_wandb_run()
+
+ # Grab params from scheduler wandb run config
+ num_workers = num_workers or self._wandb_run.config.get("scheduler", {}).get(
+ "num_workers"
+ )
+ self._num_workers = int(num_workers) if str(num_workers).isdigit() else 8
+ self._settings_config: Dict[str, Any] = self._wandb_run.config.get(
+ "settings", {}
+ )
+
+ @abstractmethod
+ def _get_next_sweep_run(self, worker_id: int) -> Optional[SweepRun]:
+ """Called when worker available."""
+
+ @abstractmethod
+ def _poll(self) -> None:
+ """Called every polling loop."""
+
+ @abstractmethod
+ def _exit(self) -> None:
+ pass
+
+ @abstractmethod
+ def _load_state(self) -> None:
+ pass
+
+ @abstractmethod
+ def _save_state(self) -> None:
+ pass
+
+ @property
+ def state(self) -> SchedulerState:
+ _logger.debug(f"{LOG_PREFIX}Scheduler state is {self._state.name}")
+ return self._state
+
+ @state.setter
+ def state(self, value: SchedulerState) -> None:
+ _logger.debug(f"{LOG_PREFIX}Scheduler was {self.state.name} is {value.name}")
+ self._state = value
+
+ @property
+ def is_alive(self) -> bool:
+ if self.state in [
+ SchedulerState.COMPLETED,
+ SchedulerState.FAILED,
+ SchedulerState.STOPPED,
+ SchedulerState.CANCELLED,
+ ]:
+ return False
+ return True
+
+ @property
+ def at_runcap(self) -> bool:
+ """False if under user-specified cap on # of runs."""
+ run_cap = self._sweep_config.get("run_cap")
+ if not run_cap:
+ return False
+ at_runcap: bool = self._num_runs_launched >= run_cap
+ return at_runcap
+
+ @property
+ def num_active_runs(self) -> int:
+ return len(self._runs)
+
+ @property
+ def busy_workers(self) -> Dict[int, _Worker]:
+ """Returns dict of id:worker already assigned to a launch run.
+
+ runs should always have a worker_id, but are created before
+ workers are assigned to the run
+ """
+ busy_workers = {}
+ for _, r in self._yield_runs():
+ busy_workers[r.worker_id] = self._workers[r.worker_id]
+ return busy_workers
+
+ @property
+ def available_workers(self) -> Dict[int, _Worker]:
+ """Returns dict of id:worker ready to launch another run."""
+ if len(self._workers) == 0:
+ return {}
+ return {
+ _id: w for _id, w in self._workers.items() if _id not in self.busy_workers
+ }
+
+ def _init_wandb_run(self) -> "wandb.Run":
+ """Controls resume or init logic for a scheduler wandb run."""
+ settings = wandb.Settings(disable_job_creation=True)
+ run: wandb.Run = wandb.init( # type: ignore
+ name=f"Scheduler.{self._sweep_id}",
+ resume="allow",
+ config=self._kwargs, # when run as a job, this sets config
+ settings=settings,
+ )
+ return run
+
+ def stop_sweep(self) -> None:
+ """Stop the sweep."""
+ self._state = SchedulerState.STOPPED
+
+ def fail_sweep(self, err: Optional[str]) -> None:
+ """Fail the sweep w/ optional exception."""
+ self._state = SchedulerState.FAILED
+ if err:
+ raise SchedulerError(err)
+
+ def start(self) -> None:
+ """Start a scheduler, confirms prerequisites, begins execution loop."""
+ wandb.termlog(f"{LOG_PREFIX}Scheduler starting.")
+ if not self.is_alive:
+ wandb.termerror(
+ f"{LOG_PREFIX}Sweep already in end state ({self.state.name.lower()}). Exiting..."
+ )
+ self.exit()
+ return
+
+ self._state = SchedulerState.STARTING
+ if not self._try_load_executable():
+ wandb.termerror(
+ f"{LOG_PREFIX}No 'job' or 'image_uri' loaded from sweep config."
+ )
+ self.exit()
+ return
+
+ # For resuming sweeps
+ self._load_state()
+ asyncio.run(self._register_agents())
+ self.run()
+
+ def run(self) -> None:
+ """Main run function."""
+ wandb.termlog(f"{LOG_PREFIX}Scheduler running")
+ self.state = SchedulerState.RUNNING
+ try:
+ while True:
+ self._update_scheduler_run_state()
+ if not self.is_alive:
+ break
+
+ wandb.termlog(f"{LOG_PREFIX}Polling for new runs to launch")
+
+ self._update_run_states()
+ self._poll()
+ if self.state == SchedulerState.FLUSH_RUNS:
+ if self.num_active_runs == 0:
+ wandb.termlog(f"{LOG_PREFIX}Done polling on runs, exiting")
+ break
+ time.sleep(self._polling_sleep)
+ continue
+
+ for worker_id in self.available_workers:
+ if self.at_runcap:
+ wandb.termlog(
+ f"{LOG_PREFIX}Sweep at run_cap ({self._num_runs_launched})"
+ )
+ self.state = SchedulerState.FLUSH_RUNS
+ break
+
+ try:
+ run: Optional[SweepRun] = self._get_next_sweep_run(worker_id)
+ if not run:
+ break
+ except SchedulerError as e:
+ raise SchedulerError(e)
+ except Exception as e:
+ wandb.termerror(
+ f"{LOG_PREFIX}Failed to get next sweep run: {e}"
+ )
+ self.state = SchedulerState.FAILED
+ break
+
+ if self._add_to_launch_queue(run):
+ self._num_runs_launched += 1
+
+ time.sleep(self._polling_sleep)
+ except KeyboardInterrupt:
+ wandb.termwarn(f"{LOG_PREFIX}Scheduler received KeyboardInterrupt. Exiting")
+ self.state = SchedulerState.STOPPED
+ self.exit()
+ return
+ except Exception as e:
+ wandb.termlog(f"{LOG_PREFIX}Scheduler failed with exception {e}")
+ self.state = SchedulerState.FAILED
+ self.exit()
+ raise
+ else:
+ # scheduler succeeds if at runcap
+ if self.state == SchedulerState.FLUSH_RUNS and self.at_runcap:
+ self.state = SchedulerState.COMPLETED
+ self.exit()
+
+ def exit(self) -> None:
+ self._exit()
+ # _save_state isn't controlled, possibly fails
+ try:
+ self._save_state()
+ except Exception:
+ wandb.termerror(
+ f"{LOG_PREFIX}Failed to save state: {traceback.format_exc()}"
+ )
+
+ status = ""
+ if self.state == SchedulerState.FLUSH_RUNS:
+ self._set_sweep_state("PAUSED")
+ status = "paused"
+ elif self.state == SchedulerState.COMPLETED:
+ self._set_sweep_state("FINISHED")
+ status = "completed"
+ elif self.state in [SchedulerState.CANCELLED, SchedulerState.STOPPED]:
+ self._set_sweep_state("CANCELED") # one L
+ status = "cancelled"
+ self._stop_runs()
+ else:
+ self.state = SchedulerState.FAILED
+ self._set_sweep_state("CRASHED")
+ status = "crashed"
+ self._stop_runs()
+
+ wandb.termlog(f"{LOG_PREFIX}Scheduler {status}")
+ self._wandb_run.finish()
+
+ def _get_num_runs_launched(self, runs: List[Dict[str, Any]]) -> int:
+ """Returns the number of valid runs in the sweep."""
+ count = 0
+ for run in runs:
+ # if bad run, shouldn't be counted against run cap
+ if run.get("state", "") in ["killed", "crashed"] and not run.get(
+ "summaryMetrics"
+ ):
+ _logger.debug(
+ f"excluding run: {run['name']} with state: {run['state']} from run cap \n{run}"
+ )
+ continue
+ count += 1
+
+ return count
+
+ def _try_load_executable(self) -> bool:
+ """Check existence of valid executable for a run.
+
+ logs and returns False when job is unreachable
+ """
+ if self._kwargs.get("job"):
+ try:
+ _job_artifact = self._public_api.job(self._kwargs["job"])
+ wandb.termlog(
+ f"{LOG_PREFIX}Successfully loaded job ({_job_artifact.name}) in scheduler"
+ )
+ except Exception:
+ wandb.termerror(f"{LOG_PREFIX}{traceback.format_exc()}")
+ return False
+ return True
+ elif self._kwargs.get("image_uri"):
+ # TODO(gst): check docker existence? Use registry in launch config?
+ return True
+ else:
+ return False
+
+ async def _register_agents(self) -> None:
+ tasks = []
+ register_agent = event_loop_thread_exec(self._api.register_agent)
+ for worker_id in range(self._num_workers):
+ _logger.debug(f"{LOG_PREFIX}Starting AgentHeartbeat worker ({worker_id})")
+ try:
+ worker = register_agent(
+ f"{socket.gethostname()}-{worker_id}", # host
+ sweep_id=self._sweep_id,
+ project_name=self._project,
+ entity=self._entity,
+ )
+ tasks.append(worker)
+ except Exception as e:
+ _logger.debug(f"failed to register agent: {e}")
+ self.fail_sweep(f"failed to register agent: {e}")
+
+ finished_tasks = await asyncio.gather(*tasks)
+ for idx, agent_config in enumerate(finished_tasks):
+ self._workers[idx] = _Worker(
+ agent_config=agent_config,
+ agent_id=agent_config["id"],
+ )
+
+ def _yield_runs(self) -> Iterator[Tuple[str, SweepRun]]:
+ """Thread-safe way to iterate over the runs."""
+ with self._threading_lock:
+ yield from self._runs.items()
+
+ def _cleanup_runs(self, runs_to_remove: List[str]) -> None:
+ """Helper for removing runs from memory.
+
+ Can be overloaded to prevent deletion of runs, which is useful
+ for debugging or when polling on completed runs.
+ """
+ with self._threading_lock:
+ for run_id in runs_to_remove:
+ wandb.termlog(f"{LOG_PREFIX}Cleaning up finished run ({run_id})")
+ del self._runs[run_id]
+
+ def _stop_runs(self) -> None:
+ to_delete = []
+ for run_id, _ in self._yield_runs():
+ to_delete += [run_id]
+
+ for run_id in to_delete:
+ wandb.termlog(f"{LOG_PREFIX}Stopping run ({run_id})")
+ if not self._stop_run(run_id):
+ wandb.termwarn(f"{LOG_PREFIX}Failed to stop run ({run_id})")
+
+ def _stop_run(self, run_id: str) -> bool:
+ """Stops a run and removes it from the scheduler."""
+ if run_id not in self._runs:
+ _logger.debug(f"run: {run_id} not in _runs: {self._runs}")
+ return False
+
+ run = self._runs[run_id]
+ del self._runs[run_id]
+
+ if not run.queued_run:
+ _logger.debug(
+ f"tried to _stop_run but run not queued yet (run_id:{run.id})"
+ )
+ return False
+
+ if not run.state.is_alive:
+ # run already dead, just delete reference
+ return True
+
+ # run still alive, send stop signal
+ encoded_run_id = base64.standard_b64encode(
+ f"Run:v1:{run_id}:{self._project}:{self._entity}".encode()
+ ).decode("utf-8")
+
+ try:
+ success: bool = self._api.stop_run(run_id=encoded_run_id)
+ if success:
+ wandb.termlog(f"{LOG_PREFIX}Stopped run {run_id}.")
+ return True
+ except Exception as e:
+ _logger.debug(f"error stopping run ({run_id}): {e}")
+
+ return False
+
+ def _update_scheduler_run_state(self) -> None:
+ """Update the scheduler state from state of scheduler run and sweep state."""
+ state: RunState = self._get_run_state(self._wandb_run.id)
+
+ # map scheduler run-state to scheduler-state
+ if state == RunState.KILLED:
+ self.state = SchedulerState.STOPPED
+ elif state in [RunState.FAILED, RunState.CRASHED]:
+ self.state = SchedulerState.FAILED
+ elif state == RunState.FINISHED:
+ self.state = SchedulerState.COMPLETED
+
+ # check sweep state for completed states, overwrite scheduler state
+ try:
+ sweep_state = self._api.get_sweep_state(
+ self._sweep_id, self._entity, self._project
+ )
+ except Exception as e:
+ _logger.debug(f"sweep state error: {e}")
+ return
+
+ if sweep_state == "FINISHED":
+ self.state = SchedulerState.COMPLETED
+ elif sweep_state in ["CANCELLED", "STOPPED"]:
+ self.state = SchedulerState.CANCELLED
+ elif sweep_state == "PAUSED":
+ self.state = SchedulerState.FLUSH_RUNS
+
+ def _update_run_states(self) -> None:
+ """Iterate through runs.
+
+ Get state from backend and deletes runs if not in running state. Threadsafe.
+ """
+ runs_to_remove: List[str] = []
+ for run_id, run in self._yield_runs():
+ run.state = self._get_run_state(run_id, run.state)
+
+ try:
+ rqi_state = run.queued_run.state if run.queued_run else None
+ except (CommError, LaunchError) as e:
+ _logger.debug(f"Failed to get queued_run.state: {e}")
+ rqi_state = None
+
+ if not run.state.is_alive or rqi_state == "failed":
+ _logger.debug(f"({run_id}) states: ({run.state}, {rqi_state})")
+ runs_to_remove.append(run_id)
+ self._cleanup_runs(runs_to_remove)
+
+ def _get_metrics_from_run(self, run_id: str) -> List[Any]:
+ """Use the public api to get metrics from a run.
+
+ Uses the metric name found in the sweep config, any
+ misspellings will result in an empty list.
+ """
+ try:
+ queued_run: Optional[QueuedRun] = self._runs[run_id].queued_run
+ if not queued_run:
+ return []
+
+ api_run: Run = self._public_api.run(
+ f"{queued_run.entity}/{queued_run.project}/{run_id}"
+ )
+ metric_name = self._sweep_config["metric"]["name"]
+ history = api_run.scan_history(keys=["_step", metric_name])
+ metrics = [x[metric_name] for x in history]
+
+ return metrics
+ except Exception as e:
+ _logger.debug(f"[_get_metrics_from_run] {e}")
+ return []
+
+ def _get_run_info(self, run_id: str) -> Dict[str, Any]:
+ """Use the public api to get info about a run."""
+ try:
+ info: Dict[str, Any] = self._api.get_run_info(
+ self._entity, self._project, run_id
+ )
+ if info:
+ return info
+ except Exception as e:
+ _logger.debug(f"[_get_run_info] {e}")
+ return {}
+
+ def _get_run_state(
+ self, run_id: str, prev_run_state: RunState = RunState.UNKNOWN
+ ) -> RunState:
+ """Use the public api to get state of a run."""
+ run_state = None
+ try:
+ state = self._api.get_run_state(self._entity, self._project, run_id)
+ run_state = RunState(state)
+ except CommError as e:
+ _logger.debug(f"error getting state for run ({run_id}): {e}")
+ if prev_run_state == RunState.UNKNOWN:
+ # triggers when we get an unknown state for the second time
+ wandb.termwarn(
+ f"Failed to get runstate for run ({run_id}). Error: {traceback.format_exc()}"
+ )
+ run_state = RunState.FAILED
+ else: # first time we get unknown state
+ run_state = RunState.UNKNOWN
+ except (AttributeError, ValueError):
+ wandb.termwarn(
+ f"Bad state ({run_state}) for run ({run_id}). Error: {traceback.format_exc()}"
+ )
+ run_state = RunState.UNKNOWN
+ return run_state
+
+ def _create_run(self) -> Dict[str, Any]:
+ """Use the public api to create a blank run."""
+ try:
+ run: List[Dict[str, Any]] = self._api.upsert_run(
+ project=self._project,
+ entity=self._entity,
+ sweep_name=self._sweep_id,
+ )
+ if run:
+ return run[0]
+ except Exception as e:
+ _logger.debug(f"[_create_run] {e}")
+ raise SchedulerError(
+ "Error creating run from scheduler, check API connection and CLI version."
+ )
+ return {}
+
+ def _set_sweep_state(self, state: str) -> None:
+ wandb.termlog(f"{LOG_PREFIX}Updating sweep state to: {state.lower()}")
+ try:
+ self._api.set_sweep_state(sweep=self._sweep_id, state=state)
+ except Exception as e:
+ _logger.debug(f"[set_sweep_state] {e}")
+
+ def _encode(self, _id: str) -> str:
+ return (
+ base64.b64decode(bytes(_id.encode("utf-8"))).decode("utf-8").split(":")[2]
+ )
+
+ def _make_entry_and_launch_config(
+ self, run: SweepRun
+ ) -> Tuple[Optional[List[str]], Dict[str, Dict[str, Any]]]:
+ args = create_sweep_command_args({"args": run.args})
+ entry_point, macro_args = make_launch_sweep_entrypoint(
+ args, self._sweep_config.get("command")
+ )
+ # handle program macro
+ if entry_point and "${program}" in entry_point:
+ if not self._sweep_config.get("program"):
+ raise SchedulerError(
+ f"{LOG_PREFIX}Program macro in command has no corresponding 'program' in sweep config."
+ )
+ pidx = entry_point.index("${program}")
+ entry_point[pidx] = self._sweep_config["program"]
+
+ launch_config = copy.deepcopy(self._wandb_run.config.get("launch", {}))
+ if "overrides" not in launch_config:
+ launch_config["overrides"] = {"run_config": {}}
+ if "run_config" not in launch_config["overrides"]:
+ launch_config["overrides"]["run_config"] = {}
+ launch_config["overrides"]["run_config"].update(args["args_dict"])
+
+ if macro_args: # pipe in hyperparam args as params to launch
+ launch_config["overrides"]["args"] = macro_args
+
+ if entry_point:
+ unresolved = [x for x in entry_point if str(x).startswith("${")]
+ if unresolved:
+ wandb.termwarn(
+ f"{LOG_PREFIX}Sweep command contains unresolved macros: "
+ f"{unresolved}, see launch docs for supported macros."
+ )
+ return entry_point, launch_config
+
+ def _add_to_launch_queue(self, run: SweepRun) -> bool:
+ """Convert a sweeprun into a launch job then push to runqueue."""
+ # job and image first from CLI args, then from sweep config
+ _job = self._kwargs.get("job") or self._sweep_config.get("job")
+ _sweep_config_uri = self._sweep_config.get("image_uri")
+ _image_uri = self._kwargs.get("image_uri") or _sweep_config_uri
+ if _job is None and _image_uri is None:
+ raise SchedulerError(f"{LOG_PREFIX}No 'job' nor 'image_uri' ({run.id})")
+ elif _job is not None and _image_uri is not None:
+ raise SchedulerError(f"{LOG_PREFIX}Sweep has both 'job' and 'image_uri'")
+
+ entry_point, launch_config = self._make_entry_and_launch_config(run)
+ if entry_point:
+ wandb.termwarn(
+ f"{LOG_PREFIX}Sweep command {entry_point} will override"
+ f" {'job' if _job else 'image_uri'} entrypoint"
+ )
+
+ # override resource and args of job
+ _job_launch_config = copy.deepcopy(self._wandb_run.config.get("launch")) or {}
+
+ # default priority is "medium"
+ _priority = int(launch_config.get("priority", 2)) # type: ignore
+
+ # strip resource_args and template_variables from launch_config
+ strip_resource_args_and_template_vars(_job_launch_config)
+
+ run_id = run.id or generate_id()
+ queued_run = launch_add(
+ run_id=run_id,
+ entry_point=entry_point,
+ config=launch_config,
+ docker_image=_image_uri, # TODO(gst): make agnostic (github? run uri?)
+ job=_job,
+ project=self._project,
+ entity=self._entity,
+ queue_name=self._kwargs.get("queue"),
+ project_queue=self._project_queue,
+ resource=_job_launch_config.get("resource"),
+ resource_args=_job_launch_config.get("resource_args"),
+ template_variables=_job_launch_config.get("template_variables"),
+ author=self._kwargs.get("author"),
+ sweep_id=self._sweep_id,
+ priority=_priority,
+ )
+ run.queued_run = queued_run
+ # TODO(gst): unify run and queued_run state
+ run.state = RunState.RUNNING # assume it will get picked up
+ self._runs[run_id] = run
+
+ wandb.termlog(
+ f"{LOG_PREFIX}Added run ({run_id}) to queue ({self._kwargs.get('queue')})"
+ )
+ return True
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/sweeps/scheduler_sweep.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/sweeps/scheduler_sweep.py
new file mode 100644
index 0000000000000000000000000000000000000000..40484fdc2ac47aa2856d3c123e465f913e2e290a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/sweeps/scheduler_sweep.py
@@ -0,0 +1,90 @@
+"""Scheduler for classic wandb Sweeps."""
+
+import logging
+from pprint import pformat as pf
+from typing import Any, Dict, List, Optional
+
+import wandb
+from wandb.sdk.launch.sweeps.scheduler import LOG_PREFIX, RunState, Scheduler, SweepRun
+
+_logger = logging.getLogger(__name__)
+
+
+class SweepScheduler(Scheduler):
+ """A controller/agent that populates a Launch RunQueue from a sweeps RunQueue."""
+
+ def __init__(
+ self,
+ *args: Any,
+ **kwargs: Any,
+ ):
+ super().__init__(*args, **kwargs)
+
+ def _get_next_sweep_run(self, worker_id: int) -> Optional[SweepRun]:
+ """Called by the main scheduler execution loop.
+
+ Expected to return a properly formatted SweepRun if the scheduler
+ is alive, or None and set the appropriate scheduler state:
+
+ FAILED: self.fail_sweep()
+ STOPPED: self.stop_sweep()
+ """
+ commands: List[Dict[str, Any]] = self._get_sweep_commands(worker_id)
+ for command in commands:
+ # The command "type" can be one of "run", "resume", "stop", "exit"
+ _type = command.get("type")
+ if _type in ["exit", "stop"]:
+ self.stop_sweep()
+ return None
+
+ if _type not in ["run", "resume"]:
+ self.fail_sweep(f"AgentHeartbeat unknown command: {_type}")
+
+ _run_id: Optional[str] = command.get("run_id")
+ if not _run_id:
+ self.fail_sweep(f"No run id in agent heartbeat: {command}")
+ return None
+
+ if _run_id in self._runs:
+ wandb.termlog(f"{LOG_PREFIX}Skipping duplicate run: {_run_id}")
+ continue
+
+ return SweepRun(
+ id=_run_id,
+ state=RunState.PENDING,
+ args=command.get("args", {}),
+ logs=command.get("logs", []),
+ worker_id=worker_id,
+ )
+ return None
+
+ def _get_sweep_commands(self, worker_id: int) -> List[Dict[str, Any]]:
+ """Helper to receive sweep command from backend."""
+ # AgentHeartbeat wants a Dict of runs which are running or queued
+ _run_states: Dict[str, bool] = {}
+ for run_id, run in self._yield_runs():
+ # Filter out runs that are from a different worker thread
+ if run.worker_id == worker_id and run.state.is_alive:
+ _run_states[run_id] = True
+
+ _logger.debug(f"Sending states: \n{pf(_run_states)}\n")
+ commands: List[Dict[str, Any]] = self._api.agent_heartbeat(
+ agent_id=self._workers[worker_id].agent_id,
+ metrics={},
+ run_states=_run_states,
+ )
+ _logger.debug(f"AgentHeartbeat commands: \n{pf(commands)}\n")
+
+ return commands
+
+ def _exit(self) -> None:
+ pass
+
+ def _poll(self) -> None:
+ _logger.debug(f"_poll. _runs: {self._runs}")
+
+ def _load_state(self) -> None:
+ pass
+
+ def _save_state(self) -> None:
+ pass
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/sweeps/utils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/sweeps/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..d09defe9b8d757f04e08e663abc277b171d6bfcf
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/sweeps/utils.py
@@ -0,0 +1,324 @@
+import json
+import os
+import re
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
+
+import yaml
+
+import wandb
+from wandb import util
+from wandb.sdk.launch.errors import LaunchError
+
+if TYPE_CHECKING:
+ from wandb.apis.public import Api as PublicApi
+
+DEFAULT_SWEEP_COMMAND: List[str] = [
+ "${env}",
+ "${interpreter}",
+ "${program}",
+ "${args}",
+]
+SWEEP_COMMAND_ENV_VAR_REGEX = re.compile(r"\$\{envvar\:([A-Z0-9_]*)\}")
+
+
+def parse_sweep_id(parts_dict: dict) -> Optional[str]:
+ """In place parse sweep path from parts dict.
+
+ Arguments:
+ parts_dict (dict): dict(entity=,project=,name=). Modifies dict inplace.
+
+ Returns:
+ None or str if there is an error
+ """
+ entity = None
+ project = None
+ sweep_id = parts_dict.get("name")
+ if not isinstance(sweep_id, str):
+ return "Expected string sweep_id"
+
+ sweep_split = sweep_id.split("/")
+ if len(sweep_split) == 1:
+ pass
+ elif len(sweep_split) == 2:
+ split_project, sweep_id = sweep_split
+ project = split_project or project
+ elif len(sweep_split) == 3:
+ split_entity, split_project, sweep_id = sweep_split
+ project = split_project or project
+ entity = split_entity or entity
+ else:
+ return (
+ "Expected sweep_id in form of sweep, project/sweep, or entity/project/sweep"
+ )
+ parts_dict.update(dict(name=sweep_id, project=project, entity=entity))
+ return None
+
+
+def sweep_config_err_text_from_jsonschema_violations(violations: List[str]) -> str:
+ """Consolidate schema violation strings from wandb/sweeps into a single string.
+
+ Parameters
+ ----------
+ violations: list of str
+ The warnings to render.
+
+ Returns:
+ -------
+ violation: str
+ The consolidated violation text.
+
+ """
+ violation_base = (
+ "Malformed sweep config detected! This may cause your sweep to behave in unexpected ways.\n"
+ "To avoid this, please fix the sweep config schema violations below:"
+ )
+
+ for i, warning in enumerate(violations):
+ violations[i] = f" Violation {i + 1}. {warning}"
+ violation = "\n".join([violation_base] + violations)
+
+ return violation
+
+
+def handle_sweep_config_violations(warnings: List[str]) -> None:
+ """Echo sweep config schema violation warnings from Gorilla to the terminal.
+
+ Parameters
+ ----------
+ warnings: list of str
+ The warnings to render.
+ """
+ warning = sweep_config_err_text_from_jsonschema_violations(warnings)
+ if len(warnings) > 0:
+ wandb.termwarn(warning)
+
+
+def load_sweep_config(sweep_config_path: str) -> Optional[Dict[str, Any]]:
+ """Load a sweep yaml from path."""
+ try:
+ yaml_file = open(sweep_config_path)
+ except OSError:
+ wandb.termerror(f"Couldn't open sweep file: {sweep_config_path}")
+ return None
+ try:
+ config: Optional[Dict[str, Any]] = yaml.safe_load(yaml_file)
+ except yaml.YAMLError as err:
+ wandb.termerror(f"Error in configuration file: {err}")
+ return None
+ if not config:
+ wandb.termerror("Configuration file is empty")
+ return None
+ return config
+
+
+def load_launch_sweep_config(config: Optional[str]) -> Any:
+ if not config:
+ return {}
+
+ parsed_config = util.load_json_yaml_dict(config)
+ if parsed_config is None:
+ raise LaunchError(f"Could not load config from {config}. Check formatting")
+ return parsed_config
+
+
+def construct_scheduler_args(
+ sweep_config: Dict[str, Any],
+ queue: str,
+ project: str,
+ author: Optional[str] = None,
+ return_job: bool = False,
+) -> Union[List[str], Dict[str, str], None]:
+ """Construct sweep scheduler args.
+
+ logs error and returns None if misconfigured,
+ otherwise returns args as a dict if is_job else a list of strings.
+ """
+ job = sweep_config.get("job")
+ image_uri = sweep_config.get("image_uri")
+ if not job and not image_uri: # don't allow empty string
+ wandb.termerror(
+ "No 'job' nor 'image_uri' top-level key found in sweep config, exactly one is required for a launch-sweep"
+ )
+ return None
+ elif job and image_uri:
+ wandb.termerror(
+ "Sweep config has both 'job' and 'image_uri' but a launch-sweep can use only one"
+ )
+ return None
+
+ # if scheduler is a job, return args as dict
+ if return_job:
+ args_dict: Dict[str, str] = {
+ "sweep_id": "WANDB_SWEEP_ID",
+ "queue": queue,
+ "project": project,
+ }
+ if job:
+ args_dict["job"] = job
+ elif image_uri:
+ args_dict["image_uri"] = image_uri
+
+ if author:
+ args_dict["author"] = author
+
+ return args_dict
+
+ # scheduler uses cli commands, pass args as param list
+ args = [
+ "--queue",
+ f"{queue!r}",
+ "--project",
+ f"{project!r}",
+ ]
+ if author:
+ args += [
+ "--author",
+ f"{author!r}",
+ ]
+ if job:
+ args += [
+ "--job",
+ f"{job!r}",
+ ]
+ elif image_uri:
+ args += ["--image_uri", image_uri]
+
+ return args
+
+
+def create_sweep_command(command: Optional[List] = None) -> List:
+ """Return sweep command, filling in environment variable macros."""
+ # Start from default sweep command
+ command = command or DEFAULT_SWEEP_COMMAND
+ for i, chunk in enumerate(command):
+ # Replace environment variable macros
+ # Search a str(chunk), but allow matches to be of any (ex: int) type
+ if SWEEP_COMMAND_ENV_VAR_REGEX.search(str(chunk)):
+ # Replace from backwards forwards
+ matches = list(SWEEP_COMMAND_ENV_VAR_REGEX.finditer(chunk))
+ for m in matches[::-1]:
+ # Default to just leaving as is if environment variable does not exist
+ _var: str = os.environ.get(m.group(1), m.group(1))
+ command[i] = f"{command[i][: m.start()]}{_var}{command[i][m.end() :]}"
+ return command
+
+
+def create_sweep_command_args(command: Dict) -> Dict[str, Any]:
+ """Create various formats of command arguments for the agent.
+
+ Raises:
+ ValueError: improperly formatted command dict
+
+ """
+ if "args" not in command:
+ raise ValueError(f'No "args" found in command: {command}')
+ # four different formats of command args
+ # (1) standard command line flags (e.g. --foo=bar)
+ flags: List[str] = []
+ # (2) flags without hyphens (e.g. foo=bar)
+ flags_no_hyphens: List[str] = []
+ # (3) flags with false booleans omitted (e.g. --foo)
+ flags_no_booleans: List[str] = []
+ # (4) flags as a dictionary (used for constructing a json)
+ flags_dict: Dict[str, Any] = {}
+ # (5) flags without equals (e.g. --foo bar)
+ args_no_equals: List[str] = []
+ # (6) flags for hydra append config value (e.g. +foo=bar)
+ flags_append_hydra: List[str] = []
+ # (7) flags for hydra override config value (e.g. ++foo=bar)
+ flags_override_hydra: List[str] = []
+ for param, config in command["args"].items():
+ # allow 'None' as a valid value, but error if no value is found
+ try:
+ _value: Any = config["value"]
+ except KeyError:
+ raise ValueError(f'No "value" found for command["args"]["{param}"]')
+
+ _flag: str = f"{param}={_value}"
+ flags.append("--" + _flag)
+ flags_no_hyphens.append(_flag)
+ args_no_equals += [f"--{param}", str(_value)]
+ flags_append_hydra.append("+" + _flag)
+ flags_override_hydra.append("++" + _flag)
+ if isinstance(_value, bool):
+ # omit flags if they are boolean and false
+ if _value:
+ flags_no_booleans.append("--" + param)
+ else:
+ flags_no_booleans.append("--" + _flag)
+ flags_dict[param] = _value
+ return {
+ "args": flags,
+ "args_no_equals": args_no_equals,
+ "args_no_hyphens": flags_no_hyphens,
+ "args_no_boolean_flags": flags_no_booleans,
+ "args_json": [json.dumps(flags_dict)],
+ "args_dict": flags_dict,
+ "args_append_hydra": flags_append_hydra,
+ "args_override_hydra": flags_override_hydra,
+ }
+
+
+def make_launch_sweep_entrypoint(
+ args: Dict[str, Any], command: Optional[List[str]]
+) -> Tuple[Optional[List[str]], Any]:
+ """Use args dict from create_sweep_command_args to construct entrypoint.
+
+ If replace is True, remove macros from entrypoint, fill them in with args
+ and then return the args in separate return value.
+ """
+ if not command:
+ return None, None
+
+ entry_point = create_sweep_command(command)
+ macro_args = {}
+ for macro in args:
+ mstr = "${" + macro + "}"
+ if mstr in entry_point:
+ idx = entry_point.index(mstr)
+ # only supports 1 macro per entrypoint
+ macro_args = args[macro]
+ entry_point = entry_point[:idx] + entry_point[idx + 1 :]
+
+ if len(entry_point) == 0:
+ return None, macro_args
+
+ return entry_point, macro_args
+
+
+def check_job_exists(public_api: "PublicApi", job: Optional[str]) -> bool:
+ """Check if the job exists using the public api.
+
+ Returns: True if no job is passed, or if the job exists.
+ Returns: False if the job is misformatted or doesn't exist.
+ """
+ if not job:
+ return True
+
+ try:
+ public_api.job(job)
+ except Exception as e:
+ wandb.termerror(f"Failed to load job. {e}")
+ return False
+ return True
+
+
+def get_previous_args(
+ run_spec: Dict[str, Any],
+) -> Tuple[Dict[str, Any], Dict[str, Any]]:
+ """Parse through previous scheduler run_spec.
+
+ returns scheduler_args and settings.
+ """
+ scheduler_args = (
+ run_spec.get("overrides", {}).get("run_config", {}).get("scheduler", {})
+ )
+ # also pipe through top level resource setup
+ if run_spec.get("resource"):
+ scheduler_args["resource"] = run_spec["resource"]
+ if run_spec.get("resource_args"):
+ scheduler_args["resource_args"] = run_spec["resource_args"]
+
+ settings = run_spec.get("overrides", {}).get("run_config", {}).get("settings", {})
+
+ return scheduler_args, settings
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/utils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..89046dd2f7e35bed515ea93817260c1d69a3a2b8
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/utils.py
@@ -0,0 +1,827 @@
+import asyncio
+import json
+import logging
+import os
+import platform
+import re
+import subprocess
+import sys
+from collections import defaultdict
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Dict,
+ Iterator,
+ List,
+ Optional,
+ Tuple,
+ Union,
+ cast,
+)
+
+import click
+
+import wandb
+import wandb.docker as docker
+from wandb import util
+from wandb.apis.internal import Api
+from wandb.sdk.launch.errors import LaunchError
+from wandb.sdk.launch.git_reference import GitReference
+from wandb.sdk.launch.wandb_reference import WandbReference
+from wandb.sdk.wandb_config import Config
+
+from .builder.templates._wandb_bootstrap import (
+ FAILED_PACKAGES_POSTFIX,
+ FAILED_PACKAGES_PREFIX,
+)
+
+FAILED_PACKAGES_REGEX = re.compile(
+ f"{re.escape(FAILED_PACKAGES_PREFIX)}(.*){re.escape(FAILED_PACKAGES_POSTFIX)}"
+)
+
+if TYPE_CHECKING: # pragma: no cover
+ from wandb.sdk.launch.agent.job_status_tracker import JobAndRunStatusTracker
+
+
+# TODO: this should be restricted to just Git repos and not S3 and stuff like that
+_GIT_URI_REGEX = re.compile(
+ r"^[^/|^~|^\.].*(git|bitbucket|dev\.azure\.com|\.visualstudio\.com)"
+)
+_VALID_IP_REGEX = r"^https?://[0-9]+(?:\.[0-9]+){3}(:[0-9]+)?"
+_VALID_PIP_PACKAGE_REGEX = r"^[a-zA-Z0-9_.-]+$"
+_VALID_WANDB_REGEX = r"^https?://(api.)?wandb"
+_WANDB_URI_REGEX = re.compile(r"|".join([_VALID_WANDB_REGEX, _VALID_IP_REGEX]))
+_WANDB_QA_URI_REGEX = re.compile(
+ r"^https?://ap\w.qa.wandb"
+) # for testing, not sure if we wanna keep this
+_WANDB_DEV_URI_REGEX = re.compile(
+ r"^https?://ap\w.wandb.test"
+) # for testing, not sure if we wanna keep this
+_WANDB_LOCAL_DEV_URI_REGEX = re.compile(
+ r"^https?://localhost"
+) # for testing, not sure if we wanna keep this
+
+API_KEY_REGEX = r"WANDB_API_KEY=\w+(-\w+)?"
+
+MACRO_REGEX = re.compile(r"\$\{(\w+)\}")
+
+AZURE_CONTAINER_REGISTRY_URI_REGEX = re.compile(
+ r"^(?:https://)?([\w]+)\.azurecr\.io/(?P[\w\-]+):?(?P.*)"
+)
+
+ELASTIC_CONTAINER_REGISTRY_URI_REGEX = re.compile(
+ r"^(?:https://)?(?P[\w-]+)\.dkr\.ecr\.(?P[\w-]+)\.amazonaws\.com/(?P[\.\/\w-]+):?(?P.*)$"
+)
+
+GCP_ARTIFACT_REGISTRY_URI_REGEX = re.compile(
+ r"^(?:https://)?(?P[\w-]+)-docker\.pkg\.dev/(?P[\w-]+)/(?P[\w-]+)/?(?P[\w-]+)?(?P:.*)?$",
+ re.IGNORECASE,
+)
+
+S3_URI_RE = re.compile(r"s3://([^/]+)(/(.*))?")
+GCS_URI_RE = re.compile(r"gs://([^/]+)(?:/(.*))?")
+AZURE_BLOB_REGEX = re.compile(
+ r"^https://([^\.]+)\.blob\.core\.windows\.net/([^/]+)/?(.*)$"
+)
+
+ARN_PARTITION_RE = re.compile(r"^arn:([^:]+):[^:]*:[^:]*:[^:]*:[^:]*$")
+
+PROJECT_SYNCHRONOUS = "SYNCHRONOUS"
+
+LAUNCH_CONFIG_FILE = "~/.config/wandb/launch-config.yaml"
+LAUNCH_DEFAULT_PROJECT = "model-registry"
+
+_logger = logging.getLogger(__name__)
+LOG_PREFIX = f"{click.style('launch:', fg='magenta')} "
+
+MAX_ENV_LENGTHS: Dict[str, int] = defaultdict(lambda: 32670)
+MAX_ENV_LENGTHS["SageMakerRunner"] = 512
+
+CODE_MOUNT_DIR = "/mnt/wandb"
+
+
+def load_wandb_config() -> Config:
+ """Load wandb config from WANDB_CONFIG environment variable(s).
+
+ The WANDB_CONFIG environment variable is a json string that can contain
+ multiple config keys. The WANDB_CONFIG_[0-9]+ environment variables are
+ used for environments where there is a limit on the length of environment
+ variables. In that case, we shard the contents of WANDB_CONFIG into
+ multiple environment variables numbered from 0.
+
+ Returns:
+ A dictionary of wandb config values.
+ """
+ config_str = os.environ.get("WANDB_CONFIG")
+ if config_str is None:
+ config_str = ""
+ idx = 0
+ while True:
+ chunk = os.environ.get(f"WANDB_CONFIG_{idx}")
+ if chunk is None:
+ break
+ config_str += chunk
+ idx += 1
+ if idx < 1:
+ raise LaunchError(
+ "No WANDB_CONFIG or WANDB_CONFIG_[0-9]+ environment variables found"
+ )
+ wandb_config = Config()
+ try:
+ env_config = json.loads(config_str)
+ except json.JSONDecodeError as e:
+ raise LaunchError(f"Failed to parse WANDB_CONFIG: {e}") from e
+
+ wandb_config.update(env_config)
+ return wandb_config
+
+
+def event_loop_thread_exec(func: Any) -> Any:
+ """Wrapper for running any function in an awaitable thread on an event loop.
+
+ Example usage:
+ ```
+ def my_func(arg1, arg2):
+ return arg1 + arg2
+
+
+ future = event_loop_thread_exec(my_func)(2, 2)
+ assert await future == 4
+ ```
+
+ The returned function must be called within an active event loop.
+ """
+
+ async def wrapper(*args: Any, **kwargs: Any) -> Any:
+ loop = asyncio.get_event_loop()
+ result = cast(
+ Any, await loop.run_in_executor(None, lambda: func(*args, **kwargs))
+ )
+ return result
+
+ return wrapper
+
+
+def _is_wandb_uri(uri: str) -> bool:
+ return (
+ _WANDB_URI_REGEX.match(uri)
+ or _WANDB_DEV_URI_REGEX.match(uri)
+ or _WANDB_LOCAL_DEV_URI_REGEX.match(uri)
+ or _WANDB_QA_URI_REGEX.match(uri)
+ ) is not None
+
+
+def _is_wandb_dev_uri(uri: str) -> bool:
+ return bool(_WANDB_DEV_URI_REGEX.match(uri))
+
+
+def _is_wandb_local_uri(uri: str) -> bool:
+ return bool(_WANDB_LOCAL_DEV_URI_REGEX.match(uri))
+
+
+def _is_git_uri(uri: str) -> bool:
+ return bool(_GIT_URI_REGEX.match(uri))
+
+
+def sanitize_wandb_api_key(s: str) -> str:
+ return str(re.sub(API_KEY_REGEX, "WANDB_API_KEY", s))
+
+
+def get_project_from_job(job: str) -> Optional[str]:
+ job_parts = job.split("/")
+ if len(job_parts) == 3:
+ return job_parts[1]
+ return None
+
+
+def set_project_entity_defaults(
+ uri: Optional[str],
+ job: Optional[str],
+ api: Api,
+ project: Optional[str],
+ entity: Optional[str],
+ launch_config: Optional[Dict[str, Any]],
+) -> Tuple[Optional[str], str]:
+ # set the target project and entity if not provided
+ source_uri = None
+ if uri is not None:
+ if _is_wandb_uri(uri):
+ _, source_uri, _ = parse_wandb_uri(uri)
+ elif _is_git_uri(uri):
+ source_uri = os.path.splitext(os.path.basename(uri))[0]
+ elif job is not None:
+ source_uri = get_project_from_job(job)
+ if project is None:
+ config_project = None
+ if launch_config:
+ config_project = launch_config.get("project")
+ project = config_project or source_uri or ""
+ if entity is None:
+ entity = get_default_entity(api, launch_config)
+ prefix = ""
+ if platform.system() != "Windows" and sys.stdout.encoding == "UTF-8":
+ prefix = "🚀 "
+ wandb.termlog(
+ f"{LOG_PREFIX}{prefix}Launching run into {entity}{'/' + project if project else ''}"
+ )
+ return project, entity
+
+
+def get_default_entity(api: Api, launch_config: Optional[Dict[str, Any]]):
+ config_entity = None
+ if launch_config:
+ config_entity = launch_config.get("entity")
+ return config_entity or api.default_entity
+
+
+def strip_resource_args_and_template_vars(launch_spec: Dict[str, Any]) -> None:
+ if launch_spec.get("resource_args", None) and launch_spec.get(
+ "template_variables", None
+ ):
+ wandb.termwarn(
+ "Launch spec contains both resource_args and template_variables, "
+ "only one can be set. Using template_variables."
+ )
+ launch_spec.pop("resource_args")
+
+
+def construct_launch_spec(
+ uri: Optional[str],
+ job: Optional[str],
+ api: Api,
+ name: Optional[str],
+ project: Optional[str],
+ entity: Optional[str],
+ docker_image: Optional[str],
+ resource: Optional[str],
+ entry_point: Optional[List[str]],
+ version: Optional[str],
+ resource_args: Optional[Dict[str, Any]],
+ launch_config: Optional[Dict[str, Any]],
+ run_id: Optional[str],
+ repository: Optional[str],
+ author: Optional[str],
+ sweep_id: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Construct the launch specification from CLI arguments."""
+ # override base config (if supplied) with supplied args
+ launch_spec = launch_config if launch_config is not None else {}
+ if uri is not None:
+ launch_spec["uri"] = uri
+ if job is not None:
+ launch_spec["job"] = job
+ project, entity = set_project_entity_defaults(
+ uri,
+ job,
+ api,
+ project,
+ entity,
+ launch_config,
+ )
+ launch_spec["entity"] = entity
+ if author:
+ launch_spec["author"] = author
+
+ launch_spec["project"] = project
+ if name:
+ launch_spec["name"] = name
+ if "docker" not in launch_spec:
+ launch_spec["docker"] = {}
+ if docker_image:
+ launch_spec["docker"]["docker_image"] = docker_image
+ if sweep_id: # all runs in a sweep have this set
+ launch_spec["sweep_id"] = sweep_id
+
+ if "resource" not in launch_spec:
+ launch_spec["resource"] = resource if resource else None
+
+ if "git" not in launch_spec:
+ launch_spec["git"] = {}
+ if version:
+ launch_spec["git"]["version"] = version
+
+ if "overrides" not in launch_spec:
+ launch_spec["overrides"] = {}
+
+ if not isinstance(launch_spec["overrides"].get("args", []), list):
+ raise LaunchError("override args must be a list of strings")
+
+ if resource_args:
+ launch_spec["resource_args"] = resource_args
+
+ if entry_point:
+ launch_spec["overrides"]["entry_point"] = entry_point
+
+ if run_id is not None:
+ launch_spec["run_id"] = run_id
+
+ if repository:
+ launch_config = launch_config or {}
+ if launch_config.get("registry"):
+ launch_config["registry"]["url"] = repository
+ else:
+ launch_config["registry"] = {"url": repository}
+
+ # dont send both resource args and template variables
+ strip_resource_args_and_template_vars(launch_spec)
+
+ return launch_spec
+
+
+def validate_launch_spec_source(launch_spec: Dict[str, Any]) -> None:
+ job = launch_spec.get("job")
+ docker_image = launch_spec.get("docker", {}).get("docker_image")
+ if bool(job) == bool(docker_image):
+ raise LaunchError(
+ "Exactly one of job or docker_image must be specified in the launch spec."
+ )
+
+
+def parse_wandb_uri(uri: str) -> Tuple[str, str, str]:
+ """Parse wandb uri to retrieve entity, project and run name."""
+ ref = WandbReference.parse(uri)
+ if not ref or not ref.entity or not ref.project or not ref.run_id:
+ raise LaunchError(f"Trouble parsing wandb uri {uri}")
+ return (ref.entity, ref.project, ref.run_id)
+
+
+def get_local_python_deps(
+ dir: str, filename: str = "requirements.local.txt"
+) -> Optional[str]:
+ try:
+ env = os.environ
+ with open(os.path.join(dir, filename), "w") as f:
+ subprocess.call(["pip", "freeze"], env=env, stdout=f)
+ return filename
+ except subprocess.CalledProcessError as e:
+ wandb.termerror(f"Command failed: {e}")
+ return None
+
+
+def diff_pip_requirements(req_1: List[str], req_2: List[str]) -> Dict[str, str]:
+ """Return a list of pip requirements that are not in req_1 but are in req_2."""
+
+ def _parse_req(req: List[str]) -> Dict[str, str]:
+ # TODO: This can be made more exhaustive, but for 99% of cases this is fine
+ # see https://pip.pypa.io/en/stable/reference/requirements-file-format/#example
+ d: Dict[str, str] = dict()
+ for line in req:
+ _name: str = None # type: ignore
+ _version: str = None # type: ignore
+ if line.startswith("#"): # Ignore comments
+ continue
+ elif "git+" in line or "hg+" in line:
+ _name = line.split("#egg=")[1]
+ _version = line.split("@")[-1].split("#")[0]
+ elif "==" in line:
+ _s = line.split("==")
+ _name = _s[0].lower()
+ _version = _s[1].split("#")[0].strip()
+ elif ">=" in line:
+ _s = line.split(">=")
+ _name = _s[0].lower()
+ _version = _s[1].split("#")[0].strip()
+ elif ">" in line:
+ _s = line.split(">")
+ _name = _s[0].lower()
+ _version = _s[1].split("#")[0].strip()
+ elif re.match(_VALID_PIP_PACKAGE_REGEX, line) is not None:
+ _name = line
+ else:
+ raise ValueError(f"Unable to parse pip requirements file line: {line}")
+ if _name is not None:
+ assert re.match(_VALID_PIP_PACKAGE_REGEX, _name), (
+ f"Invalid pip package name {_name}"
+ )
+ d[_name] = _version
+ return d
+
+ # Use symmetric difference between dict representation to print errors
+ try:
+ req_1_dict: Dict[str, str] = _parse_req(req_1)
+ req_2_dict: Dict[str, str] = _parse_req(req_2)
+ except (AssertionError, ValueError, IndexError, KeyError) as e:
+ raise LaunchError(f"Failed to parse pip requirements: {e}")
+ diff: List[Tuple[str, str]] = []
+ for item in set(req_1_dict.items()) ^ set(req_2_dict.items()):
+ diff.append(item)
+ # Parse through the diff to make it pretty
+ pretty_diff: Dict[str, str] = {}
+ for name, version in diff:
+ if pretty_diff.get(name) is None:
+ pretty_diff[name] = version
+ else:
+ pretty_diff[name] = f"v{version} and v{pretty_diff[name]}"
+ return pretty_diff
+
+
+def validate_wandb_python_deps(
+ requirements_file: Optional[str],
+ dir: str,
+) -> None:
+ """Warn if local python dependencies differ from wandb requirements.txt."""
+ if requirements_file is not None:
+ requirements_path = os.path.join(dir, requirements_file)
+ with open(requirements_path) as f:
+ wandb_python_deps: List[str] = f.read().splitlines()
+
+ local_python_file = get_local_python_deps(dir)
+ if local_python_file is not None:
+ local_python_deps_path = os.path.join(dir, local_python_file)
+ with open(local_python_deps_path) as f:
+ local_python_deps: List[str] = f.read().splitlines()
+
+ diff_pip_requirements(wandb_python_deps, local_python_deps)
+ return
+ _logger.warning("Unable to validate local python dependencies")
+
+
+def apply_patch(patch_string: str, dst_dir: str) -> None:
+ """Applies a patch file to a directory."""
+ _logger.info("Applying diff.patch")
+ with open(os.path.join(dst_dir, "diff.patch"), "w") as fp:
+ fp.write(patch_string)
+ try:
+ subprocess.check_call(
+ [
+ "patch",
+ "-s",
+ f"--directory={dst_dir}",
+ "-p1",
+ "-i",
+ "diff.patch",
+ ]
+ )
+ except subprocess.CalledProcessError:
+ raise wandb.Error("Failed to apply diff.patch associated with run.")
+
+
+def _fetch_git_repo(dst_dir: str, uri: str, version: Optional[str]) -> Optional[str]:
+ """Clones the git repo at ``uri`` into ``dst_dir``.
+
+ checks out commit ``version``. Assumes authentication parameters are
+ specified by the environment, e.g. by a Git credential helper.
+ """
+ # We defer importing git until the last moment, because the import requires that the git
+ # executable is available on the PATH, so we only want to fail if we actually need it.
+
+ _logger.info("Fetching git repo")
+ ref = GitReference(uri, version)
+ if ref is None:
+ raise LaunchError(f"Unable to parse git uri: {uri}")
+ ref.fetch(dst_dir)
+ if version is None:
+ version = ref.ref
+ return version
+
+
+def convert_jupyter_notebook_to_script(fname: str, project_dir: str) -> str:
+ nbconvert = wandb.util.get_module(
+ "nbconvert", "nbformat and nbconvert are required to use launch with notebooks"
+ )
+ nbformat = wandb.util.get_module(
+ "nbformat", "nbformat and nbconvert are required to use launch with notebooks"
+ )
+
+ _logger.info("Converting notebook to script")
+ new_name = fname.replace(".ipynb", ".py")
+ with open(os.path.join(project_dir, fname)) as fh:
+ nb = nbformat.reads(fh.read(), nbformat.NO_CONVERT)
+ for cell in nb.cells:
+ if cell.cell_type == "code":
+ source_lines = cell.source.split("\n")
+ modified_lines = []
+ for line in source_lines:
+ if not line.startswith("!"):
+ modified_lines.append(line)
+ cell.source = "\n".join(modified_lines)
+
+ exporter = nbconvert.PythonExporter()
+ source, meta = exporter.from_notebook_node(nb)
+
+ with open(os.path.join(project_dir, new_name), "w+") as fh:
+ fh.writelines(source)
+ return new_name
+
+
+def to_camel_case(maybe_snake_str: str) -> str:
+ if "_" not in maybe_snake_str:
+ return maybe_snake_str
+ components = maybe_snake_str.split("_")
+ return "".join(x.title() if x else "_" for x in components)
+
+
+def validate_build_and_registry_configs(
+ build_config: Dict[str, Any], registry_config: Dict[str, Any]
+) -> None:
+ build_config_credentials = build_config.get("credentials", {})
+ registry_config_credentials = registry_config.get("credentials", {})
+ if (
+ build_config_credentials
+ and registry_config_credentials
+ and build_config_credentials != registry_config_credentials
+ ):
+ raise LaunchError("registry and build config credential mismatch")
+
+
+async def get_kube_context_and_api_client(
+ kubernetes: Any,
+ resource_args: Dict[str, Any],
+) -> Tuple[Any, Any]:
+ config_file = resource_args.get("configFile", None)
+ context = None
+ if config_file is not None or os.path.exists(os.path.expanduser("~/.kube/config")):
+ # context only exist in the non-incluster case
+ (
+ all_contexts,
+ active_context,
+ ) = kubernetes.config.list_kube_config_contexts(config_file)
+ context = None
+ if resource_args.get("context"):
+ context_name = resource_args["context"]
+ for c in all_contexts:
+ if c["name"] == context_name:
+ context = c
+ break
+ raise LaunchError(f"Specified context {context_name} was not found.")
+ else:
+ context = active_context
+ # TODO: We should not really be performing this check if the user is not
+ # using EKS but I don't see an obvious way to make an eks specific code path
+ # right here.
+ util.get_module(
+ "awscli",
+ "awscli is required to load a kubernetes context "
+ "from eks. Please run `pip install wandb[launch]` to install it.",
+ )
+ await kubernetes.config.load_kube_config(config_file, context["name"])
+ api_client = await kubernetes.config.new_client_from_config(
+ config_file, context=context["name"]
+ )
+ return context, api_client
+ else:
+ kubernetes.config.load_incluster_config()
+ api_client = kubernetes.client.api_client.ApiClient()
+ return context, api_client
+
+
+def resolve_build_and_registry_config(
+ default_launch_config: Optional[Dict[str, Any]],
+ build_config: Optional[Dict[str, Any]],
+ registry_config: Optional[Dict[str, Any]],
+) -> Tuple[Dict[str, Any], Dict[str, Any]]:
+ resolved_build_config: Dict[str, Any] = {}
+ if build_config is None and default_launch_config is not None:
+ resolved_build_config = default_launch_config.get("builder", {})
+ elif build_config is not None:
+ resolved_build_config = build_config
+ resolved_registry_config: Dict[str, Any] = {}
+ if registry_config is None and default_launch_config is not None:
+ resolved_registry_config = default_launch_config.get("registry", {})
+ elif registry_config is not None:
+ resolved_registry_config = registry_config
+ validate_build_and_registry_configs(resolved_build_config, resolved_registry_config)
+ return resolved_build_config, resolved_registry_config
+
+
+def check_logged_in(api: Api) -> bool:
+ """Check if a user is logged in.
+
+ Raises an error if the viewer doesn't load (likely a broken API key). Expected time
+ cost is 0.1-0.2 seconds.
+ """
+ res = api.api.viewer()
+ if not res:
+ raise LaunchError(
+ "Could not connect with current API-key. "
+ "Please relogin using `wandb login --relogin`"
+ " and try again (see `wandb login --help` for more options)"
+ )
+
+ return True
+
+
+def make_name_dns_safe(name: str) -> str:
+ resp = name.replace("_", "-").lower()
+ resp = re.sub(r"[^a-z\.\-]", "", resp)
+ # Actual length limit is 253, but we want to leave room for the generated suffix
+ resp = resp[:200]
+ return resp
+
+
+def make_k8s_label_safe(value: str) -> str:
+ """Return a Kubernetes label/identifier safe string (DNS-1123 label).
+
+ See:
+ https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#dns-label-names
+
+ Rules:
+ - lowercase alphanumeric and '-'
+ - must start and end with an alphanumeric
+ - max length 63
+ """
+ # Normalize common separators first
+ safe = value.replace("_", "-").lower()
+ # Remove any invalid characters
+ safe = re.sub(r"[^a-z0-9\-]", "", safe)
+ # Collapse consecutive '-'
+ safe = re.sub(r"-+", "-", safe)
+ # Trim to 63 and strip leading/trailing '-'
+ safe = safe[:63].strip("-")
+
+ if not safe:
+ raise LaunchError(f"Invalid value for Kubernetes label: {value}")
+
+ return safe
+
+
+def warn_failed_packages_from_build_logs(
+ log: str, image_uri: str, api: Api, job_tracker: Optional["JobAndRunStatusTracker"]
+) -> None:
+ match = FAILED_PACKAGES_REGEX.search(log)
+ if match:
+ _msg = f"Failed to install the following packages: {match.group(1)} for image: {image_uri}. Will attempt to launch image without them."
+ wandb.termwarn(_msg)
+ if job_tracker is not None:
+ res = job_tracker.saver.save_contents(
+ _msg, "failed-packages.log", "warning"
+ )
+ api.update_run_queue_item_warning(
+ job_tracker.run_queue_item_id,
+ "Some packages were not successfully installed during the build",
+ "build",
+ res,
+ )
+
+
+def docker_image_exists(docker_image: str, should_raise: bool = False) -> bool:
+ """Check if a specific image is already available.
+
+ Optionally raises an exception if the image is not found.
+ """
+ _logger.info("Checking if base image exists...")
+ try:
+ docker.run(["docker", "image", "inspect", docker_image])
+ return True
+ except (docker.DockerError, ValueError):
+ if should_raise:
+ raise
+ _logger.info("Base image not found. Generating new base image")
+ return False
+
+
+def pull_docker_image(docker_image: str) -> None:
+ """Pull the requested docker image."""
+ try:
+ docker.run(["docker", "pull", docker_image])
+ except docker.DockerError as e:
+ raise LaunchError(f"Docker server returned error: {e}")
+
+
+def macro_sub(original: str, sub_dict: Dict[str, Optional[str]]) -> str:
+ """Substitute macros in a string.
+
+ Macros occur in the string in the ${macro} format. The macro names are
+ substituted with their values from the given dictionary. If a macro
+ is not found in the dictionary, it is left unchanged.
+
+ Args:
+ original: The string to substitute macros in.
+ sub_dict: A dictionary mapping macro names to their values.
+
+ Returns:
+ The string with the macros substituted.
+ """
+ return MACRO_REGEX.sub(
+ lambda match: str(sub_dict.get(match.group(1), match.group(0))), original
+ )
+
+
+def recursive_macro_sub(source: Any, sub_dict: Dict[str, Optional[str]]) -> Any:
+ """Recursively substitute macros in a parsed JSON or YAML blob.
+
+ Macros occur in strings at leaves of the blob in the ${macro} format.
+ The macro names are substituted with their values from the given dictionary.
+ If a macro is not found in the dictionary, it is left unchanged.
+
+ Arguments:
+ source: The JSON or YAML blob to substitute macros in.
+ sub_dict: A dictionary mapping macro names to their values.
+
+ Returns:
+ The blob with the macros substituted.
+ """
+ if isinstance(source, str):
+ return macro_sub(source, sub_dict)
+ elif isinstance(source, list):
+ return [recursive_macro_sub(item, sub_dict) for item in source]
+ elif isinstance(source, dict):
+ return {
+ key: recursive_macro_sub(value, sub_dict) for key, value in source.items()
+ }
+ else:
+ return source
+
+
+def fetch_and_validate_template_variables(
+ runqueue: Any, fields: dict
+) -> Dict[str, Any]:
+ template_variables = {}
+
+ variable_schemas = {}
+ for tv in runqueue.template_variables:
+ variable_schemas[tv["name"]] = json.loads(tv["schema"])
+
+ for field in fields:
+ field_parts = field.split("=")
+ if len(field_parts) != 2:
+ raise LaunchError(
+ f'--set-var value must be in the format "--set-var key1=value1", instead got: {field}'
+ )
+ key, val = field_parts
+ if key not in variable_schemas:
+ raise LaunchError(
+ f"Queue {runqueue.name} does not support overriding {key}."
+ )
+ schema = variable_schemas.get(key, {})
+ field_type = schema.get("type")
+ try:
+ if field_type == "integer":
+ val = int(val)
+ elif field_type == "number":
+ val = float(val)
+
+ except ValueError:
+ raise LaunchError(f"Value for {key} must be of type {field_type}.")
+ template_variables[key] = val
+ return template_variables
+
+
+def get_entrypoint_file(entrypoint: List[str]) -> Optional[str]:
+ """Get the entrypoint file from the given command.
+
+ Args:
+ entrypoint (List[str]): List of command and arguments.
+
+ Returns:
+ Optional[str]: The entrypoint file if found, otherwise None.
+ """
+ if not entrypoint:
+ return None
+ if entrypoint[0].endswith(".py") or entrypoint[0].endswith(".sh"):
+ return entrypoint[0]
+ if len(entrypoint) < 2:
+ return None
+ return entrypoint[1]
+
+
+def get_current_python_version() -> Tuple[str, str]:
+ full_version = sys.version.split()[0].split(".")
+ major = full_version[0]
+ version = ".".join(full_version[:2]) if len(full_version) >= 2 else major + ".0"
+ return version, major
+
+
+def yield_containers(root: Union[dict, list]) -> Iterator[dict]:
+ """Yield all container specs in a manifest.
+
+ Recursively traverses the manifest and yields all container specs. Container
+ specs are identified by the presence of a "containers" key in the value.
+ """
+ if isinstance(root, dict):
+ for k, v in root.items():
+ if k == "containers":
+ if isinstance(v, list):
+ yield from v
+ elif isinstance(v, (dict, list)):
+ yield from yield_containers(v)
+ elif isinstance(root, list):
+ for item in root:
+ yield from yield_containers(item)
+
+
+def sanitize_identifiers_for_k8s(root: Any) -> None:
+ if isinstance(root, list):
+ for item in root:
+ sanitize_identifiers_for_k8s(item)
+ return
+
+ # Only dicts have metadata and nested structures we need to sanitize.
+ if not isinstance(root, dict):
+ return
+
+ metadata = root.get("metadata")
+ if isinstance(metadata, dict):
+ if name := metadata.get("name"):
+ metadata["name"] = make_k8s_label_safe(str(name))
+
+ for container in yield_containers(root):
+ if name := container.get("name"):
+ container["name"] = make_k8s_label_safe(str(name))
+
+ # nested names
+ for key, value in root.items():
+ if isinstance(value, (dict, list)):
+ sanitize_identifiers_for_k8s(value)
+ elif key == "name" and isinstance(value, str):
+ root[key] = make_k8s_label_safe(value)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/wandb_reference.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/wandb_reference.py
new file mode 100644
index 0000000000000000000000000000000000000000..5de34c04bf3aa77068da19cb6b4af8f1e163709d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/launch/wandb_reference.py
@@ -0,0 +1,138 @@
+"""Support for parsing W&B URLs (which might be user provided) into constituent parts."""
+
+from dataclasses import dataclass
+from enum import IntEnum
+from typing import Optional
+from urllib.parse import urlparse
+
+PREFIX_HTTP = "http://"
+PREFIX_HTTPS = "https://"
+
+
+class ReferenceType(IntEnum):
+ RUN = 1
+ JOB = 2
+
+
+# Ideally we would not overload the URL paths as we do.
+# TODO: Not sure these are exhaustive, and even if so more special paths might get added.
+# Would be good to have restrictions that we could check.
+RESERVED_NON_ENTITIES = (
+ "create-team",
+ "fully-connected",
+ "registry",
+ "settings",
+ "subscriptions",
+)
+RESERVED_NON_PROJECTS = (
+ "likes",
+ "projects",
+)
+RESERVED_JOB_PATHS = ("_view",)
+
+
+@dataclass
+class WandbReference:
+ # TODO: This will include port, should we separate that out?
+ host: Optional[str] = None
+
+ entity: Optional[str] = None
+ project: Optional[str] = None
+
+ # Set when we don't know how to parse yet
+ path: Optional[str] = None
+
+ # Reference type will determine what other fields are set
+ ref_type: Optional[ReferenceType] = None
+
+ run_id: Optional[str] = None
+
+ job_name: Optional[str] = None
+ job_alias: str = "latest" # In addition to an alias can be a version specifier
+
+ def is_bare(self) -> bool:
+ return self.host is None
+
+ def is_job(self) -> bool:
+ return self.ref_type == ReferenceType.JOB
+
+ def is_run(self) -> bool:
+ return self.ref_type == ReferenceType.RUN
+
+ def is_job_or_run(self) -> bool:
+ return self.is_job() or self.is_run()
+
+ def job_reference(self) -> str:
+ assert self.is_job()
+ return f"{self.job_name}:{self.job_alias}"
+
+ def job_reference_scoped(self) -> str:
+ assert self.entity
+ assert self.project
+ unscoped = self.job_reference()
+ return f"{self.entity}/{self.project}/{unscoped}"
+
+ def url_host(self) -> str:
+ return f"{PREFIX_HTTPS}{self.host}" if self.host else ""
+
+ def url_entity(self) -> str:
+ assert self.entity
+ return f"{self.url_host()}/{self.entity}"
+
+ def url_project(self) -> str:
+ assert self.project
+ return f"{self.url_entity()}/{self.project}"
+
+ @staticmethod
+ def parse(uri: str) -> Optional["WandbReference"]:
+ """Attempt to parse a string as a W&B URL."""
+ # TODO: Error if HTTP and host is not localhost?
+ if (
+ not uri.startswith("/")
+ and not uri.startswith(PREFIX_HTTP)
+ and not uri.startswith(PREFIX_HTTPS)
+ ):
+ return None
+
+ ref = WandbReference()
+
+ # This takes care of things like query and fragment
+ parsed = urlparse(uri)
+ if parsed.netloc:
+ ref.host = parsed.netloc
+
+ if not parsed.path.startswith("/"):
+ return ref
+
+ ref.path = parsed.path[1:]
+ parts = ref.path.split("/")
+ if len(parts) > 0:
+ if parts[0] not in RESERVED_NON_ENTITIES:
+ ref.path = None
+ ref.entity = parts[0]
+ if len(parts) > 1:
+ if parts[1] not in RESERVED_NON_PROJECTS:
+ ref.project = parts[1]
+ if len(parts) > 3 and parts[2] == "runs":
+ ref.ref_type = ReferenceType.RUN
+ ref.run_id = parts[3]
+ elif (
+ len(parts) > 4
+ and parts[2] == "artifacts"
+ and parts[3] == "job"
+ ):
+ ref.ref_type = ReferenceType.JOB
+ ref.job_name = parts[4]
+ if len(parts) > 5 and parts[5] not in RESERVED_JOB_PATHS:
+ ref.job_alias = parts[5]
+ # TODO: Right now we are not tracking selection as part of URL state in the Jobs tab.
+ # If that changes we'll want to update this.
+
+ return ref
+
+ @staticmethod
+ def is_uri_job_or_run(uri: str) -> bool:
+ ref = WandbReference.parse(uri)
+ if ref and ref.is_job_or_run():
+ return True
+ return False
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4289765c6c7c4fda2dbe42dddc1f5f7d69da0c45
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/__init__.py
@@ -0,0 +1,5 @@
+from . import lazyloader
+from .disabled import RunDisabled, SummaryDisabled
+from .run_moment import RunMoment
+
+__all__ = ("lazyloader", "RunDisabled", "SummaryDisabled", "RunMoment")
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/apikey.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/apikey.py
new file mode 100644
index 0000000000000000000000000000000000000000..f30e791de800d4d4996b403d163ac9c0a4af9f45
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/apikey.py
@@ -0,0 +1,334 @@
+"""apikey util."""
+
+from __future__ import annotations
+
+import dataclasses
+import os
+import platform
+import stat
+import sys
+import textwrap
+from functools import partial
+
+# import Literal
+from typing import TYPE_CHECKING, Callable, Literal
+from urllib.parse import urlparse
+
+import click
+from requests.utils import NETRC_FILES, get_netrc_auth
+
+import wandb
+from wandb.apis import InternalApi
+from wandb.errors import term
+from wandb.errors.links import url_registry
+from wandb.sdk import wandb_setup
+from wandb.util import _is_databricks, isatty, prompt_choices
+
+if TYPE_CHECKING:
+ from wandb.sdk.wandb_settings import Settings
+
+LOGIN_CHOICE_ANON = "Private W&B dashboard, no account required"
+LOGIN_CHOICE_NEW = "Create a W&B account"
+LOGIN_CHOICE_EXISTS = "Use an existing W&B account"
+LOGIN_CHOICE_DRYRUN = "Don't visualize my results"
+LOGIN_CHOICE_NOTTY = "Unconfigured"
+LOGIN_CHOICES = [
+ LOGIN_CHOICE_ANON,
+ LOGIN_CHOICE_NEW,
+ LOGIN_CHOICE_EXISTS,
+ LOGIN_CHOICE_DRYRUN,
+]
+
+
+@dataclasses.dataclass(frozen=True)
+class _NetrcPermissions:
+ exists: bool
+ read_access: bool
+ write_access: bool
+
+
+class WriteNetrcError(Exception):
+ """Raised when we cannot write to the netrc file."""
+
+
+Mode = Literal["allow", "must", "never", "false", "true"]
+
+
+getpass = partial(click.prompt, hide_input=True, err=True)
+
+
+def _fixup_anon_mode(default: Mode | None) -> Mode | None:
+ # Convert weird anonymode values from legacy settings files
+ # into one of our expected values.
+ anon_mode = default or "never"
+ mapping: dict[Mode, Mode] = {"true": "allow", "false": "never"}
+ return mapping.get(anon_mode, anon_mode)
+
+
+def get_netrc_file_path() -> str:
+ """Return the path to the netrc file."""
+ # if the NETRC environment variable is set, use that
+ netrc_file = os.environ.get("NETRC")
+ if netrc_file:
+ return os.path.expanduser(netrc_file)
+
+ # if either .netrc or _netrc exists in the home directory, use that
+ for netrc_file in NETRC_FILES:
+ home_dir = os.path.expanduser("~")
+ if os.path.exists(os.path.join(home_dir, netrc_file)):
+ return os.path.join(home_dir, netrc_file)
+
+ # otherwise, use .netrc on non-Windows platforms and _netrc on Windows
+ netrc_file = ".netrc" if platform.system() != "Windows" else "_netrc"
+
+ return os.path.join(os.path.expanduser("~"), netrc_file)
+
+
+def _api_key_prompt_str(app_url: str, referrer: str | None = None) -> str:
+ """Generate a prompt string for API key authorization.
+
+ Creates a URL string that directs users to the authorization page where they
+ can find their API key.
+
+ Args:
+ app_url: The base URL of the W&B application.
+ referrer: Optional referrer parameter to include in the URL.
+
+ Returns:
+ A formatted string with instructions and the authorization URL.
+ """
+ ref = ""
+ if referrer:
+ ref = f"?ref={referrer}"
+ return f"You can find your API key in your browser here: {app_url}/authorize{ref}"
+
+
+def prompt_api_key( # noqa: C901
+ settings: Settings,
+ api: InternalApi | None = None,
+ input_callback: Callable | None = None,
+ browser_callback: Callable | None = None,
+ no_offline: bool = False,
+ no_create: bool = False,
+ local: bool = False,
+ referrer: str | None = None,
+) -> str | bool | None:
+ """Prompt for api key.
+
+ Returns:
+ str - if key is configured
+ None - if dryrun is selected
+ False - if unconfigured (notty)
+ """
+ input_callback = input_callback or getpass
+ log_string = term.LOG_STRING
+ api = api or InternalApi(settings)
+ anon_mode = _fixup_anon_mode(settings.anonymous) # type: ignore
+ jupyter = settings._jupyter or False
+ app_url = api.app_url
+
+ choices = [choice for choice in LOGIN_CHOICES]
+ if anon_mode == "never":
+ # Omit LOGIN_CHOICE_ANON as a choice if the env var is set to never
+ choices.remove(LOGIN_CHOICE_ANON)
+ if (jupyter and not settings.login_timeout) or no_offline:
+ choices.remove(LOGIN_CHOICE_DRYRUN)
+ if (jupyter and not settings.login_timeout) or no_create:
+ choices.remove(LOGIN_CHOICE_NEW)
+
+ if jupyter and "google.colab" in sys.modules:
+ log_string = term.LOG_STRING_NOCOLOR
+ key = wandb.jupyter.attempt_colab_login(app_url) # type: ignore
+ if key is not None:
+ return key # type: ignore
+
+ if anon_mode == "must":
+ result = LOGIN_CHOICE_ANON
+ # If we're not in an interactive environment, default to dry-run.
+ elif (
+ not jupyter and (not isatty(sys.stdout) or not isatty(sys.stdin))
+ ) or _is_databricks():
+ result = LOGIN_CHOICE_NOTTY
+ elif local:
+ result = LOGIN_CHOICE_EXISTS
+ elif len(choices) == 1:
+ result = choices[0]
+ else:
+ result = prompt_choices(
+ choices, input_timeout=settings.login_timeout, jupyter=jupyter
+ )
+
+ key = None
+ api_ask = (
+ f"{log_string}: Paste an API key from your profile and hit enter"
+ if jupyter
+ else f"{log_string}: Paste an API key from your profile and hit enter, or press ctrl+c to quit"
+ )
+ if result == LOGIN_CHOICE_ANON:
+ key = api.create_anonymous_api_key()
+ elif result == LOGIN_CHOICE_NEW:
+ key = browser_callback(signup=True) if browser_callback else None
+
+ if not key:
+ ref = f"&ref={referrer}" if referrer else ""
+ wandb.termlog(
+ f"Create an account here: {app_url}/authorize?signup=true{ref}"
+ )
+ key = input_callback(api_ask).strip()
+ elif result == LOGIN_CHOICE_EXISTS:
+ key = browser_callback() if browser_callback else None
+
+ if not key:
+ if not (settings.is_local or local):
+ host = app_url
+ for prefix in ("http://", "https://"):
+ if app_url.startswith(prefix):
+ host = app_url[len(prefix) :]
+ wandb.termlog(
+ f"Logging into {host}. (Learn how to deploy a W&B server "
+ f"locally: {url_registry.url('wandb-server')})"
+ )
+ wandb.termlog(_api_key_prompt_str(app_url, referrer))
+ key = input_callback(api_ask).strip()
+ elif result == LOGIN_CHOICE_NOTTY:
+ # TODO: Needs refactor as this needs to be handled by caller
+ return False
+ elif result == LOGIN_CHOICE_DRYRUN:
+ return None
+ else:
+ # Jupyter environments don't have a tty, but we can still try logging in using
+ # the browser callback if one is supplied.
+ key, anonymous = (
+ browser_callback() if jupyter and browser_callback else (None, False)
+ )
+
+ if not key:
+ raise ValueError("No API key specified.")
+ return key
+
+
+def check_netrc_access(
+ netrc_path: str,
+) -> _NetrcPermissions:
+ """Check if we can read and write to the netrc file."""
+ file_exists = False
+ write_access = False
+ read_access = False
+ try:
+ st = os.stat(netrc_path)
+ file_exists = True
+ write_access = bool(st.st_mode & stat.S_IWUSR)
+ read_access = bool(st.st_mode & stat.S_IRUSR)
+ except FileNotFoundError:
+ # If the netrc file doesn't exist, we will create it.
+ write_access = True
+ read_access = True
+ except OSError as e:
+ wandb.termerror(f"Unable to read permissions for {netrc_path}, {e}")
+
+ return _NetrcPermissions(
+ exists=file_exists,
+ write_access=write_access,
+ read_access=read_access,
+ )
+
+
+def write_netrc(host: str, entity: str, key: str):
+ """Add our host and key to .netrc."""
+ _, key_suffix = key.split("-", 1) if "-" in key else ("", key)
+ if len(key_suffix) != 40:
+ raise ValueError(
+ f"API-key must be exactly 40 characters long: {key_suffix} ({len(key_suffix)} chars)"
+ )
+
+ normalized_host = urlparse(host).netloc
+ netrc_path = get_netrc_file_path()
+ netrc_access = check_netrc_access(netrc_path)
+
+ if not netrc_access.write_access or not netrc_access.read_access:
+ raise WriteNetrcError(
+ f"Cannot access {netrc_path}. In order to persist your API key, "
+ "grant read and write permissions for your user to the file "
+ 'or specify a different file with the environment variable "NETRC=".'
+ )
+
+ machine_line = f"machine {normalized_host}"
+ orig_lines = None
+ try:
+ with open(netrc_path) as f:
+ orig_lines = f.read().strip().split("\n")
+ except FileNotFoundError:
+ wandb.termlog("No netrc file found, creating one.")
+ except OSError as e:
+ raise WriteNetrcError(f"Unable to read {netrc_path}") from e
+
+ try:
+ with open(netrc_path, "w") as f:
+ if orig_lines:
+ # delete this machine from the file if it's already there.
+ skip = 0
+ for line in orig_lines:
+ # we fix invalid netrc files with an empty host that we wrote before
+ # verifying host...
+ if line == "machine " or machine_line in line:
+ skip = 2
+ elif skip:
+ skip -= 1
+ else:
+ f.write(f"{line}\n")
+
+ wandb.termlog(
+ f"Appending key for {normalized_host} to your netrc file: {netrc_path}"
+ )
+ f.write(
+ textwrap.dedent(
+ """\
+ machine {host}
+ login {entity}
+ password {key}
+ """
+ ).format(host=normalized_host, entity=entity, key=key)
+ )
+ os.chmod(netrc_path, stat.S_IRUSR | stat.S_IWUSR)
+ except OSError as e:
+ raise WriteNetrcError(f"Unable to write {netrc_path}") from e
+
+
+def write_key(
+ settings: Settings,
+ key: str | None,
+ api: InternalApi | None = None,
+) -> None:
+ if not key:
+ raise ValueError("No API key specified.")
+
+ # TODO(jhr): api shouldn't be optional or it shouldn't be passed, clean up callers
+ api = api or InternalApi()
+
+ # Normal API keys are 40-character hex strings. On-prem API keys have a
+ # variable-length prefix, a dash, then the 40-char string.
+ _, suffix = key.split("-", 1) if "-" in key else ("", key)
+
+ if len(suffix) != 40:
+ raise ValueError(f"API key must be 40 characters long, yours was {len(key)}")
+
+ write_netrc(settings.base_url, "user", key)
+
+
+def api_key(settings: Settings | None = None) -> str | None:
+ if settings is None:
+ settings = wandb_setup.singleton().settings
+ if settings.api_key:
+ return settings.api_key
+
+ netrc_access = check_netrc_access(get_netrc_file_path())
+ if netrc_access.exists and not netrc_access.read_access:
+ wandb.termwarn(f"Cannot access {get_netrc_file_path()}.")
+ return None
+
+ if netrc_access.exists:
+ auth = get_netrc_auth(settings.base_url)
+ if auth:
+ return auth[-1]
+
+ return None
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/asyncio_compat.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/asyncio_compat.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb5a17dd10e25765078cba48ac39c52a4628de7d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/asyncio_compat.py
@@ -0,0 +1,278 @@
+"""Functions for compatibility with asyncio."""
+
+from __future__ import annotations
+
+import asyncio
+import concurrent
+import concurrent.futures
+import contextlib
+import threading
+from typing import Any, AsyncIterator, Callable, Coroutine, TypeVar
+
+_T = TypeVar("_T")
+
+
+def run(fn: Callable[[], Coroutine[Any, Any, _T]]) -> _T:
+ """Run `fn` in an asyncio loop in a new thread.
+
+ This must always be used instead of `asyncio.run` which fails if there is
+ an active `asyncio` event loop in the current thread. Since `wandb` was not
+ originally designed with `asyncio` in mind, using `asyncio.run` would break
+ users who were calling `wandb` methods from an `asyncio` loop.
+
+ Note that due to starting a new thread, this is slightly slow.
+ """
+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
+ runner = CancellableRunner()
+ future = executor.submit(runner.run, fn)
+
+ try:
+ return future.result()
+
+ finally:
+ runner.cancel()
+
+
+class RunnerCancelledError(Exception):
+ """The `CancellableRunner.run()` invocation was cancelled."""
+
+
+class CancellableRunner:
+ """Runs an asyncio event loop allowing cancellation.
+
+ The `run()` method is like `asyncio.run()`. The `cancel()` method may
+ be used in a different thread, for instance in a `finally` block, to cancel
+ all tasks, and it is a no-op if `run()` completed.
+
+ Without this, it is impossible to make `asyncio.run()` stop if it runs
+ in a non-main thread. In particular, a KeyboardInterrupt causes the
+ ThreadPoolExecutor above to block until the asyncio thread completes,
+ but there is no way to tell the asyncio thread to cancel its work.
+ A second KeyboardInterrupt makes ThreadPoolExecutor give up while the
+ asyncio thread still runs in the background, with terrible effects if it
+ prints to the user's terminal.
+ """
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+
+ self._is_cancelled = False
+ self._started = False
+ self._done = False
+
+ self._loop: asyncio.AbstractEventLoop | None = None
+ self._cancel_event: asyncio.Event | None = None
+
+ def run(self, fn: Callable[[], Coroutine[Any, Any, _T]]) -> _T:
+ """Run a coroutine in asyncio, cancelling it on `cancel()`.
+
+ Returns:
+ The result of the coroutine returned by `fn`.
+
+ Raises:
+ RunnerCancelledError: If `cancel()` is called.
+ """
+ return asyncio.run(self._run_or_cancel(fn))
+
+ async def _run_or_cancel(
+ self,
+ fn: Callable[[], Coroutine[Any, Any, _T]],
+ ) -> _T:
+ with self._lock:
+ if self._is_cancelled:
+ raise RunnerCancelledError()
+
+ self._loop = asyncio.get_running_loop()
+ self._cancel_event = asyncio.Event()
+ self._started = True
+
+ cancellation_task = asyncio.create_task(self._cancel_event.wait())
+ fn_task = asyncio.create_task(fn())
+
+ try:
+ await asyncio.wait(
+ [cancellation_task, fn_task],
+ return_when=asyncio.FIRST_COMPLETED,
+ )
+
+ if fn_task.done():
+ return fn_task.result()
+ else:
+ raise RunnerCancelledError()
+
+ finally:
+ # NOTE: asyncio.run() cancels all tasks after the main task exits,
+ # but this is not documented, so we cancel them explicitly here
+ # as well. It also blocks until canceled tasks complete.
+ cancellation_task.cancel()
+ fn_task.cancel()
+
+ with self._lock:
+ self._done = True
+
+ def cancel(self) -> None:
+ """Cancel all asyncio work started by `run()`."""
+ with self._lock:
+ if self._is_cancelled:
+ return
+ self._is_cancelled = True
+
+ if self._done or not self._started:
+ # If the runner already finished, no need to cancel it.
+ #
+ # If the runner hasn't started the loop yet, then it will not
+ # as we already set _is_cancelled.
+ return
+
+ assert self._loop
+ assert self._cancel_event
+ self._loop.call_soon_threadsafe(self._cancel_event.set)
+
+
+class TaskGroup:
+ """Object that `open_task_group()` yields."""
+
+ def __init__(self) -> None:
+ self._tasks: list[asyncio.Task] = []
+
+ def start_soon(self, coro: Coroutine[Any, Any, Any]) -> None:
+ """Schedule a task in the group.
+
+ Args:
+ coro: The return value of the `async` function defining the task.
+ """
+ self._tasks.append(asyncio.create_task(coro))
+
+ async def _wait_all(self, *, race: bool, timeout: float | None) -> None:
+ """Block until tasks complete.
+
+ Args:
+ race: If true, blocks until the first task completes and then
+ cancels the rest. Otherwise, waits for all tasks or until
+ the first exception.
+ timeout: How long to wait.
+
+ Raises:
+ TimeoutError: If the timeout expires.
+ Exception: If one or more tasks raises an exception, one of these
+ is raised arbitrarily.
+ """
+ if not self._tasks:
+ return
+
+ if race:
+ return_when = asyncio.FIRST_COMPLETED
+ else:
+ return_when = asyncio.FIRST_EXCEPTION
+
+ done, pending = await asyncio.wait(
+ self._tasks,
+ timeout=timeout,
+ return_when=return_when,
+ )
+
+ if not done:
+ raise TimeoutError(f"Timed out after {timeout} seconds.")
+
+ # If any of the finished tasks raised an exception, pick the first one.
+ for task in done:
+ if exc := task.exception():
+ raise exc
+
+ # Wait for remaining tasks to clean up, then re-raise any exceptions
+ # that arise. Note that pending is only non-empty when race=True.
+ for task in pending:
+ task.cancel()
+ await asyncio.gather(*pending, return_exceptions=True)
+ for task in pending:
+ if task.cancelled():
+ continue
+ if exc := task.exception():
+ raise exc
+
+ async def _cancel_all(self) -> None:
+ """Cancel all tasks.
+
+ Blocks until cancelled tasks complete to allow them to clean up.
+ Ignores exceptions.
+ """
+ for task in self._tasks:
+ # NOTE: It is safe to cancel tasks that have already completed.
+ task.cancel()
+ await asyncio.gather(*self._tasks, return_exceptions=True)
+
+
+@contextlib.asynccontextmanager
+async def open_task_group(
+ *,
+ exit_timeout: float | None = None,
+ race: bool = False,
+) -> AsyncIterator[TaskGroup]:
+ """Create a task group.
+
+ `asyncio` gained task groups in Python 3.11.
+
+ This is an async context manager, meant to be used with `async with`.
+ On exit, it blocks until all subtasks complete. If any subtask fails, or if
+ the current task is cancelled, it cancels all subtasks in the group and
+ raises the subtask's exception. If multiple subtasks fail simultaneously,
+ one of their exceptions is chosen arbitrarily.
+
+ NOTE: Subtask exceptions do not propagate until the context manager exits.
+ This means that the task group cannot cancel code running inside the
+ `async with` block .
+
+ Args:
+ exit_timeout: An optional timeout in seconds. When exiting the
+ context manager, if tasks don't complete in this time,
+ they are cancelled and a TimeoutError is raised.
+ race: If true, all pending tasks are cancelled once any task
+ in the group completes. Prefer to use the race() function instead.
+
+ Raises:
+ TimeoutError: if exit_timeout is specified and tasks don't finish
+ in time.
+ """
+ task_group = TaskGroup()
+
+ try:
+ yield task_group
+ await task_group._wait_all(race=race, timeout=exit_timeout)
+ finally:
+ await task_group._cancel_all()
+
+
+@contextlib.asynccontextmanager
+async def cancel_on_exit(coro: Coroutine[Any, Any, Any]) -> AsyncIterator[None]:
+ """Schedule a task, cancelling it when exiting the context manager.
+
+ If the context manager exits successfully but the given coroutine raises
+ an exception, that exception is reraised. The exception is suppressed
+ if the context manager raises an exception.
+ """
+
+ async def stop_immediately():
+ pass
+
+ async with open_task_group(race=True) as group:
+ group.start_soon(stop_immediately())
+ group.start_soon(coro)
+ yield
+
+
+async def race(*coros: Coroutine[Any, Any, Any]) -> None:
+ """Wait until the first completed task.
+
+ After any coroutine completes, all others are cancelled.
+ If the current task is cancelled, all coroutines are cancelled too.
+
+ If coroutines complete simultaneously and any one of them raises
+ an exception, an arbitrary one is propagated. Similarly, if any coroutines
+ raise exceptions during cancellation, one of them propagates.
+
+ Args:
+ coros: Coroutines to race.
+ """
+ async with open_task_group(race=True) as tg:
+ for coro in coros:
+ tg.start_soon(coro)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/asyncio_manager.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/asyncio_manager.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9126f38f6e82905e29bc182978787f1826d7457
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/asyncio_manager.py
@@ -0,0 +1,252 @@
+"""Implements an asyncio thread suitable for internal wandb use."""
+
+from __future__ import annotations
+
+import asyncio
+import concurrent.futures
+import contextlib
+import logging
+import threading
+from typing import Any, Callable, Coroutine, TypeVar
+
+from . import asyncio_compat
+
+_T = TypeVar("_T")
+
+_logger = logging.getLogger(__name__)
+
+
+class RunCancelledError(Exception):
+ """A function passed to AsyncioManager.run() was cancelled."""
+
+
+class AlreadyJoinedError(Exception):
+ """AsyncioManager.run() used after join()."""
+
+
+class AsyncioManager:
+ """Manages a thread running an asyncio loop.
+
+ The thread must be started using start() and should be joined using
+ join(). The thread is a daemon thread, so if join() is not invoked,
+ the asyncio work could end abruptly when all non-daemon threads exit.
+
+ The run() method allows invoking an async function in the asyncio thread
+ and waiting until it completes. The run_soon() method allows running
+ an async function without waiting for it.
+
+ Note that although tempting, it is **not** possible to write a safe
+ run_in_loop() method that chooses whether to use run() or execute a function
+ directly based on whether it's called from the asyncio thread: Suppose a
+ function bad() holds a threading.Lock while using run_in_loop() and an
+ asyncio task calling bad() is scheduled. If bad() is then invoked in a
+ different thread that reaches run_in_loop(), the aforementioned asyncio task
+ will deadlock. It is unreasonable to require that run_in_loop() never be
+ called while holding a lock (which would apply to the callers of its
+ callers, and so on), so it cannot safely exist.
+ """
+
+ def __init__(self) -> None:
+ self._runner = asyncio_compat.CancellableRunner()
+ self._thread = threading.Thread(
+ target=self._main,
+ name="wandb-AsyncioManager-main",
+ daemon=True,
+ )
+ self._lock = threading.Lock()
+
+ self._ready_event = threading.Event()
+ """Whether asyncio primitives have been initialized."""
+
+ self._joined = False
+ """Whether join() has been called. Guarded by _lock."""
+
+ self._loop: asyncio.AbstractEventLoop
+ """A handle for interacting with the asyncio event loop."""
+
+ self._done_event: asyncio.Event
+ """Indicates to the asyncio loop that join() was called."""
+
+ self._remaining_tasks = 0
+ """The number of tasks remaining. Guarded by _lock."""
+
+ self._task_finished_cond: asyncio.Condition
+ """Signalled when _remaining_tasks is decremented."""
+
+ def start(self) -> None:
+ """Start the asyncio thread."""
+ self._thread.start()
+
+ def join(self) -> None:
+ """Stop accepting new asyncio tasks and wait for the remaining ones."""
+ try:
+ with self._lock:
+ # If join() was already called, block until the thread completes
+ # and then return.
+ if self._joined:
+ self._thread.join()
+ return
+
+ self._joined = True
+
+ # Wait until _loop and _done_event are initialized.
+ self._ready_event.wait()
+
+ # Set the done event. The main function will exit once all
+ # tasks complete.
+ self._loop.call_soon_threadsafe(self._done_event.set)
+
+ self._thread.join()
+
+ finally:
+ # Any of the above may get interrupted by Ctrl+C, in which case we
+ # should cancel all tasks, since join() can only be called once.
+ # This only matters if the KeyboardInterrupt is suppressed.
+ self._runner.cancel()
+
+ def run(self, fn: Callable[[], Coroutine[Any, Any, _T]]) -> _T:
+ """Run an async function to completion.
+
+ The function is called in the asyncio thread. Blocks until start()
+ is called. This raises an error if called inside an async function,
+ and as a consequence, the caller may also not be called inside an
+ async function.
+
+ Args:
+ fn: The function to run.
+
+ Returns:
+ The return value of fn.
+
+ Raises:
+ Exception: Any exception raised by fn.
+ RunCancelledError: If fn is cancelled, particularly when join()
+ is interrupted by Ctrl+C or if it otherwise cancels itself.
+ AlreadyJoinedError: If join() was already called.
+ ValueError: If called inside an async function.
+ """
+ self._ready_event.wait()
+
+ if threading.current_thread().ident == self._thread.ident:
+ raise ValueError("Cannot use run() inside async loop.")
+
+ future = self._schedule(fn, daemon=False)
+
+ try:
+ return future.result()
+
+ except concurrent.futures.CancelledError:
+ raise RunCancelledError from None
+
+ except KeyboardInterrupt:
+ # If we're interrupted here, we only cancel this task rather than
+ # cancelling all tasks like in join(). This only matters if the
+ # interrupt is then suppressed (or delayed) in which case we
+ # should let other tasks progress.
+ future.cancel()
+ raise
+
+ def run_soon(
+ self,
+ fn: Callable[[], Coroutine[Any, Any, None]],
+ *,
+ daemon: bool = False,
+ name: str | None = None,
+ ) -> None:
+ """Run an async function without waiting for it to complete.
+
+ The function is called in the asyncio thread. Note that since that's
+ a daemon thread, it will not get joined when the main thread exits,
+ so fn can stop abruptly.
+
+ Unlike run(), it is OK to call this inside an async function.
+
+ Blocks until start() is called.
+
+ Args:
+ fn: The function to run.
+ daemon: If true, join() will cancel fn after all non-daemon
+ tasks complete. By default, join() blocks until fn
+ completes.
+ name: An optional name to give to long-running tasks which can
+ appear in error traces and be useful to debugging.
+
+ Raises:
+ AlreadyJoinedError: If join() was already called.
+ """
+
+ # Wrap exceptions so that they're not printed to console.
+ async def fn_wrap_exceptions() -> None:
+ try:
+ await fn()
+ except Exception:
+ _logger.exception("Uncaught exception in run_soon callback.")
+
+ _ = self._schedule(fn_wrap_exceptions, daemon=daemon, name=name)
+
+ def _schedule(
+ self,
+ fn: Callable[[], Coroutine[Any, Any, _T]],
+ daemon: bool,
+ name: str | None = None,
+ ) -> concurrent.futures.Future[_T]:
+ # Wait for _loop to be initialized.
+ self._ready_event.wait()
+
+ with self._lock:
+ if self._joined:
+ raise AlreadyJoinedError
+
+ if not daemon:
+ self._remaining_tasks += 1
+
+ return asyncio.run_coroutine_threadsafe(
+ self._wrap(fn, daemon=daemon, name=name),
+ self._loop,
+ )
+
+ async def _wrap(
+ self,
+ fn: Callable[[], Coroutine[Any, Any, _T]],
+ daemon: bool,
+ name: str | None,
+ ) -> _T:
+ """Run fn to completion and possibly decrement _remaining tasks."""
+ try:
+ if name and (task := asyncio.current_task()):
+ task.set_name(name)
+
+ return await fn()
+ finally:
+ if not daemon:
+ async with self._task_finished_cond:
+ with self._lock:
+ self._remaining_tasks -= 1
+ self._task_finished_cond.notify_all()
+
+ def _main(self) -> None:
+ """Run the asyncio loop until join() is called and all tasks finish."""
+ # A cancellation error is expected if join() is interrupted.
+ #
+ # Were it not suppressed, its stacktrace would get printed.
+ with contextlib.suppress(asyncio_compat.RunnerCancelledError):
+ self._runner.run(self._main_async)
+
+ async def _main_async(self) -> None:
+ """Wait until join() is called and all tasks finish."""
+ self._loop = asyncio.get_running_loop()
+ self._done_event = asyncio.Event()
+ self._task_finished_cond = asyncio.Condition()
+
+ self._ready_event.set()
+
+ # Wait until done.
+ await self._done_event.wait()
+
+ # Wait for all tasks to complete.
+ #
+ # Once we exit, asyncio will cancel any leftover tasks.
+ async with self._task_finished_cond:
+ await self._task_finished_cond.wait_for(
+ lambda: self._remaining_tasks <= 0,
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/capped_dict.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/capped_dict.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e162109926cf7c115bf835323de4d292f8725e8
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/capped_dict.py
@@ -0,0 +1,26 @@
+import collections
+from typing import Any, Optional
+
+
+class CappedDict(collections.OrderedDict):
+ default_max_size = 50
+
+ def __init__(self, max_size: Optional[int] = None) -> None:
+ self.max_size = max_size or self.default_max_size
+ super().__init__()
+
+ def __setitem__(self, key: str, val: Any) -> None:
+ if key not in self:
+ max_size = self.max_size - 1
+ self._prune_dict(max_size)
+ super().__setitem__(key, val)
+
+ def update(self, **kwargs: Any) -> None: # type: ignore[override]
+ super().update(**kwargs)
+ self._prune_dict(self.max_size)
+
+ def _prune_dict(self, max_size: int) -> None:
+ if len(self) >= max_size:
+ diff = len(self) - max_size
+ for k in list(self.keys())[:diff]:
+ del self[k]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/config_util.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/config_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c20f844174374d09d1eec1711d4f9eea392c8e0
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/config_util.py
@@ -0,0 +1,101 @@
+import json
+import logging
+import os
+from typing import Any, Dict, Optional
+
+import yaml
+
+import wandb
+from wandb.errors import Error
+from wandb.util import load_yaml
+
+from . import filesystem
+
+logger = logging.getLogger("wandb")
+
+
+class ConfigError(Error):
+ pass
+
+
+def dict_from_proto_list(obj_list):
+ d = dict()
+ for item in obj_list:
+ d[item.key] = dict(desc=None, value=json.loads(item.value_json))
+ return d
+
+
+def dict_strip_value_dict(config_dict):
+ d = dict()
+ for k, v in config_dict.items():
+ d[k] = v["value"]
+ return d
+
+
+def dict_no_value_from_proto_list(obj_list):
+ d = dict()
+ for item in obj_list:
+ possible_dict = json.loads(item.value_json)
+ if not isinstance(possible_dict, dict) or "value" not in possible_dict:
+ continue
+ d[item.key] = possible_dict["value"]
+
+ return d
+
+
+# TODO(jhr): these functions should go away once we merge jobspec PR
+def save_config_file_from_dict(config_filename, config_dict):
+ s = b"wandb_version: 1"
+ if config_dict: # adding an empty dictionary here causes a parse error
+ s += b"\n\n" + yaml.dump(
+ config_dict,
+ Dumper=yaml.SafeDumper,
+ default_flow_style=False,
+ allow_unicode=True,
+ encoding="utf-8",
+ sort_keys=False,
+ )
+ data = s.decode("utf-8")
+ filesystem.mkdir_exists_ok(os.path.dirname(config_filename))
+ with open(config_filename, "w") as conf_file:
+ conf_file.write(data)
+
+
+def dict_from_config_file(
+ filename: str, must_exist: bool = False
+) -> Optional[Dict[str, Any]]:
+ if not os.path.exists(filename):
+ if must_exist:
+ raise ConfigError(f"config file {filename} doesn't exist")
+ logger.debug(f"no default config file found in {filename}")
+ return None
+ try:
+ conf_file = open(filename)
+ except OSError:
+ raise ConfigError(f"Couldn't read config file: {filename}")
+ try:
+ loaded = load_yaml(conf_file)
+ except yaml.parser.ParserError:
+ raise ConfigError("Invalid YAML in config yaml")
+ if loaded is None:
+ wandb.termwarn(
+ "Found an empty default config file (config-defaults.yaml). Proceeding with no defaults."
+ )
+ return None
+ config_version = loaded.pop("wandb_version", None)
+ if config_version is not None and config_version != 1:
+ raise ConfigError("Unknown config version")
+ data = dict()
+ for k, v in loaded.items():
+ data[k] = v["value"]
+ return data
+
+
+def merge_dicts(dest: dict, src: dict) -> dict:
+ """Recursively merge two dictionaries. Similar to Lodash's _.merge()."""
+ for key, value in src.items():
+ if isinstance(value, dict) and key in dest and isinstance(dest[key], dict):
+ merge_dicts(dest[key], value)
+ else:
+ dest[key] = value
+ return dest
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/console_capture.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/console_capture.py
new file mode 100644
index 0000000000000000000000000000000000000000..f9d56af0d74f518969de5a8c62811b30d49e36b6
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/console_capture.py
@@ -0,0 +1,219 @@
+"""Module for intercepting stdout/stderr.
+
+This patches the `write()` method of `stdout` and `stderr` on import.
+Once patched, it is not possible to unpatch or repatch, though individual
+callbacks can be removed.
+
+We assume that all other writing methods on the object delegate to `write()`,
+like `writelines()`. This is not guaranteed to be true, but it is true for
+common implementations. In particular, CPython's implementation of IOBase's
+`writelines()` delegates to `write()`.
+
+It is important to note that this technique interacts poorly with other
+code that performs similar patching if it also allows unpatching as this
+discards our modification. This is why we patch on import and do not support
+unpatching:
+
+ with contextlib.redirect_stderr(...):
+ from ... import console_capture
+ # Here, everything works fine.
+ # Here, callbacks are never called again.
+
+In particular, it does not work with some combinations of pytest's
+`capfd` / `capsys` fixtures and pytest's `--capture` option.
+"""
+
+from __future__ import annotations
+
+import logging
+import sys
+import threading
+from typing import IO, AnyStr, Callable, Protocol
+
+from . import wb_logging
+
+_logger = logging.getLogger(__name__)
+
+
+class CannotCaptureConsoleError(Exception):
+ """The module failed to patch stdout or stderr."""
+
+
+class _WriteCallback(Protocol):
+ """A callback that receives intercepted bytes or string data.
+
+ This may be called from any thread, but is only called from one thread
+ at a time.
+
+ Note on errors: Any error raised during the callback will clear all
+ callbacks. This means that if a user presses Ctrl-C at an unlucky time
+ during a run, we will stop uploading console output---but it's not
+ likely to be a problem unless something catches the KeyboardInterrupt.
+
+ Regular Exceptions are caught and logged instead of bubbling up to the
+ user's print() statements; other exceptions like KeyboardInterrupt are
+ re-raised.
+
+ Callbacks should handle all exceptions---a callback that raises any
+ Exception is considered buggy.
+ """
+
+ def __call__(
+ self,
+ data: bytes | str,
+ written: int,
+ /,
+ ) -> None:
+ """Intercept data passed to `write()`.
+
+ See the protocol docstring for information about exceptions.
+
+ Args:
+ data: The object passed to stderr's or stdout's `write()`.
+ written: The number of bytes or characters written.
+ This is the return value of `write()`.
+ """
+
+
+# A reentrant lock is used to catch callbacks that write to stderr/stdout.
+_module_rlock = threading.RLock()
+_is_writing = False
+
+_patch_exception: CannotCaptureConsoleError | None = None
+
+_next_callback_id: int = 1
+
+_stdout_callbacks: dict[int, _WriteCallback] = {}
+_stderr_callbacks: dict[int, _WriteCallback] = {}
+
+
+def capture_stdout(callback: _WriteCallback) -> Callable[[], None]:
+ """Install a callback that runs after every write to sys.stdout.
+
+ Args:
+ callback: A callback to invoke after running `sys.stdout.write`.
+
+ Returns:
+ A function to uninstall the callback.
+
+ Raises:
+ CannotCaptureConsoleError: If patching failed on import.
+ """
+ with _module_rlock:
+ if _patch_exception:
+ raise _patch_exception
+
+ return _insert_disposably(
+ _stdout_callbacks,
+ callback,
+ )
+
+
+def capture_stderr(callback: _WriteCallback) -> Callable[[], None]:
+ """Install a callback that runs after every write to sys.sdterr.
+
+ Args:
+ callback: A callback to invoke after running `sys.stderr.write`.
+
+ Returns:
+ A function to uninstall the callback.
+
+ Raises:
+ CannotCaptureConsoleError: If patching failed on import.
+ """
+ with _module_rlock:
+ if _patch_exception:
+ raise _patch_exception
+
+ return _insert_disposably(
+ _stderr_callbacks,
+ callback,
+ )
+
+
+def _insert_disposably(
+ callback_dict: dict[int, _WriteCallback],
+ callback: _WriteCallback,
+) -> Callable[[], None]:
+ global _next_callback_id
+ id = _next_callback_id
+ _next_callback_id += 1
+
+ disposed = False
+
+ def dispose() -> None:
+ nonlocal disposed
+
+ with _module_rlock:
+ if disposed:
+ return
+
+ callback_dict.pop(id, None)
+
+ disposed = True
+
+ callback_dict[id] = callback
+ return dispose
+
+
+def _patch(
+ stdout_or_stderr: IO[AnyStr],
+ callbacks: dict[int, _WriteCallback],
+) -> None:
+ orig_write: Callable[[AnyStr], int]
+
+ @wb_logging.log_to_all_runs()
+ def write_with_callbacks(s: AnyStr, /) -> int:
+ global _is_writing
+ n = orig_write(s)
+
+ # NOTE: Since _module_rlock is reentrant, this is safe. It will not
+ # deadlock if a callback invokes write() again.
+ with _module_rlock:
+ if _is_writing:
+ return n
+
+ _is_writing = True
+ try:
+ for cb in callbacks.values():
+ cb(s, n)
+
+ except BaseException as e:
+ # Clear all callbacks on any exception to avoid infinite loops:
+ #
+ # * If we re-raise, an exception handler is likely to print
+ # the exception to the console and trigger callbacks again
+ # * If we log, we can't guarantee that this doesn't print
+ # to console.
+ #
+ # This is especially important for KeyboardInterrupt.
+ _stderr_callbacks.clear()
+ _stdout_callbacks.clear()
+
+ if isinstance(e, Exception):
+ # We suppress Exceptions so that bugs in W&B code don't
+ # cause the user's print() statements to raise errors.
+ _logger.exception("Error in console callback, clearing all!")
+ else:
+ # Re-raise errors like KeyboardInterrupt.
+ raise
+
+ finally:
+ _is_writing = False
+
+ return n
+
+ orig_write = stdout_or_stderr.write
+
+ # mypy==1.14.1 fails to type-check this:
+ # Incompatible types in assignment (expression has type
+ # "Callable[[bytes], int]", variable has type overloaded function)
+ stdout_or_stderr.write = write_with_callbacks # type: ignore
+
+
+try:
+ _patch(sys.stdout, _stdout_callbacks)
+ _patch(sys.stderr, _stderr_callbacks)
+except Exception as _patch_exception_cause:
+ _patch_exception = CannotCaptureConsoleError()
+ _patch_exception.__cause__ = _patch_exception_cause
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/credentials.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/credentials.py
new file mode 100644
index 0000000000000000000000000000000000000000..422cf0efe6e219c9edd38f8edd7a8d23b9c89d9d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/credentials.py
@@ -0,0 +1,141 @@
+import json
+import os
+from datetime import datetime, timedelta
+from pathlib import Path
+
+import requests.utils
+
+from wandb.errors import AuthenticationError
+
+DEFAULT_WANDB_CREDENTIALS_FILE = Path(
+ os.path.expanduser("~/.config/wandb/credentials.json")
+)
+
+_expires_at_fmt = "%Y-%m-%d %H:%M:%S"
+
+
+def access_token(base_url: str, token_file: Path, credentials_file: Path) -> str:
+ """Retrieve an access token from the credentials file.
+
+ If no access token exists, create a new one by exchanging the identity
+ token from the token file, and save it to the credentials file.
+
+ Args:
+ base_url (str): The base URL of the server
+ token_file (pathlib.Path): The path to the file containing the
+ identity token
+ credentials_file (pathlib.Path): The path to file used to save
+ temporary access tokens
+
+ Returns:
+ str: The access token
+ """
+ if not credentials_file.exists():
+ _write_credentials_file(base_url, token_file, credentials_file)
+
+ data = _fetch_credentials(base_url, token_file, credentials_file)
+ return data["access_token"]
+
+
+def _write_credentials_file(base_url: str, token_file: Path, credentials_file: Path):
+ """Obtain an access token from the server and write it to the credentials file.
+
+ Args:
+ base_url (str): The base URL of the server
+ token_file (pathlib.Path): The path to the file containing the
+ identity token
+ credentials_file (pathlib.Path): The path to file used to save
+ temporary access tokens
+ """
+ credentials = _create_access_token(base_url, token_file)
+ data = {"credentials": {base_url: credentials}}
+ with open(credentials_file, "w") as file:
+ json.dump(data, file, indent=4)
+
+ # Set file permissions to be read/write by the owner only
+ os.chmod(credentials_file, 0o600)
+
+
+def _fetch_credentials(base_url: str, token_file: Path, credentials_file: Path) -> dict:
+ """Fetch the access token from the credentials file.
+
+ If the access token has expired, fetch a new one from the server and save it
+ to the credentials file.
+
+ Args:
+ base_url (str): The base URL of the server
+ token_file (pathlib.Path): The path to the file containing the
+ identity token
+ credentials_file (pathlib.Path): The path to file used to save
+ temporary access tokens
+
+ Returns:
+ dict: The credentials including the access token.
+ """
+ creds = {}
+ with open(credentials_file) as file:
+ data = json.load(file)
+ if "credentials" not in data:
+ data["credentials"] = {}
+ if base_url in data["credentials"]:
+ creds = data["credentials"][base_url]
+
+ expires_at = datetime.utcnow()
+ if "expires_at" in creds:
+ expires_at = datetime.strptime(creds["expires_at"], _expires_at_fmt)
+
+ if expires_at <= datetime.utcnow():
+ creds = _create_access_token(base_url, token_file)
+ with open(credentials_file, "w") as file:
+ data["credentials"][base_url] = creds
+ json.dump(data, file, indent=4)
+
+ return creds
+
+
+def _create_access_token(base_url: str, token_file: Path) -> dict:
+ """Exchange an identity token for an access token from the server.
+
+ Args:
+ base_url (str): The base URL of the server.
+ token_file (pathlib.Path): The path to the file containing the
+ identity token
+
+ Returns:
+ dict: The access token and its expiration.
+
+ Raises:
+ FileNotFoundError: If the token file is not found.
+ OSError: If there is an issue reading the token file.
+ AuthenticationError: If the server fails to provide an access token.
+ """
+ try:
+ with open(token_file) as file:
+ token = file.read().strip()
+ except FileNotFoundError as e:
+ raise FileNotFoundError(f"Identity token file not found: {token_file}") from e
+ except OSError as e:
+ raise OSError(
+ f"Failed to read the identity token from file: {token_file}"
+ ) from e
+
+ url = f"{base_url}/oidc/token"
+ data = {
+ "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
+ "assertion": token,
+ }
+ headers = {"Content-Type": "application/x-www-form-urlencoded"}
+
+ response = requests.post(url, data=data, headers=headers)
+
+ if response.status_code != 200:
+ raise AuthenticationError(
+ f"Failed to retrieve access token: {response.status_code}, {response.text}"
+ )
+
+ resp_json = response.json()
+ expires_at = datetime.utcnow() + timedelta(seconds=float(resp_json["expires_in"]))
+ resp_json["expires_at"] = expires_at.strftime(_expires_at_fmt)
+ del resp_json["expires_in"]
+
+ return resp_json
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/deprecate.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/deprecate.py
new file mode 100644
index 0000000000000000000000000000000000000000..29eb633ce036717d1e566752779e93bf6bcb6623
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/deprecate.py
@@ -0,0 +1,27 @@
+from __future__ import annotations
+
+import wandb
+from wandb.proto.wandb_deprecated import DEPRECATED_FEATURES
+from wandb.sdk.lib import telemetry
+
+
+def deprecate(
+ field_name: DEPRECATED_FEATURES,
+ warning_message: str,
+ run: wandb.Run | None = None,
+) -> None:
+ """Warn the user that a feature has been deprecated.
+
+ If a run is provided, the given field on its telemetry is updated.
+ Otherwise, the global run is used.
+
+ Args:
+ field_name: The field on the Deprecated proto for this deprecation.
+ warning_message: The message to display to the user.
+ run: The run whose telemetry to update.
+ """
+ _run = run or wandb.run
+ with telemetry.context(run=_run) as tel:
+ setattr(tel.deprecated, field_name, True)
+
+ wandb.termwarn(warning_message, repeat=False)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/disabled.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/disabled.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c2a9b2f49b9a77c903ab742125cd69b9aac4cf9
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/disabled.py
@@ -0,0 +1,30 @@
+from typing import Any
+
+from wandb.proto.wandb_deprecated import Deprecated
+from wandb.sdk.lib import deprecate
+
+
+class SummaryDisabled(dict):
+ __setattr__ = dict.__setitem__
+ __delattr__ = dict.__delitem__
+
+ def __getattr__(self, key):
+ return self[key]
+
+ def __getitem__(self, key):
+ val = dict.__getitem__(self, key)
+ if isinstance(val, dict) and not isinstance(val, SummaryDisabled):
+ val = SummaryDisabled(val)
+ self[key] = val
+ return val
+
+
+class RunDisabled:
+ """Compatibility class for integrations that explicitly check for wandb.RunDisabled."""
+
+ def __getattr__(self, name: str) -> Any:
+ deprecate.deprecate(
+ field_name=Deprecated.run_disabled,
+ warning_message="RunDisabled is deprecated and is a no-op. "
+ '`wandb.init(mode="disabled")` now returns an instance of `wandb.Run`.',
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/exit_hooks.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/exit_hooks.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa747495299a646041f7deaeb72c1a9bcc050660
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/exit_hooks.py
@@ -0,0 +1,54 @@
+import sys
+import traceback
+from types import TracebackType
+from typing import TYPE_CHECKING, Optional, Type
+
+import wandb
+from wandb.errors import Error
+
+if TYPE_CHECKING:
+ from typing import NoReturn
+
+
+class ExitHooks:
+ exception: Optional[BaseException] = None
+
+ def __init__(self) -> None:
+ self.exit_code = 0
+ self.exception = None
+
+ def hook(self) -> None:
+ self._orig_exit = sys.exit
+ sys.exit = self.exit
+ self._orig_excepthook = (
+ sys.excepthook
+ if sys.excepthook
+ != sys.__excepthook__ # respect hooks by other libraries like pdb
+ else None
+ )
+ sys.excepthook = self.exc_handler # type: ignore
+
+ def exit(self, code: object = 0) -> "NoReturn":
+ orig_code = code
+ code = code if code is not None else 0
+ code = code if isinstance(code, int) else 1
+ self.exit_code = code
+ self._orig_exit(orig_code) # type: ignore
+
+ def was_ctrl_c(self) -> bool:
+ return isinstance(self.exception, KeyboardInterrupt)
+
+ def exc_handler(
+ self, exc_type: Type[BaseException], exc: BaseException, tb: TracebackType
+ ) -> None:
+ self.exit_code = 1
+ self.exception = exc
+ if issubclass(exc_type, Error):
+ wandb.termerror(str(exc), repeat=False)
+
+ if self.was_ctrl_c():
+ self.exit_code = 255
+
+ traceback.print_exception(exc_type, exc, tb)
+ if self._orig_excepthook:
+ self._orig_excepthook(exc_type, exc, tb)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/file_stream_utils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/file_stream_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7420b99706f8cd413da35b50ab76c1bd1e8fce6
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/file_stream_utils.py
@@ -0,0 +1,118 @@
+#
+from typing import Any, Dict, Iterable
+
+
+def split_files(
+ files: Dict[str, Any], max_bytes: int = 10 * 1024 * 1024
+) -> Iterable[Dict[str, Dict]]:
+ """Split a file's dict (see `files` arg) into smaller dicts.
+
+ Each smaller dict will have at most `MAX_BYTES` size.
+
+ This method is used in `FileStreamAPI._send()` to limit the size of post requests
+ sent to wandb server.
+
+ Args:
+ files (dict): `dict` of form {file_name: {'content': ".....", 'offset': 0}}
+ The key `file_name` can also be mapped to a List [{"offset": int, "content": str}]
+ `max_bytes`: max size for chunk in bytes
+ """
+ current_volume: Dict[str, Dict] = {}
+ current_size = 0
+
+ def _str_size(x):
+ return len(x) if isinstance(x, bytes) else len(x.encode("utf-8"))
+
+ def _file_size(file):
+ size = file.get("_size")
+ if size is None:
+ size = sum(map(_str_size, file["content"]))
+ file["_size"] = size
+ return size
+
+ def _split_file(file, num_lines):
+ offset = file["offset"]
+ content = file["content"]
+ name = file["name"]
+ f1 = {"offset": offset, "content": content[:num_lines], "name": name}
+ f2 = {
+ "offset": offset + num_lines,
+ "content": content[num_lines:],
+ "name": name,
+ }
+ return f1, f2
+
+ def _num_lines_from_num_bytes(file, num_bytes):
+ size = 0
+ num_lines = 0
+ content = file["content"]
+ while num_lines < len(content):
+ size += _str_size(content[num_lines])
+ if size > num_bytes:
+ break
+ num_lines += 1
+ return num_lines
+
+ files_stack = []
+ for k, v in files.items():
+ if isinstance(v, list):
+ for item in v:
+ files_stack.append(
+ {"name": k, "offset": item["offset"], "content": item["content"]}
+ )
+ else:
+ files_stack.append(
+ {"name": k, "offset": v["offset"], "content": v["content"]}
+ )
+
+ while files_stack:
+ f = files_stack.pop()
+ if f["name"] in current_volume:
+ files_stack.append(f)
+ yield current_volume
+ current_volume = {}
+ current_size = 0
+ continue
+ # For each file, we have to do 1 of 4 things:
+ # - Add the file as such to the current volume if possible.
+ # - Split the file and add the first part to the current volume and push the second part back onto the stack.
+ # - If that's not possible, check if current volume is empty:
+ # - If empty, add first line of file to current volume and push rest onto stack (This volume will exceed MAX_MB).
+ # - If not, push file back to stack and yield current volume.
+ fsize = _file_size(f)
+ rem = max_bytes - current_size
+ if fsize <= rem:
+ current_volume[f["name"]] = {
+ "offset": f["offset"],
+ "content": f["content"],
+ }
+ current_size += fsize
+ else:
+ num_lines = _num_lines_from_num_bytes(f, rem)
+ if not num_lines and not current_volume:
+ num_lines = 1
+ if num_lines:
+ f1, f2 = _split_file(f, num_lines)
+ current_volume[f1["name"]] = {
+ "offset": f1["offset"],
+ "content": f1["content"],
+ }
+ files_stack.append(f2)
+ yield current_volume
+ current_volume = {}
+ current_size = 0
+ continue
+ else:
+ files_stack.append(f)
+ yield current_volume
+ current_volume = {}
+ current_size = 0
+ continue
+ if current_size >= max_bytes:
+ yield current_volume
+ current_volume = {}
+ current_size = 0
+ continue
+
+ if current_volume:
+ yield current_volume
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/filenames.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/filenames.py
new file mode 100644
index 0000000000000000000000000000000000000000..c272b7a2c3337ddb6d91ce03ed800e84affcc5ff
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/filenames.py
@@ -0,0 +1,64 @@
+import os
+from typing import Callable, Generator, Union
+
+WANDB_DIRS = ("wandb", ".wandb")
+
+CONFIG_FNAME = "config.yaml"
+OUTPUT_FNAME = "output.log"
+DIFF_FNAME = "diff.patch"
+SUMMARY_FNAME = "wandb-summary.json"
+METADATA_FNAME = "wandb-metadata.json"
+REQUIREMENTS_FNAME = "requirements.txt"
+HISTORY_FNAME = "wandb-history.jsonl"
+EVENTS_FNAME = "wandb-events.jsonl"
+JOBSPEC_FNAME = "wandb-jobspec.json"
+CONDA_ENVIRONMENTS_FNAME = "conda-environment.yaml"
+
+
+def is_wandb_file(name: str) -> bool:
+ return (
+ name.startswith("wandb")
+ or name == METADATA_FNAME
+ or name == CONFIG_FNAME
+ or name == REQUIREMENTS_FNAME
+ or name == OUTPUT_FNAME
+ or name == DIFF_FNAME
+ or name == CONDA_ENVIRONMENTS_FNAME
+ )
+
+
+def filtered_dir(
+ root: str,
+ include_fn: Union[Callable[[str, str], bool], Callable[[str], bool]],
+ exclude_fn: Union[Callable[[str, str], bool], Callable[[str], bool]],
+) -> Generator[str, None, None]:
+ """Simple generator to walk a directory."""
+ import inspect
+
+ # compatibility with old API, which didn't pass root
+ def _include_fn(path: str, root: str) -> bool:
+ return (
+ include_fn(path, root) # type: ignore
+ if len(inspect.signature(include_fn).parameters) == 2
+ else include_fn(path) # type: ignore
+ )
+
+ def _exclude_fn(path: str, root: str) -> bool:
+ return (
+ exclude_fn(path, root) # type: ignore
+ if len(inspect.signature(exclude_fn).parameters) == 2
+ else exclude_fn(path) # type: ignore
+ )
+
+ for dirpath, _, files in os.walk(root):
+ for fname in files:
+ file_path = os.path.join(dirpath, fname)
+ if _include_fn(file_path, root) and not _exclude_fn(file_path, root):
+ yield file_path
+
+
+def exclude_wandb_fn(path: str, root: str) -> bool:
+ return any(
+ os.path.relpath(path, root).startswith(wandb_dir + os.sep)
+ for wandb_dir in WANDB_DIRS
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/filesystem.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/filesystem.py
new file mode 100644
index 0000000000000000000000000000000000000000..180ebbb2c19aaa522e9d839141c9c0a740666117
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/filesystem.py
@@ -0,0 +1,372 @@
+import contextlib
+import ctypes
+import errno
+import logging
+import os
+import platform
+import re
+import shutil
+import tempfile
+import threading
+from pathlib import Path
+from typing import IO, Any, BinaryIO, Generator, Optional
+
+from wandb.sdk.lib.paths import StrPath
+
+logger = logging.getLogger(__name__)
+
+# https://en.wikipedia.org/wiki/Filename#Comparison_of_filename_limitations
+PROBLEMATIC_PATH_CHARS = "".join(chr(i) for i in range(32)) + ':"*<>?|'
+
+
+def mkdir_exists_ok(dir_name: StrPath) -> None:
+ """Create `dir_name` and any parent directories if they don't exist.
+
+ Raises:
+ FileExistsError: if `dir_name` exists and is not a directory.
+ PermissionError: if `dir_name` is not writable.
+ """
+ try:
+ os.makedirs(dir_name, exist_ok=True)
+ except FileExistsError as e:
+ raise FileExistsError(f"{dir_name!s} exists and is not a directory") from e
+ except PermissionError as e:
+ raise PermissionError(f"{dir_name!s} is not writable") from e
+
+
+def path_fallbacks(path: StrPath) -> Generator[str, None, None]:
+ """Yield variations of `path` that may exist on the filesystem.
+
+ Return a sequence of paths that should be checked in order for existence or
+ create-ability. Essentially, keep replacing "suspect" characters until we run out.
+ """
+ path = str(path)
+ root, tail = os.path.splitdrive(path)
+ yield os.path.join(root, tail)
+ for char in PROBLEMATIC_PATH_CHARS:
+ if char in tail:
+ tail = tail.replace(char, "-")
+ yield os.path.join(root, tail)
+
+
+def mkdir_allow_fallback(dir_name: StrPath) -> StrPath:
+ """Create `dir_name`, removing invalid path characters if necessary.
+
+ Returns:
+ The path to the created directory, which may not be the original path.
+ """
+ for new_name in path_fallbacks(dir_name):
+ try:
+ os.makedirs(new_name, exist_ok=True)
+ if Path(new_name) != Path(dir_name):
+ logger.warning(f"Creating '{new_name}' instead of '{dir_name}'")
+ return Path(new_name) if isinstance(dir_name, Path) else new_name
+ except (ValueError, NotADirectoryError):
+ pass
+ except OSError as e:
+ if e.errno != 22:
+ raise
+
+ raise OSError(f"Unable to create directory '{dir_name}'")
+
+
+def files_in(path: StrPath) -> Generator[os.DirEntry, None, None]:
+ """Yield a directory entry for each file under a given path (recursive)."""
+ if not os.path.isdir(path):
+ return
+ for entry in os.scandir(path):
+ if entry.is_dir():
+ yield from files_in(entry.path)
+ else:
+ yield entry
+
+
+class WriteSerializingFile:
+ """Wrapper for a file object that serializes writes."""
+
+ def __init__(self, f: BinaryIO) -> None:
+ self.lock = threading.Lock()
+ self.f = f
+
+ def write(self, *args, **kargs) -> None: # type: ignore
+ self.lock.acquire()
+ try:
+ self.f.write(*args, **kargs)
+ self.f.flush()
+ finally:
+ self.lock.release()
+
+ def close(self) -> None:
+ self.lock.acquire() # wait for pending writes
+ try:
+ self.f.close()
+ finally:
+ self.lock.release()
+
+
+class CRDedupedFile(WriteSerializingFile):
+ def __init__(self, f: BinaryIO) -> None:
+ super().__init__(f=f)
+ self._buff = b""
+
+ def write(self, data) -> None: # type: ignore
+ lines = re.split(b"\r\n|\n", data)
+ ret = [] # type: ignore
+ for line in lines:
+ if line[:1] == b"\r":
+ if ret:
+ ret.pop()
+ elif self._buff:
+ self._buff = b""
+ line = line.split(b"\r")[-1]
+ if line:
+ ret.append(line)
+ if self._buff:
+ ret.insert(0, self._buff)
+ if ret:
+ self._buff = ret.pop()
+ super().write(b"\n".join(ret) + b"\n")
+
+ def close(self) -> None:
+ if self._buff:
+ super().write(self._buff)
+ super().close()
+
+
+def copy_or_overwrite_changed(source_path: StrPath, target_path: StrPath) -> StrPath:
+ """Copy source_path to target_path, unless it already exists with the same mtime.
+
+ We liberally add write permissions to deal with the case of multiple users needing
+ to share the same cache or run directory.
+
+ Args:
+ source_path: The path to the file to copy.
+ target_path: The path to copy the file to.
+
+ Returns:
+ The path to the copied file (which may be different from target_path).
+ """
+ return_type = type(target_path)
+
+ target_path = system_preferred_path(target_path, warn=True)
+
+ need_copy = (
+ not os.path.isfile(target_path)
+ or os.stat(source_path).st_mtime != os.stat(target_path).st_mtime
+ )
+
+ permissions_plus_write = os.stat(source_path).st_mode
+ if need_copy:
+ dir_name, file_name = os.path.split(target_path)
+ target_path = os.path.join(mkdir_allow_fallback(dir_name), file_name)
+ try:
+ # Use copy2 to preserve file metadata (including modified time).
+ shutil.copy2(source_path, target_path)
+ except PermissionError:
+ # If the file is read-only try to make it writable.
+ try:
+ os.chmod(target_path, permissions_plus_write)
+ shutil.copy2(source_path, target_path)
+ except PermissionError as e:
+ raise PermissionError("Unable to overwrite '{target_path!s}'") from e
+ # Prevent future permissions issues by universal write permissions now.
+ os.chmod(target_path, permissions_plus_write)
+
+ return return_type(target_path) # type: ignore # 'os.PathLike' is abstract.
+
+
+@contextlib.contextmanager
+def safe_open(
+ path: StrPath, mode: str = "r", *args: Any, **kwargs: Any
+) -> Generator[IO, None, None]:
+ """Open a file, ensuring any changes only apply atomically after close.
+
+ This context manager ensures that even unsuccessful writes will not leave a "dirty"
+ file or overwrite good data, and that all temp data is cleaned up.
+
+ The semantics and behavior are intended to be nearly identical to the built-in
+ open() function. Differences:
+ - It creates any parent directories that don't exist, rather than raising.
+ - In 'x' mode, it checks at the beginning AND end of the write and fails if the
+ file exists either time.
+ """
+ path = Path(path).resolve()
+ path.parent.mkdir(parents=True, exist_ok=True)
+
+ if "x" in mode and path.exists():
+ raise FileExistsError(f"{path!s} already exists")
+
+ if "r" in mode and "+" not in mode:
+ # This is read-only, so we can just open the original file.
+ # TODO (hugh): create a reflink and read from that.
+ with path.open(mode, *args, **kwargs) as f:
+ yield f
+ return
+
+ with tempfile.TemporaryDirectory(dir=path.parent) as tmp_dir:
+ tmp_path = Path(tmp_dir) / path.name
+
+ if ("r" in mode or "a" in mode) and path.exists():
+ # We need to copy the original file in order to support reads and appends.
+ # TODO (hugh): use reflinks to avoid the copy on platforms that support it.
+ shutil.copy2(path, tmp_path)
+
+ with tmp_path.open(mode, *args, **kwargs) as f:
+ yield f
+ f.flush()
+ os.fsync(f.fileno())
+
+ if "x" in mode:
+ # Ensure that if another process has beaten us to writing the file we raise
+ # rather than overwrite. os.link() atomically creates a hard link to the
+ # target file and will raise FileExistsError if the target already exists.
+ os.link(tmp_path, path)
+ os.unlink(tmp_path)
+ else:
+ tmp_path.replace(path)
+
+
+def safe_copy(source_path: StrPath, target_path: StrPath) -> StrPath:
+ """Copy a file atomically.
+
+ Copying is not usually atomic, and on operating systems that allow multiple
+ writers to the same file, the result can get corrupted. If two writers copy
+ to the same file, the contents can become interleaved.
+
+ We mitigate the issue somewhat by copying to a temporary file first and
+ then renaming. Renaming is atomic: if process 1 renames file A to X and
+ process 2 renames file B to X, then X will either contain the contents
+ of A or the contents of B, not some mixture of both.
+ """
+ # TODO (hugh): check that there is enough free space.
+ output_path = Path(target_path).resolve()
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(dir=output_path.parent) as tmp_dir:
+ tmp_path = (Path(tmp_dir) / Path(source_path).name).with_suffix(".tmp")
+ shutil.copy2(source_path, tmp_path)
+ tmp_path.replace(output_path)
+ return target_path
+
+
+def _reflink_linux(existing_path: Path, new_path: Path) -> None:
+ """Create a reflink to `existing_path` at `new_path` on Linux."""
+ import fcntl
+
+ FICLONE = 0x40049409 # magic number from # noqa: N806
+ with open(existing_path, "rb") as t_f, open(new_path, "wb+") as l_f:
+ fcntl.ioctl(l_f.fileno(), FICLONE, t_f.fileno())
+
+
+def _reflink_macos(existing_path: Path, new_path: Path) -> None:
+ try:
+ clib = ctypes.CDLL("libc.dylib", use_errno=True)
+ except (FileNotFoundError, OSError) as e:
+ if ctypes.get_errno() != errno.ENOENT and not isinstance(e, FileNotFoundError):
+ raise
+ # Before macOS 11 ( None:
+ """Create a reflink to `existing_path` at `new_path`.
+
+ A reflink (reflective link) is a copy-on-write reference to a file. Once linked, the
+ file and link are both "real" files (not symbolic or hard links) and each can be
+ modified independently without affecting the other; however, they share the same
+ underlying data blocks on disk so until one is modified they are "zero-cost" copies.
+
+ Reflinks have all the functionality of copies, so we should use them wherever they
+ are supported if we would otherwise copy a file. (This is not particularly radical--
+ GNU `cp` defaults to `reflink=auto`, using it whenever available) However, support
+ for them is limited to a small number of filesystems. They should work on:
+ - Linux with a Btrfs or XFS filesystem (NOT ext4)
+ - macOS 10.13 or later with an APFS filesystem (called clone files)
+
+ Reflinks are also supported on Solaris and Windows with ReFSv2, but we haven't
+ implemented support for them.
+
+ Like hard links, a reflink can only be created on the same filesystem as the target.
+ """
+ if platform.system() == "Linux":
+ link_fn = _reflink_linux
+ elif platform.system() == "Darwin":
+ link_fn = _reflink_macos
+ else:
+ raise OSError(
+ errno.ENOTSUP, f"reflinks are not supported on {platform.system()}"
+ )
+
+ new_path = Path(new_path).resolve()
+ existing_path = Path(existing_path).resolve()
+ if new_path.exists():
+ if not overwrite:
+ raise FileExistsError(f"{new_path} already exists")
+ logger.warning(f"Overwriting existing file {new_path}.")
+ new_path.unlink()
+
+ # Create any missing parent directories.
+ new_path.parent.mkdir(parents=True, exist_ok=True)
+
+ try:
+ link_fn(existing_path, new_path)
+ except OSError as e:
+ base_msg = f"failed to create reflink from {existing_path} to {new_path}."
+ if e.errno in (errno.EPERM, errno.EACCES):
+ raise PermissionError(f"Insufficient permissions; {base_msg}") from e
+ if e.errno == errno.ENOENT:
+ raise FileNotFoundError(f"File not found; {base_msg}") from e
+ if e.errno == errno.EXDEV:
+ raise ValueError(f"Cannot link across filesystems; {base_msg}") from e
+ if e.errno == errno.EISDIR:
+ raise IsADirectoryError(f"Cannot reflink a directory; {base_msg}") from e
+ if e.errno in (errno.EOPNOTSUPP, errno.ENOTSUP):
+ raise OSError(
+ errno.ENOTSUP,
+ f"Filesystem does not support reflinks; {base_msg}",
+ ) from e
+ if e.errno == errno.EINVAL:
+ raise ValueError(f"Cannot link file ranges; {base_msg}") from e
+ raise
+
+
+def check_exists(path: StrPath) -> Optional[StrPath]:
+ """Look for variations of `path` and return the first found.
+
+ This exists to support former behavior around system-dependent paths; we used to use
+ ':' in Artifact paths unless we were on Windows, but this has issues when e.g. a
+ Linux machine is accessing an NTFS filesystem; we might need to look for the
+ alternate path. This checks all the possible directories we would consider creating.
+ """
+ for dest in path_fallbacks(path):
+ if os.path.exists(dest):
+ return Path(dest) if isinstance(path, Path) else dest
+ return None
+
+
+def system_preferred_path(path: StrPath, warn: bool = False) -> StrPath:
+ """Replace ':' with '-' in paths on Windows.
+
+ Args:
+ path: The path to convert.
+ warn: Whether to warn if ':' is replaced.
+ """
+ if platform.system() != "Windows":
+ return path
+ head, tail = os.path.splitdrive(path)
+ if warn and ":" in tail:
+ logger.warning(f"Replacing ':' in {tail} with '-'")
+ new_path = head + tail.replace(":", "-")
+ return Path(new_path) if isinstance(path, Path) else new_path
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/fsm.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/fsm.py
new file mode 100644
index 0000000000000000000000000000000000000000..d36bb472f7a39668896488115dfcb9cdaee9ae78
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/fsm.py
@@ -0,0 +1,165 @@
+#!/usr/bin/env python
+"""Finite state machine.
+
+Simple FSM implementation.
+
+Usage:
+ ```python
+ class A:
+ def on_output(self, inputs) -> None:
+ pass
+
+
+ class B:
+ def on_output(self, inputs) -> None:
+ pass
+
+
+ def to_b(inputs) -> bool:
+ return True
+
+
+ def to_a(inputs) -> bool:
+ return True
+
+
+ f = Fsm(states=[A(), B()], table={A: [(to_b, B)], B: [(to_a, A)]})
+ f.run({"input1": 1, "input2": 2})
+ ```
+"""
+
+from abc import abstractmethod
+from dataclasses import dataclass
+from typing import Callable, Dict, Generic, Optional, Sequence, Type, Union
+
+from typing_extensions import Protocol, TypeAlias, TypeVar, runtime_checkable
+
+T_FsmInputs = TypeVar("T_FsmInputs", contravariant=True)
+T_FsmContext = TypeVar("T_FsmContext")
+T_FsmContext_cov = TypeVar("T_FsmContext_cov", covariant=True)
+T_FsmContext_contra = TypeVar("T_FsmContext_contra", contravariant=True)
+
+
+@runtime_checkable
+class FsmStateCheck(Protocol[T_FsmInputs]):
+ @abstractmethod
+ def on_check(self, inputs: T_FsmInputs) -> None: ... # pragma: no cover
+
+
+@runtime_checkable
+class FsmStateOutput(Protocol[T_FsmInputs]):
+ @abstractmethod
+ def on_state(self, inputs: T_FsmInputs) -> None: ... # pragma: no cover
+
+
+@runtime_checkable
+class FsmStateEnter(Protocol[T_FsmInputs]):
+ @abstractmethod
+ def on_enter(self, inputs: T_FsmInputs) -> None: ... # pragma: no cover
+
+
+@runtime_checkable
+class FsmStateEnterWithContext(Protocol[T_FsmInputs, T_FsmContext_contra]):
+ @abstractmethod
+ def on_enter(
+ self, inputs: T_FsmInputs, context: T_FsmContext_contra
+ ) -> None: ... # pragma: no cover
+
+
+@runtime_checkable
+class FsmStateStay(Protocol[T_FsmInputs]):
+ @abstractmethod
+ def on_stay(self, inputs: T_FsmInputs) -> None: ... # pragma: no cover
+
+
+@runtime_checkable
+class FsmStateExit(Protocol[T_FsmInputs, T_FsmContext_cov]):
+ @abstractmethod
+ def on_exit(self, inputs: T_FsmInputs) -> T_FsmContext_cov: ... # pragma: no cover
+
+
+# It would be nice if python provided optional protocol members, but it does not as described here:
+# https://peps.python.org/pep-0544/#support-optional-protocol-members
+# Until then, we can only enforce that a state at least supports one protocol interface. This
+# unfortunately will not check the signature of other potential protocols.
+FsmState: TypeAlias = Union[
+ FsmStateCheck[T_FsmInputs],
+ FsmStateOutput[T_FsmInputs],
+ FsmStateEnter[T_FsmInputs],
+ FsmStateEnterWithContext[T_FsmInputs, T_FsmContext],
+ FsmStateStay[T_FsmInputs],
+ FsmStateExit[T_FsmInputs, T_FsmContext],
+]
+
+
+@dataclass
+class FsmEntry(Generic[T_FsmInputs, T_FsmContext]):
+ condition: Callable[[T_FsmInputs], bool]
+ target_state: Type[FsmState[T_FsmInputs, T_FsmContext]]
+ action: Optional[Callable[[T_FsmInputs], None]] = None
+
+
+FsmTableWithContext: TypeAlias = Dict[
+ Type[FsmState[T_FsmInputs, T_FsmContext]],
+ Sequence[FsmEntry[T_FsmInputs, T_FsmContext]],
+]
+
+
+FsmTable: TypeAlias = FsmTableWithContext[T_FsmInputs, None]
+
+
+class FsmWithContext(Generic[T_FsmInputs, T_FsmContext]):
+ _state_dict: Dict[Type[FsmState], FsmState]
+ _table: FsmTableWithContext[T_FsmInputs, T_FsmContext]
+ _state: FsmState[T_FsmInputs, T_FsmContext]
+ _states: Sequence[FsmState]
+
+ def __init__(
+ self,
+ states: Sequence[FsmState],
+ table: FsmTableWithContext[T_FsmInputs, T_FsmContext],
+ ) -> None:
+ self._states = states
+ self._table = table
+ self._state_dict = {type(s): s for s in states}
+ self._state = self._state_dict[type(states[0])]
+
+ def _transition(
+ self,
+ inputs: T_FsmInputs,
+ new_state: Type[FsmState[T_FsmInputs, T_FsmContext]],
+ action: Optional[Callable[[T_FsmInputs], None]],
+ ) -> None:
+ if action:
+ action(inputs)
+
+ context = None
+ if isinstance(self._state, FsmStateExit):
+ context = self._state.on_exit(inputs)
+
+ prev_state = type(self._state)
+ if prev_state == new_state:
+ if isinstance(self._state, FsmStateStay):
+ self._state.on_stay(inputs)
+ else:
+ self._state = self._state_dict[new_state]
+ if context and isinstance(self._state, FsmStateEnterWithContext):
+ self._state.on_enter(inputs, context=context)
+ elif isinstance(self._state, FsmStateEnter):
+ self._state.on_enter(inputs)
+
+ def _check_transitions(self, inputs: T_FsmInputs) -> None:
+ for entry in self._table[type(self._state)]:
+ if entry.condition(inputs):
+ self._transition(inputs, entry.target_state, entry.action)
+ return
+
+ def input(self, inputs: T_FsmInputs) -> None:
+ if isinstance(self._state, FsmStateCheck):
+ self._state.on_check(inputs)
+ self._check_transitions(inputs)
+ if isinstance(self._state, FsmStateOutput):
+ self._state.on_state(inputs)
+
+
+Fsm: TypeAlias = FsmWithContext[T_FsmInputs, None]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/gitlib.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/gitlib.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2f18a42e101ae3a78764282421a2fb0c57ee673
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/gitlib.py
@@ -0,0 +1,240 @@
+import configparser
+import logging
+import os
+from typing import TYPE_CHECKING, Any, Optional
+from urllib.parse import urlparse, urlunparse
+
+import wandb
+
+try:
+ from git import ( # type: ignore
+ GitCommandError,
+ InvalidGitRepositoryError,
+ NoSuchPathError,
+ Repo,
+ )
+except ImportError:
+ Repo = None # type: ignore
+
+if TYPE_CHECKING:
+ from git import Repo
+
+
+logger = logging.getLogger(__name__)
+
+
+class GitRepo:
+ def __init__(
+ self,
+ root: Optional[str] = None,
+ remote: str = "origin",
+ lazy: bool = True,
+ remote_url: Optional[str] = None,
+ commit: Optional[str] = None,
+ ) -> None:
+ self.remote_name = remote if remote_url is None else None
+ self._root = root
+ self._remote_url = remote_url
+ self._commit = commit
+ self._repo = None
+ self._repo_initialized = False
+ if not lazy:
+ self._repo = self._init_repo()
+
+ def _init_repo(self) -> Optional[Repo]:
+ self._repo_initialized = True
+ if Repo is None:
+ return None
+ if self.remote_name is None:
+ return None
+ try:
+ return Repo(self._root or os.getcwd(), search_parent_directories=True)
+ except FileNotFoundError:
+ wandb.termwarn("current working directory has been invalidated")
+ logger.warning("current working directory has been invalidated")
+ except InvalidGitRepositoryError:
+ logger.debug("git repository is invalid")
+ except NoSuchPathError:
+ wandb.termwarn(f"git root {self._root} does not exist")
+ logger.warning(f"git root {self._root} does not exist")
+ return None
+
+ @property
+ def repo(self) -> Optional[Repo]:
+ if not self._repo_initialized:
+ self._repo = self._init_repo()
+ return self._repo
+
+ @property
+ def auto(self) -> bool:
+ return self._remote_url is None
+
+ def is_untracked(self, file_name: str) -> Optional[bool]:
+ if not self.repo:
+ return True
+ try:
+ return file_name in self.repo.untracked_files
+ except GitCommandError:
+ return None
+
+ @property
+ def enabled(self) -> bool:
+ return bool(self.repo)
+
+ @property
+ def root(self) -> Any:
+ if not self.repo:
+ return None
+ try:
+ return self.repo.git.rev_parse("--show-toplevel")
+ except GitCommandError:
+ # todo: collect telemetry on this
+ logger.exception("git root error")
+ return None
+
+ @property
+ def dirty(self) -> Any:
+ if not self.repo:
+ return False
+ try:
+ return self.repo.is_dirty()
+ except GitCommandError:
+ return False
+
+ @property
+ def email(self) -> Optional[str]:
+ if not self.repo:
+ return None
+ try:
+ return self.repo.config_reader().get_value("user", "email") # type: ignore
+ except configparser.Error:
+ return None
+
+ @property
+ def last_commit(self) -> Any:
+ if self._commit:
+ return self._commit
+ if not self.repo:
+ return None
+ if not self.repo.head or not self.repo.head.is_valid():
+ return None
+ # TODO: Saw a user getting a Unicode decode error when parsing refs,
+ # more details on implementing a real fix in [WB-4064]
+ try:
+ if len(self.repo.refs) > 0: # type: ignore[arg-type]
+ return self.repo.head.commit.hexsha
+ else:
+ return self.repo.git.show_ref("--head").split(" ")[0]
+ except Exception:
+ logger.exception("Unable to find most recent commit in git")
+ return None
+
+ @property
+ def branch(self) -> Any:
+ if not self.repo:
+ return None
+ return self.repo.head.ref.name
+
+ @property
+ def remote(self) -> Any:
+ if not self.repo:
+ return None
+ try:
+ return self.repo.remotes[self.remote_name] # type: ignore[index]
+ except IndexError:
+ return None
+
+ # the --submodule=diff option doesn't exist in pre-2.11 versions of git (november 2016)
+ # https://stackoverflow.com/questions/10757091/git-list-of-all-changed-files-including-those-in-submodules
+ @property
+ def has_submodule_diff(self) -> bool:
+ if not self.repo:
+ return False
+ return bool(self.repo.git.version_info >= (2, 11, 0))
+
+ @property
+ def remote_url(self) -> Any:
+ if self._remote_url:
+ return self._remote_url
+ if not self.remote:
+ return None
+ parsed = urlparse(self.remote.url)
+ hostname = parsed.hostname
+ if parsed.port is not None:
+ hostname = f"{hostname}:{parsed.port}"
+ if parsed.password is not None:
+ return urlunparse(parsed._replace(netloc=f"{parsed.username}:@{hostname}"))
+ return urlunparse(parsed._replace(netloc=hostname))
+
+ @property
+ def root_dir(self) -> Any:
+ if not self.repo:
+ return None
+ try:
+ return self.repo.git.rev_parse("--show-toplevel")
+ except GitCommandError:
+ return None
+
+ def get_upstream_fork_point(self) -> Any:
+ """Get the most recent ancestor of HEAD that occurs on an upstream branch.
+
+ First looks at the current branch's tracking branch, if applicable. If
+ that doesn't work, looks at every other branch to find the most recent
+ ancestor of HEAD that occurs on a tracking branch.
+
+ Returns:
+ git.Commit object or None
+ """
+ possible_relatives = []
+ try:
+ if not self.repo:
+ return None
+ try:
+ active_branch = self.repo.active_branch
+ except (TypeError, ValueError):
+ logger.debug("git is in a detached head state")
+ return None # detached head
+ else:
+ tracking_branch = active_branch.tracking_branch()
+ if tracking_branch:
+ possible_relatives.append(tracking_branch.commit)
+
+ if not possible_relatives:
+ for branch in self.repo.branches: # type: ignore[attr-defined]
+ tracking_branch = branch.tracking_branch()
+ if tracking_branch is not None:
+ possible_relatives.append(tracking_branch.commit)
+
+ head = self.repo.head
+ most_recent_ancestor = None
+ for possible_relative in possible_relatives:
+ # at most one:
+ for ancestor in self.repo.merge_base(head, possible_relative):
+ if most_recent_ancestor is None:
+ most_recent_ancestor = ancestor
+ elif self.repo.is_ancestor(most_recent_ancestor, ancestor): # type: ignore
+ most_recent_ancestor = ancestor
+ except GitCommandError as e:
+ logger.debug("git remote upstream fork point could not be found")
+ logger.debug(str(e))
+ return None
+
+ return most_recent_ancestor
+
+ def tag(self, name: str, message: Optional[str]) -> Any:
+ if not self.repo:
+ return None
+ try:
+ return self.repo.create_tag(f"wandb/{name}", message=message, force=True)
+ except GitCommandError:
+ logger.debug("Failed to tag repository.")
+ return None
+
+ def push(self, name: str) -> Any:
+ if not self.remote:
+ return None
+ try:
+ return self.remote.push(f"wandb/{name}", force=True)
+ except GitCommandError:
+ logger.debug("failed to push git")
+ return None
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/gql_request.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/gql_request.py
new file mode 100644
index 0000000000000000000000000000000000000000..8006d4659dcd1fb75280e414745420b9af15136a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/gql_request.py
@@ -0,0 +1,76 @@
+"""A simple GraphQL client for sending queries and mutations.
+
+Note: This was originally wandb/vendor/gql-0.2.0/wandb_gql/transport/requests.py
+The only substantial change is to reuse a requests.Session object.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Callable
+
+import requests
+from wandb_gql.transport.http import HTTPTransport
+from wandb_graphql.execution import ExecutionResult
+from wandb_graphql.language import ast
+from wandb_graphql.language.printer import print_ast
+
+from wandb._analytics import tracked_func
+
+
+class GraphQLSession(HTTPTransport):
+ def __init__(
+ self,
+ url: str,
+ auth: tuple[str, str] | Callable | None = None,
+ use_json: bool = False,
+ timeout: int | float | None = None,
+ proxies: dict[str, str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Setup a session for sending GraphQL queries and mutations.
+
+ Args:
+ url (str): The GraphQL URL
+ auth (tuple or callable): Auth tuple or callable for Basic/Digest/Custom HTTP Auth
+ use_json (bool): Send request body as JSON instead of form-urlencoded
+ timeout (int, float): Specifies a default timeout for requests (Default: None)
+ """
+ super().__init__(url, **kwargs)
+ self.session = requests.Session()
+ if proxies:
+ self.session.proxies.update(proxies)
+ self.session.auth = auth
+ self.default_timeout = timeout
+ self.use_json = use_json
+
+ def execute(
+ self,
+ document: ast.Node,
+ variable_values: dict[str, Any] | None = None,
+ timeout: int | float | None = None,
+ ) -> ExecutionResult:
+ query_str = print_ast(document)
+ payload = {"query": query_str, "variables": variable_values or {}}
+
+ data_key = "json" if self.use_json else "data"
+
+ headers = self.headers.copy() if self.headers else {}
+
+ # If we're tracking a calling python function, include it in the headers
+ if func_info := tracked_func():
+ headers.update(func_info.to_headers())
+
+ post_args = {
+ "headers": headers or None,
+ "cookies": self.cookies,
+ "timeout": timeout or self.default_timeout,
+ data_key: payload,
+ }
+ request = self.session.post(self.url, **post_args)
+ request.raise_for_status()
+
+ result = request.json()
+ data, errors = result.get("data"), result.get("errors")
+ if data is None and errors is None:
+ raise RuntimeError(f"Received non-compatible response: {result}")
+ return ExecutionResult(data=data, errors=errors)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/handler_util.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/handler_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4efd8d571baebab80f9a7702efdd962f0c9028d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/handler_util.py
@@ -0,0 +1,21 @@
+import wandb.data_types as data_types
+
+
+def get_types():
+ classes = map(data_types.__dict__.get, data_types.__all__)
+ types = []
+ for cls in classes:
+ if hasattr(cls, "_log_type") and cls._log_type is not None:
+ types.append(cls._log_type)
+ # add table-file type because this is a special case
+ # that does not have a matching _log_type for artifacts
+ # and files
+ types.append("table-file")
+ return types
+
+
+WANDB_TYPES = get_types()
+
+
+def metric_is_wandb_dict(metric):
+ return "_type" in list(metric.keys()) and metric["_type"] in WANDB_TYPES
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/hashutil.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/hashutil.py
new file mode 100644
index 0000000000000000000000000000000000000000..96f7ac8f63678c49ad8bb92a3db5bfe270b3cfeb
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/hashutil.py
@@ -0,0 +1,106 @@
+from __future__ import annotations
+
+import base64
+import hashlib
+import logging
+import mmap
+import sys
+import time
+from typing import TYPE_CHECKING
+
+from typing_extensions import TypeAlias
+
+from wandb.sdk.lib.paths import StrPath
+
+if TYPE_CHECKING:
+ import _hashlib # type: ignore[import-not-found]
+
+
+logger = logging.getLogger(__name__)
+
+# In the future, consider relying on pydantic to validate these types via e.g.
+# - Base64Str: https://docs.pydantic.dev/latest/api/types/#pydantic.types.Base64Str
+# - a custom EncodedStr + Encoder impl: https://docs.pydantic.dev/latest/api/types/#pydantic.types.EncodedStr
+#
+# Note that so long as we continue to support Pydantic v1, the options above will require a compatible shim/backport
+# implementation, since those types are not in Pydantic v1.
+ETag: TypeAlias = str
+HexMD5: TypeAlias = str
+B64MD5: TypeAlias = str
+
+
+def _md5(data: bytes = b"") -> _hashlib.HASH:
+ """Allow FIPS-compliant md5 hash when supported."""
+ if sys.version_info >= (3, 9):
+ return hashlib.md5(data, usedforsecurity=False)
+ else:
+ return hashlib.md5(data)
+
+
+def md5_string(string: str) -> B64MD5:
+ return _b64_from_hasher(_md5(string.encode("utf-8")))
+
+
+def _b64_from_hasher(hasher: _hashlib.HASH) -> B64MD5:
+ return B64MD5(base64.b64encode(hasher.digest()).decode("ascii"))
+
+
+def b64_to_hex_id(string: B64MD5) -> HexMD5:
+ return HexMD5(base64.standard_b64decode(string).hex())
+
+
+def hex_to_b64_id(encoded_string: str | bytes) -> B64MD5:
+ if isinstance(encoded_string, bytes):
+ encoded_string = encoded_string.decode("utf-8")
+ as_str = bytes.fromhex(encoded_string)
+ return B64MD5(base64.standard_b64encode(as_str).decode("utf-8"))
+
+
+def md5_file_b64(*paths: StrPath) -> B64MD5:
+ start_time = time.monotonic()
+ digest = _b64_from_hasher(_md5_file_hasher(*paths))
+ hash_time_seconds = time.monotonic() - start_time
+ if hash_time_seconds > 1.0:
+ logger.debug(
+ "Computed MD5 hash for file. paths=%s, hashTimeMs=%d",
+ paths,
+ int(hash_time_seconds * 1000),
+ )
+ return digest
+
+
+def md5_file_hex(*paths: StrPath) -> HexMD5:
+ return HexMD5(_md5_file_hasher(*paths).hexdigest())
+
+
+_KB: int = 1_024
+_CHUNKSIZE: int = 128 * _KB
+"""Chunk size (in bytes) for iteratively reading from file, if needed."""
+
+
+def _md5_file_hasher(*paths: StrPath) -> _hashlib.HASH:
+ md5_hash = _md5()
+
+ # Note: We use str paths (instead of pathlib.Path objs) for minor perf improvements.
+ for path in sorted(map(str, paths)):
+ with open(path, "rb") as f:
+ try:
+ with mmap.mmap(f.fileno(), length=0, access=mmap.ACCESS_READ) as mview:
+ md5_hash.update(mview)
+ except OSError:
+ # This occurs if the mmap-ed file is on a different/mounted filesystem,
+ # so we'll fall back on a less performant implementation.
+
+ # Note: At the time of implementation, the walrus operator `:=`
+ # is avoided to maintain support for users on python 3.7.
+ # Consider revisiting once 3.7 support is no longer needed.
+ chunk = f.read(_CHUNKSIZE)
+ while chunk:
+ md5_hash.update(chunk)
+ chunk = f.read(_CHUNKSIZE)
+ except ValueError:
+ # This occurs when mmap-ing an empty file, which can be skipped.
+ # See: https://github.com/python/cpython/blob/986a4e1b6fcae7fe7a1d0a26aea446107dd58dd2/Modules/mmapmodule.c#L1589
+ pass
+
+ return md5_hash
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/import_hooks.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/import_hooks.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ef7bb3f4384797fb491650acd0446ef0d1cb35b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/import_hooks.py
@@ -0,0 +1,275 @@
+"""Implements a post-import hook mechanism.
+
+Styled as per PEP-369. Note that it doesn't cope with modules being reloaded.
+
+Note: This file is based on
+https://github.com/GrahamDumpleton/wrapt/blob/1.12.1/src/wrapt/importer.py
+and manual backports of later patches up to 1.15.0 in the wrapt repository
+(with slight modifications).
+"""
+
+import sys
+import threading
+from importlib.util import find_spec
+from typing import Any, Callable, Dict, Optional, Union
+
+# The dictionary registering any post import hooks to be triggered once
+# the target module has been imported. Once a module has been imported
+# and the hooks fired, the list of hooks recorded against the target
+# module will be truncated but the list left in the dictionary. This
+# acts as a flag to indicate that the module had already been imported.
+
+_post_import_hooks: Dict = {}
+_post_import_hooks_init: bool = False
+_post_import_hooks_lock = threading.RLock()
+
+# Register a new post import hook for the target module name. This
+# differs from the PEP-369 implementation in that it also allows the
+# hook function to be specified as a string consisting of the name of
+# the callback in the form 'module:function'. This will result in a
+# proxy callback being registered which will defer loading of the
+# specified module containing the callback function until required.
+
+
+def _create_import_hook_from_string(name: str) -> Callable:
+ def import_hook(module: Any) -> Callable:
+ module_name, function = name.split(":")
+ attrs = function.split(".")
+ __import__(module_name)
+ callback = sys.modules[module_name]
+ for attr in attrs:
+ callback = getattr(callback, attr)
+ return callback(module) # type: ignore
+
+ return import_hook
+
+
+def register_post_import_hook(
+ hook: Union[str, Callable], hook_id: str, name: str
+) -> None:
+ # Create a deferred import hook if hook is a string name rather than
+ # a callable function.
+
+ if isinstance(hook, (str,)):
+ hook = _create_import_hook_from_string(hook)
+
+ # Automatically install the import hook finder if it has not already
+ # been installed.
+
+ with _post_import_hooks_lock:
+ global _post_import_hooks_init
+
+ if not _post_import_hooks_init:
+ _post_import_hooks_init = True
+ sys.meta_path.insert(0, ImportHookFinder()) # type: ignore
+
+ # Check if the module is already imported. If not, register the hook
+ # to be called after import.
+
+ module = sys.modules.get(name, None)
+
+ if module is None:
+ _post_import_hooks.setdefault(name, {}).update({hook_id: hook})
+
+ # If the module is already imported, we fire the hook right away. Note that
+ # the hook is called outside of the lock to avoid deadlocks if code run as a
+ # consequence of calling the module import hook in turn triggers a separate
+ # thread which tries to register an import hook.
+
+ if module is not None:
+ hook(module)
+
+
+def unregister_post_import_hook(name: str, hook_id: Optional[str]) -> None:
+ # Remove the import hook if it has been registered.
+ with _post_import_hooks_lock:
+ hooks = _post_import_hooks.get(name)
+
+ if hooks is not None:
+ if hook_id is not None:
+ hooks.pop(hook_id, None)
+
+ if not hooks:
+ del _post_import_hooks[name]
+ else:
+ del _post_import_hooks[name]
+
+
+def unregister_all_post_import_hooks() -> None:
+ with _post_import_hooks_lock:
+ _post_import_hooks.clear()
+
+
+# Indicate that a module has been loaded. Any post import hooks which
+# were registered against the target module will be invoked. If an
+# exception is raised in any of the post import hooks, that will cause
+# the import of the target module to fail.
+
+
+def notify_module_loaded(module: Any) -> None:
+ name = getattr(module, "__name__", None)
+
+ with _post_import_hooks_lock:
+ hooks = _post_import_hooks.pop(name, {})
+
+ # Note that the hook is called outside of the lock to avoid deadlocks if
+ # code run as a consequence of calling the module import hook in turn
+ # triggers a separate thread which tries to register an import hook.
+ for hook in hooks.values():
+ if hook:
+ hook(module)
+
+
+# A custom module import finder. This intercepts attempts to import
+# modules and watches out for attempts to import target modules of
+# interest. When a module of interest is imported, then any post import
+# hooks which are registered will be invoked.
+
+
+class _ImportHookChainedLoader:
+ def __init__(self, loader: Any) -> None:
+ self.loader = loader
+
+ if hasattr(loader, "load_module"):
+ self.load_module = self._load_module
+ if hasattr(loader, "create_module"):
+ self.create_module = self._create_module
+ if hasattr(loader, "exec_module"):
+ self.exec_module = self._exec_module
+
+ def _set_loader(self, module: Any) -> None:
+ # Set module's loader to self.loader unless it's already set to
+ # something else. Import machinery will set it to spec.loader if it is
+ # None, so handle None as well. The module may not support attribute
+ # assignment, in which case we simply skip it. Note that we also deal
+ # with __loader__ not existing at all. This is to future proof things
+ # due to proposal to remove the attribute as described in the GitHub
+ # issue at https://github.com/python/cpython/issues/77458. Also prior
+ # to Python 3.3, the __loader__ attribute was only set if a custom
+ # module loader was used. It isn't clear whether the attribute still
+ # existed in that case or was set to None.
+
+ class UNDEFINED:
+ pass
+
+ if getattr(module, "__loader__", UNDEFINED) in (None, self):
+ try:
+ module.__loader__ = self.loader
+ except AttributeError:
+ pass
+
+ if (
+ getattr(module, "__spec__", None) is not None
+ and getattr(module.__spec__, "loader", None) is self
+ ):
+ module.__spec__.loader = self.loader
+
+ def _load_module(self, fullname: str) -> Any:
+ module = self.loader.load_module(fullname)
+ self._set_loader(module)
+ notify_module_loaded(module)
+
+ return module
+
+ # Python 3.4 introduced create_module() and exec_module() instead of
+ # load_module() alone. Splitting the two steps.
+
+ def _create_module(self, spec: Any) -> Any:
+ return self.loader.create_module(spec)
+
+ def _exec_module(self, module: Any) -> None:
+ self._set_loader(module)
+ self.loader.exec_module(module)
+ notify_module_loaded(module)
+
+
+class ImportHookFinder:
+ def __init__(self) -> None:
+ self.in_progress: Dict = {}
+
+ def find_module( # type: ignore
+ self,
+ fullname: str,
+ path: Optional[str] = None,
+ ) -> Optional["_ImportHookChainedLoader"]:
+ # If the module being imported is not one we have registered
+ # post import hooks for, we can return immediately. We will
+ # take no further part in the importing of this module.
+
+ with _post_import_hooks_lock:
+ if fullname not in _post_import_hooks:
+ return None
+
+ # When we are interested in a specific module, we will call back
+ # into the import system a second time to defer to the import
+ # finder that is supposed to handle the importing of the module.
+ # We set an in progress flag for the target module so that on
+ # the second time through we don't trigger another call back
+ # into the import system and cause a infinite loop.
+
+ if fullname in self.in_progress:
+ return None
+
+ self.in_progress[fullname] = True
+
+ # Now call back into the import system again.
+
+ try:
+ # For Python 3 we need to use find_spec().loader
+ # from the importlib.util module. It doesn't actually
+ # import the target module and only finds the
+ # loader. If a loader is found, we need to return
+ # our own loader which will then in turn call the
+ # real loader to import the module and invoke the
+ # post import hooks.
+ loader = getattr(find_spec(fullname), "loader", None)
+
+ if loader and not isinstance(loader, _ImportHookChainedLoader):
+ return _ImportHookChainedLoader(loader)
+
+ finally:
+ del self.in_progress[fullname]
+
+ def find_spec(
+ self, fullname: str, path: Optional[str] = None, target: Any = None
+ ) -> Any:
+ # Since Python 3.4, you are meant to implement find_spec() method
+ # instead of find_module() and since Python 3.10 you get deprecation
+ # warnings if you don't define find_spec().
+
+ # If the module being imported is not one we have registered
+ # post import hooks for, we can return immediately. We will
+ # take no further part in the importing of this module.
+
+ with _post_import_hooks_lock:
+ if fullname not in _post_import_hooks:
+ return None
+
+ # When we are interested in a specific module, we will call back
+ # into the import system a second time to defer to the import
+ # finder that is supposed to handle the importing of the module.
+ # We set an in progress flag for the target module so that on
+ # the second time through we don't trigger another call back
+ # into the import system and cause a infinite loop.
+
+ if fullname in self.in_progress:
+ return None
+
+ self.in_progress[fullname] = True
+
+ # Now call back into the import system again.
+
+ try:
+ # This should only be Python 3 so find_spec() should always
+ # exist so don't need to check.
+ spec = find_spec(fullname)
+ loader = getattr(spec, "loader", None)
+
+ if loader and not isinstance(loader, _ImportHookChainedLoader):
+ assert spec is not None
+ spec.loader = _ImportHookChainedLoader(loader) # type: ignore
+
+ return spec
+
+ finally:
+ del self.in_progress[fullname]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/interrupt.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/interrupt.py
new file mode 100644
index 0000000000000000000000000000000000000000..19cc0fe914674d1a328b278024c03efef8b61ad9
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/interrupt.py
@@ -0,0 +1,37 @@
+"""Utility to send an interrupt (Ctrl+C) signal to the main thread.
+
+This is necessary because Windows and POSIX use different models for Ctrl+C
+interrupts.
+"""
+
+import platform
+import signal
+import threading
+
+
+def interrupt_main():
+ """Interrupt the main Python thread with a SIGINT signal.
+
+ In POSIX, signal.pthread_kill() is the most reliable way to send a signal
+ to the main thread.
+
+ os.kill() is often recommended, but it isn't guaranteed to deliver the
+ signal to the main OS thread. Likewise, signal.raise_signal() delivers
+ the signal to the current thread in POSIX. The issue is that if any other
+ thread receives the signal, Python will set an internal flag and process it
+ on the main thread at the next opportunity. If the main thread is executing
+ C code or is blocked on a syscall (e.g. time.sleep(999999)) the signal
+ handler won't execute until that's done---i.e. Python won't preempt the OS
+ thread on its own.
+
+ On Windows, pthread_kill is not available and os.kill() ignores its
+ second argument and always kills the process. However,
+ signal.raise_signal() does the right thing.
+ """
+ if platform.system() == "Windows":
+ signal.raise_signal(signal.SIGINT)
+ else:
+ signal.pthread_kill(
+ threading.main_thread().ident,
+ signal.SIGINT,
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/ipython.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/ipython.py
new file mode 100644
index 0000000000000000000000000000000000000000..74022e99e318a7b9f85cc933fcaca59b26207ae4
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/ipython.py
@@ -0,0 +1,126 @@
+import logging
+import sys
+import warnings
+from typing import Literal, Optional
+
+import wandb
+
+PythonType = Literal["python", "ipython", "jupyter"]
+
+logger = logging.getLogger(__name__)
+
+
+def toggle_button(what="run"):
+ """Returns the HTML for a button used to reveal the element following it.
+
+ The element immediately after the button must have `display: none`.
+ """
+ return (
+ ""
+ )
+
+
+def _get_python_type() -> PythonType:
+ if "IPython" not in sys.modules:
+ return "python"
+
+ try:
+ from IPython import get_ipython # type: ignore
+
+ # Calling get_ipython can cause an ImportError
+ if get_ipython() is None:
+ return "python"
+ except ImportError:
+ return "python"
+
+ # jupyter-based environments (e.g. jupyter itself, colab, kaggle, etc) have a connection file
+ ip_kernel_app_connection_file = (
+ (get_ipython().config.get("IPKernelApp", {}) or {})
+ .get("connection_file", "")
+ .lower()
+ ) or (
+ (get_ipython().config.get("ColabKernelApp", {}) or {})
+ .get("connection_file", "")
+ .lower()
+ )
+
+ if (
+ ("terminal" in get_ipython().__module__)
+ or ("jupyter" not in ip_kernel_app_connection_file)
+ or ("spyder" in sys.modules)
+ ):
+ return "ipython"
+ else:
+ return "jupyter"
+
+
+def in_jupyter() -> bool:
+ """Returns True if we're in a Jupyter notebook."""
+ return _get_python_type() == "jupyter"
+
+
+def in_ipython() -> bool:
+ """Returns True if we're running in IPython in the terminal."""
+ return _get_python_type() == "ipython"
+
+
+def in_notebook() -> bool:
+ """Returns True if we're running in Jupyter or IPython."""
+ return _get_python_type() != "python"
+
+
+class ProgressWidget:
+ """A simple wrapper to render a nice progress bar with a label."""
+
+ def __init__(self, widgets, min, max):
+ from IPython import display
+
+ self._ipython_display = display
+
+ self.widgets = widgets
+ self._progress = widgets.FloatProgress(min=min, max=max)
+ self._label = widgets.Label()
+ self._widget = self.widgets.VBox([self._label, self._progress])
+ self._displayed = False
+ self._disabled = False
+
+ def update(self, value: float, label: str) -> None:
+ if self._disabled:
+ return
+ try:
+ self._progress.value = value
+ self._label.value = label
+ if not self._displayed:
+ self._displayed = True
+ self._ipython_display.display(self._widget)
+ except Exception:
+ logger.exception("Error in ProgressWidget.update()")
+ self._disabled = True
+ wandb.termwarn(
+ "Unable to render progress bar, see the user log for details"
+ )
+
+ def close(self) -> None:
+ if self._disabled or not self._displayed:
+ return
+ self._widget.close()
+
+
+def jupyter_progress_bar(min: float = 0, max: float = 1.0) -> Optional[ProgressWidget]:
+ """Return an ipywidget progress bar or None if we can't import it."""
+ widgets = wandb.util.get_module("ipywidgets")
+ try:
+ if widgets is None:
+ # TODO: this currently works in iPython but it's deprecated since 4.0
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ from IPython.html import widgets # type: ignore
+
+ assert hasattr(widgets, "VBox")
+ assert hasattr(widgets, "Label")
+ assert hasattr(widgets, "FloatProgress")
+ return ProgressWidget(widgets, min=min, max=max)
+ except (ImportError, AssertionError):
+ return None
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/json_util.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/json_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..1892e21219bfe062dbd456d05fbd9e8608f9482f
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/json_util.py
@@ -0,0 +1,75 @@
+import json
+import logging
+import os
+from typing import Any, Union
+
+logger = logging.getLogger(__name__)
+
+
+try:
+ import orjson # type: ignore
+
+ # todo: orjson complies with the json standard and does not support
+ # NaN, Infinity, and -Infinity. Should be fixed in the future.
+
+ # additional safeguard for now
+ if os.environ.get("_WANDB_ORJSON"):
+
+ def dumps(obj: Any, **kwargs: Any) -> str:
+ """Wrapper for .dumps."""
+ cls = kwargs.pop("cls", None)
+ try:
+ _kwargs = kwargs.copy()
+ if cls:
+ _kwargs["default"] = cls.default
+ encoded = orjson.dumps(
+ obj, option=orjson.OPT_NON_STR_KEYS, **_kwargs
+ ).decode()
+ except Exception:
+ logger.exception("Error using orjson.dumps")
+ if cls:
+ kwargs["cls"] = cls
+ encoded = json.dumps(obj, **kwargs)
+
+ return encoded # type: ignore[no-any-return]
+
+ def dump(obj: Any, fp: Any, **kwargs: Any) -> None:
+ """Wrapper for .dump."""
+ cls = kwargs.pop("cls", None)
+ try:
+ _kwargs = kwargs.copy()
+ if cls:
+ _kwargs["default"] = cls.default
+ encoded = orjson.dumps(obj, option=orjson.OPT_NON_STR_KEYS, **_kwargs)
+ fp.write(encoded)
+ except Exception:
+ logger.exception("Error using orjson.dump")
+ if cls:
+ kwargs["cls"] = cls
+ json.dump(obj, fp, **kwargs)
+
+ def loads(obj: Union[str, bytes]) -> Any:
+ """Wrapper for orjson.loads."""
+ try:
+ decoded = orjson.loads(obj)
+ except Exception:
+ logger.exception("Error using orjson.loads")
+ decoded = json.loads(obj)
+
+ return decoded
+
+ def load(fp: Any) -> Any:
+ """Wrapper for orjson.load."""
+ try:
+ decoded = orjson.loads(fp.read())
+ except Exception:
+ logger.exception("Error using orjson.load")
+ decoded = json.load(fp)
+
+ return decoded
+
+ else:
+ from json import dump, dumps, load, loads # type: ignore[assignment]
+
+except ImportError:
+ from json import dump, dumps, load, loads # type: ignore[assignment] # noqa: F401
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/lazyloader.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/lazyloader.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c7aec3f94ac6bab37154c3fb796ac0ac63ba9a4
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/lazyloader.py
@@ -0,0 +1,63 @@
+"""module lazyloader."""
+
+import importlib
+import sys
+import types
+
+
+class LazyLoader(types.ModuleType):
+ """Lazily import a module, mainly to avoid pulling in large dependencies.
+
+ We use this for tensorflow and other optional libraries primarily at the
+ top module level.
+ """
+
+ # The lint error here is incorrect.
+ def __init__(
+ self,
+ local_name, # pylint: disable=super-on-old-class
+ parent_module_globals,
+ name,
+ warning=None,
+ ):
+ self._local_name = local_name
+ self._parent_module_globals = parent_module_globals
+ self._warning = warning
+
+ super().__init__(str(name))
+
+ def _load(self):
+ """Load the module and insert it into the parent's globals."""
+ # Import the target module and insert it into the parent's namespace
+ module = importlib.import_module(self.__name__)
+ self._parent_module_globals[self._local_name] = module
+ # print("import", self.__name__)
+ # print("Set global", self._local_name)
+ # print("mod", module)
+ sys.modules[self._local_name] = module
+
+ # Emit a warning if one was specified
+ if self._warning:
+ print(self._warning) # noqa: T201
+ # Make sure to only warn once.
+ self._warning = None
+
+ # Update this object's dict so that if someone keeps a reference to the
+ # LazyLoader, lookups are efficient (__getattr__ is only called on lookups
+ # that fail).
+ self.__dict__.update(module.__dict__)
+
+ return module
+
+ # def __getattribute__(self, item):
+ # print("getattribute", item)
+
+ def __getattr__(self, item):
+ # print("getattr", item)
+ module = self._load()
+ return getattr(module, item)
+
+ def __dir__(self):
+ # print("dir")
+ module = self._load()
+ return dir(module)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/module.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/module.py
new file mode 100644
index 0000000000000000000000000000000000000000..74516737c87aa2f7f09678e085c3817015156f84
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/module.py
@@ -0,0 +1,72 @@
+#
+import wandb
+
+from . import preinit
+
+
+def set_global(
+ run=None,
+ config=None,
+ log=None,
+ summary=None,
+ save=None,
+ use_artifact=None,
+ log_artifact=None,
+ define_metric=None,
+ alert=None,
+ mark_preempting=None,
+ log_model=None,
+ use_model=None,
+ link_model=None,
+ watch=None,
+ unwatch=None,
+):
+ if run:
+ wandb.run = run
+ if config is not None:
+ wandb.config = config
+ if log:
+ wandb.log = log
+ if summary is not None:
+ wandb.summary = summary
+ if save:
+ wandb.save = save
+ if use_artifact:
+ wandb.use_artifact = use_artifact
+ if log_artifact:
+ wandb.log_artifact = log_artifact
+ if define_metric:
+ wandb.define_metric = define_metric
+ if alert:
+ wandb.alert = alert
+ if mark_preempting:
+ wandb.mark_preempting = mark_preempting
+ if log_model:
+ wandb.log_model = log_model
+ if use_model:
+ wandb.use_model = use_model
+ if link_model:
+ wandb.link_model = link_model
+ if watch:
+ wandb.watch = watch
+ if unwatch:
+ wandb.unwatch = unwatch
+
+
+def unset_globals():
+ wandb.run = None
+ wandb.config = preinit.PreInitObject("wandb.config")
+ wandb.summary = preinit.PreInitObject("wandb.summary")
+ wandb.log = preinit.PreInitCallable("wandb.log", wandb.Run.log)
+ wandb.watch = preinit.PreInitCallable("wandb.watch", wandb.Run.watch)
+ wandb.unwatch = preinit.PreInitCallable("wandb.unwatch", wandb.Run.unwatch)
+ wandb.save = preinit.PreInitCallable("wandb.save", wandb.Run.save)
+ wandb.use_artifact = preinit.PreInitCallable(
+ "wandb.use_artifact", wandb.Run.use_artifact
+ )
+ wandb.log_artifact = preinit.PreInitCallable(
+ "wandb.log_artifact", wandb.Run.log_artifact
+ )
+ wandb.define_metric = preinit.PreInitCallable(
+ "wandb.define_metric", wandb.Run.define_metric
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/paths.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/paths.py
new file mode 100644
index 0000000000000000000000000000000000000000..809c7de8566b45ef81e499d9cae22cbee3c37bf4
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/paths.py
@@ -0,0 +1,108 @@
+from __future__ import annotations
+
+import os
+import platform
+from functools import wraps
+from pathlib import PurePath, PurePosixPath
+from typing import Any, Union
+
+from typing_extensions import TypeAlias
+
+# Path _inputs_ should generally accept any kind of path. This is named the same and
+# modeled after the hint defined in the Python standard library's `typeshed`:
+# https://github.com/python/typeshed/blob/0b1cd5989669544866213807afa833a88f649ee7/stdlib/_typeshed/__init__.pyi#L56-L65
+StrPath: TypeAlias = Union[str, "os.PathLike[str]"]
+
+FilePathStr: TypeAlias = str #: A native path to a file on a local filesystem.
+URIStr: TypeAlias = str
+
+
+class LogicalPath(str):
+ """A string that represents a path relative to an artifact or run.
+
+ The format of the string is always as a POSIX path, e.g. "foo/bar.txt".
+
+ A neat trick is that you can use this class as if it were a PurePosixPath. E.g.:
+ ```
+ >>> path = LogicalPath("foo/bar.txt")
+ >>> path.parts
+ ('foo', 'bar.txt')
+ >>> path.parent / "baz.txt"
+ 'foo/baz.txt'
+ >>> type(path.relative_to("foo"))
+ LogicalPath
+ ```
+ """
+
+ # It should probably always be a relative path, but that would be a behavior change.
+ #
+ # These strings used to be the output of `to_forward_slash_path`, which only works
+ # with strings and whose behavior is pretty simple:
+ # ```
+ # if platform.system() == "Windows":
+ # path = path.replace("\\", "/")
+ # ```
+ #
+ # This results in some weird things, such as backslashes being allowed from
+ # non-Windows platforms (which would probably break if such an artifact was used
+ # from Windows) and anchors or absolute paths being allowed. E.g., the Windows path
+ # "C:\foo\bar.txt" becomes "C:/foo/bar.txt", which then would mount as
+ # "./artifacts/artifact_name:v0/C:/foo/bar.txt" on MacOS and as
+ # "./artifacts/artifact_name-v0/C-/foo/bar.txt" on Windows.
+ #
+ # This implementation preserves behavior for strings but attempts to sanitize other
+ # formerly unsupported inputs more aggressively. It uses the `.as_posix()` form of
+ # pathlib objects rather than the `str()` form to reduce how often identical inputs
+ # will result in different outputs on different platforms; however, it doesn't alter
+ # absolute paths or check for prohibited characters etc.
+
+ def __new__(cls, path: StrPath) -> LogicalPath:
+ if isinstance(path, LogicalPath):
+ return super().__new__(cls, path)
+ if hasattr(path, "as_posix"):
+ path = PurePosixPath(path.as_posix())
+ return super().__new__(cls, str(path))
+ if hasattr(path, "__fspath__"):
+ path = path.__fspath__() # Can be str or bytes.
+ if isinstance(path, bytes):
+ path = os.fsdecode(path)
+ # For historical reasons we have to convert backslashes to forward slashes, but
+ # only on Windows, and need to do it before any pathlib operations.
+ if platform.system() == "Windows":
+ path = path.replace("\\", "/")
+ # This weird contortion and the one above are because in some unusual cases
+ # PurePosixPath(path.as_posix()).as_posix() != path.as_posix().
+ path = PurePath(path).as_posix()
+ return super().__new__(cls, str(PurePosixPath(path)))
+
+ def to_path(self) -> PurePosixPath:
+ """Convert this path to a PurePosixPath."""
+ return PurePosixPath(self)
+
+ def __getattr__(self, name: str) -> Any:
+ """Act like a subclass of PurePosixPath for all methods not defined on str."""
+ try:
+ attr = getattr(self.to_path(), name)
+ except AttributeError:
+ classname = type(self).__qualname__
+ raise AttributeError(f"{classname!r} has no attribute {name!r}") from None
+
+ if isinstance(attr, PurePosixPath):
+ return LogicalPath(attr)
+
+ # If the result is a callable (a method), wrap it so that it has the same
+ # behavior: if the call result returns a PurePosixPath, return a LogicalPath.
+ if callable(fn := attr):
+
+ @wraps(fn)
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ if isinstance(res := fn(*args, **kwargs), PurePosixPath):
+ return LogicalPath(res)
+ return res
+
+ return wrapper
+ return attr
+
+ def __truediv__(self, other: StrPath) -> LogicalPath:
+ """Act like a PurePosixPath for the / operator, but return a LogicalPath."""
+ return LogicalPath(self.to_path() / LogicalPath(other))
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/preinit.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/preinit.py
new file mode 100644
index 0000000000000000000000000000000000000000..624528198b1cab580f95d29eb91b0531378041e8
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/preinit.py
@@ -0,0 +1,42 @@
+from typing import Any, Callable, Optional
+
+import wandb
+
+
+class PreInitObject:
+ def __init__(self, name: str, destination: Optional[Any] = None) -> None:
+ self._name = name
+
+ if destination is not None:
+ self.__doc__ = destination.__doc__
+
+ def __getitem__(self, key: str) -> None:
+ raise wandb.Error(f"You must call wandb.init() before {self._name}[{key!r}]")
+
+ def __setitem__(self, key: str, value: Any) -> Any:
+ raise wandb.Error(f"You must call wandb.init() before {self._name}[{key!r}]")
+
+ def __setattr__(self, key: str, value: Any) -> Any:
+ if not key.startswith("_"):
+ raise wandb.Error(f"You must call wandb.init() before {self._name}.{key}")
+ else:
+ return object.__setattr__(self, key, value)
+
+ def __getattr__(self, key: str) -> Any:
+ if not key.startswith("_"):
+ raise wandb.Error(f"You must call wandb.init() before {self._name}.{key}")
+ else:
+ raise AttributeError
+
+
+def PreInitCallable( # noqa: N802
+ name: str, destination: Optional[Any] = None
+) -> Callable:
+ def preinit_wrapper(*args: Any, **kwargs: Any) -> Any:
+ raise wandb.Error(f"You must call wandb.init() before {name}()")
+
+ preinit_wrapper.__name__ = str(name)
+ if destination:
+ preinit_wrapper.__wrapped__ = destination # type: ignore
+ preinit_wrapper.__doc__ = destination.__doc__
+ return preinit_wrapper
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/printer.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/printer.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c24adc70af48d678f13e3e731b1a3fddf396ba1
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/printer.py
@@ -0,0 +1,567 @@
+"""Terminal, Jupyter and file output for W&B."""
+
+from __future__ import annotations
+
+import abc
+import contextlib
+import itertools
+import platform
+import sys
+from typing import Callable, Iterator
+
+import click
+from typing_extensions import override
+
+import wandb
+import wandb.util
+from wandb.errors import term
+from wandb.sdk import wandb_setup
+
+from . import ipython, sparkline
+
+# Follow the same logic as the python logging module
+CRITICAL = 50
+FATAL = CRITICAL
+ERROR = 40
+WARNING = 30
+WARN = WARNING
+INFO = 20
+DEBUG = 10
+NOTSET = 0
+
+_level_to_name = {
+ CRITICAL: "CRITICAL",
+ ERROR: "ERROR",
+ WARNING: "WARNING",
+ INFO: "INFO",
+ DEBUG: "DEBUG",
+ NOTSET: "NOTSET",
+}
+
+_name_to_level = {
+ "CRITICAL": CRITICAL,
+ "FATAL": FATAL,
+ "ERROR": ERROR,
+ "WARN": WARNING,
+ "WARNING": WARNING,
+ "INFO": INFO,
+ "DEBUG": DEBUG,
+ "NOTSET": NOTSET,
+}
+
+_PROGRESS_SYMBOL_ANIMATION = "⢿⣻⣽⣾⣷⣯⣟⡿"
+"""Sequence of characters for a progress spinner.
+
+Unicode characters from the Braille Patterns block arranged
+to form a subtle clockwise spinning animation.
+"""
+
+_PROGRESS_SYMBOL_COLOR = 0xB2
+"""Color from the 256-color palette for the progress symbol."""
+
+_JUPYTER_TABLE_STYLES = """
+
+"""
+
+_JUPYTER_PANEL_STYLES = """
+
+"""
+
+
+def new_printer(settings: wandb.Settings | None = None) -> Printer:
+ """Returns a printer appropriate for the environment we're in.
+
+ Args:
+ settings: The settings of a run. If not provided and `wandb.setup()`
+ has been called, then global settings are used. Otherwise,
+ settings (such as silent mode) are ignored.
+ """
+ if not settings and (s := wandb_setup.singleton().settings_if_loaded):
+ settings = s
+
+ if ipython.in_jupyter():
+ return _PrinterJupyter(settings=settings)
+ else:
+ return _PrinterTerm(settings=settings)
+
+
+class Printer(abc.ABC):
+ """An object that shows styled text to the user."""
+
+ @contextlib.contextmanager
+ @abc.abstractmethod
+ def dynamic_text(self) -> Iterator[DynamicText | None]:
+ """A context manager providing a handle to a block of changeable text.
+
+ Since `wandb` may be outputting to a terminal, it's important to only
+ use this when `wandb` is performing blocking calls, or else text output
+ by non-`wandb` code may get overwritten.
+
+ Returns None if dynamic text is not supported, such as if stderr is not
+ a TTY and we're not in a Jupyter notebook.
+ """
+
+ @abc.abstractmethod
+ def display(
+ self,
+ text: str | list[str] | tuple[str],
+ *,
+ level: str | int | None = None,
+ ) -> None:
+ """Display text to the user.
+
+ Args:
+ text: The text to display. If given an iterable of strings, they're
+ joined with newlines.
+ level: The logging level, for controlling verbosity.
+ """
+
+ @abc.abstractmethod
+ def progress_update(
+ self,
+ text: str,
+ percent_done: float | None = None,
+ ) -> None:
+ r"""Set the text on the progress indicator.
+
+ Args:
+ text: The text to set, which must end with \r.
+ percent_done: The current progress, between 0 and 1.
+ """
+
+ @abc.abstractmethod
+ def progress_close(self) -> None:
+ """Close the progress indicator.
+
+ After this, `progress_update` should not be used.
+ """
+
+ @staticmethod
+ def _sanitize_level(name_or_level: str | int | None) -> int:
+ """Returns the number corresponding to the logging level.
+
+ Args:
+ name_or_level: The logging level passed to `display`.
+
+ Raises:
+ ValueError: if the input is not a valid logging level.
+ """
+ if isinstance(name_or_level, str):
+ try:
+ return _name_to_level[name_or_level.upper()]
+ except KeyError:
+ raise ValueError(
+ f"Unknown level name: {name_or_level}, supported levels: {_name_to_level.keys()}"
+ )
+
+ if isinstance(name_or_level, int):
+ return name_or_level
+
+ if name_or_level is None:
+ return INFO
+
+ raise ValueError(f"Unknown status level {name_or_level}")
+
+ @property
+ @abc.abstractmethod
+ def supports_html(self) -> bool:
+ """Whether text passed to display may contain HTML styling."""
+
+ @property
+ @abc.abstractmethod
+ def supports_unicode(self) -> bool:
+ """Whether text passed to display may contain arbitrary Unicode."""
+
+ def sparklines(self, series: list[int | float]) -> str | None:
+ """Returns a Unicode art representation of the series of numbers.
+
+ Also known as "ASCII art", except this uses non-ASCII
+ Unicode characters.
+
+ Returns None if the output doesn't support Unicode.
+ """
+ if self.supports_unicode:
+ return sparkline.sparkify(series)
+ else:
+ return None
+
+ @abc.abstractmethod
+ def code(self, text: str) -> str:
+ """Returns the text styled like code."""
+
+ @abc.abstractmethod
+ def name(self, text: str) -> str:
+ """Returns the text styled like a run name."""
+
+ @abc.abstractmethod
+ def link(self, link: str, text: str | None = None) -> str:
+ """Returns the text styled like a link.
+
+ Args:
+ link: The target link.
+ text: The text to show for the link. If not set, or if we're not
+ in an environment that supports clickable links,
+ this is ignored.
+ """
+
+ @abc.abstractmethod
+ def secondary_text(self, text: str) -> str:
+ """Returns the text styled to draw less attention."""
+
+ @abc.abstractmethod
+ def loading_symbol(self, tick: int) -> str:
+ """Returns a frame of an animated loading symbol.
+
+ May return an empty string.
+
+ Args:
+ tick: An index into the animation.
+ """
+
+ @abc.abstractmethod
+ def error(self, text: str) -> str:
+ """Returns the text colored like an error."""
+
+ @abc.abstractmethod
+ def emoji(self, name: str) -> str:
+ """Returns the string for a named emoji, or an empty string."""
+
+ @abc.abstractmethod
+ def files(self, text: str) -> str:
+ """Returns the text styled like a file path."""
+
+ @abc.abstractmethod
+ def grid(self, rows: list[list[str]], title: str | None = None) -> str:
+ """Returns a grid of strings with an optional title."""
+
+ @abc.abstractmethod
+ def panel(self, columns: list[str]) -> str:
+ """Returns the column text combined in a compact way."""
+
+
+class DynamicText(abc.ABC):
+ """A handle to a block of text that's allowed to change."""
+
+ @abc.abstractmethod
+ def set_text(self, text: str) -> None:
+ r"""Change the text.
+
+ Args:
+ text: The text to put in the block, with lines separated
+ by \n characters. The text should not end in \n unless
+ a blank line at the end of the block is desired.
+ May include styled output from methods on the Printer
+ that created this.
+ """
+
+
+class _PrinterTerm(Printer):
+ def __init__(self, *, settings: wandb.Settings | None) -> None:
+ super().__init__()
+ self._settings = settings
+ self._progress = itertools.cycle(["-", "\\", "|", "/"])
+
+ @override
+ @contextlib.contextmanager
+ def dynamic_text(self) -> Iterator[DynamicText | None]:
+ if self._settings and self._settings.silent:
+ yield None
+ return
+
+ with term.dynamic_text() as handle:
+ if not handle:
+ yield None
+ else:
+ yield _DynamicTermText(handle)
+
+ @override
+ def display(
+ self,
+ text: str | list[str] | tuple[str],
+ *,
+ level: str | int | None = None,
+ ) -> None:
+ if self._settings and self._settings.silent:
+ return
+
+ text = "\n".join(text) if isinstance(text, (list, tuple)) else text
+ self._display_fn_mapping(level)(text)
+
+ @staticmethod
+ def _display_fn_mapping(level: str | int | None = None) -> Callable[[str], None]:
+ level = Printer._sanitize_level(level)
+
+ if level >= CRITICAL:
+ return wandb.termerror
+ elif ERROR <= level < CRITICAL:
+ return wandb.termerror
+ elif WARNING <= level < ERROR:
+ return wandb.termwarn
+ elif INFO <= level < WARNING:
+ return wandb.termlog
+ elif DEBUG <= level < INFO:
+ return wandb.termlog
+ else:
+ return wandb.termlog
+
+ @override
+ def progress_update(self, text: str, percent_done: float | None = None) -> None:
+ if self._settings and self._settings.silent:
+ return
+
+ wandb.termlog(f"{next(self._progress)} {text}", newline=False)
+
+ @override
+ def progress_close(self) -> None:
+ if self._settings and self._settings.silent:
+ return
+
+ @property
+ @override
+ def supports_html(self) -> bool:
+ return False
+
+ @property
+ @override
+ def supports_unicode(self) -> bool:
+ return wandb.util.is_unicode_safe(sys.stderr)
+
+ @override
+ def code(self, text: str) -> str:
+ ret: str = click.style(text, bold=True)
+ return ret
+
+ @override
+ def name(self, text: str) -> str:
+ ret: str = click.style(text, fg="yellow")
+ return ret
+
+ @override
+ def link(self, link: str, text: str | None = None) -> str:
+ ret: str = click.style(link, fg="blue", underline=True)
+ # ret = f"\x1b[m{text or link}\x1b[0m"
+ # ret = f"\x1b]8;;{link}\x1b\\{ret}\x1b]8;;\x1b\\"
+ return ret
+
+ @override
+ def emoji(self, name: str) -> str:
+ emojis = dict()
+ if platform.system() != "Windows" and wandb.util.is_unicode_safe(sys.stdout):
+ emojis = dict(
+ star="⭐️",
+ broom="🧹",
+ rocket="🚀",
+ gorilla="🦍",
+ turtle="🐢",
+ lightning="️⚡",
+ )
+
+ return emojis.get(name, "")
+
+ @override
+ def secondary_text(self, text: str) -> str:
+ # NOTE: "white" is really a light gray, and is usually distinct
+ # from the terminal's foreground color (i.e. default text color)
+ return click.style(text, fg="white")
+
+ @override
+ def loading_symbol(self, tick: int) -> str:
+ if not self.supports_unicode:
+ return ""
+
+ idx = tick % len(_PROGRESS_SYMBOL_ANIMATION)
+ return click.style(
+ _PROGRESS_SYMBOL_ANIMATION[idx],
+ fg=_PROGRESS_SYMBOL_COLOR,
+ )
+
+ @override
+ def error(self, text: str) -> str:
+ return click.style(text, fg="red")
+
+ @override
+ def files(self, text: str) -> str:
+ ret: str = click.style(text, fg="magenta", bold=True)
+ return ret
+
+ @override
+ def grid(self, rows: list[list[str]], title: str | None = None) -> str:
+ max_len = max(len(row[0]) for row in rows)
+ format_row = " ".join(["{:>{max_len}}", "{}" * (len(rows[0]) - 1)])
+ grid = "\n".join([format_row.format(*row, max_len=max_len) for row in rows])
+ if title:
+ return f"{title}\n{grid}\n"
+ return f"{grid}\n"
+
+ @override
+ def panel(self, columns: list[str]) -> str:
+ return "\n" + "\n".join(columns)
+
+
+class _DynamicTermText(DynamicText):
+ def __init__(self, handle: term.DynamicBlock) -> None:
+ self._handle = handle
+
+ @override
+ def set_text(self, text: str) -> None:
+ self._handle.set_text(text)
+
+
+class _PrinterJupyter(Printer):
+ def __init__(self, *, settings: wandb.Settings | None) -> None:
+ super().__init__()
+ self._settings = settings
+ self._progress = ipython.jupyter_progress_bar()
+
+ from IPython import display
+
+ self._ipython_display = display
+
+ @override
+ @contextlib.contextmanager
+ def dynamic_text(self) -> Iterator[DynamicText | None]:
+ if self._settings and self._settings.silent:
+ yield None
+ return
+
+ handle = self._ipython_display.display(
+ self._ipython_display.HTML(""),
+ display_id=True,
+ )
+
+ if not handle:
+ yield None
+ return
+
+ try:
+ yield _DynamicJupyterText(handle)
+ finally:
+ handle.update(self._ipython_display.HTML(""))
+
+ @override
+ def display(
+ self,
+ text: str | list[str] | tuple[str],
+ *,
+ level: str | int | None = None,
+ ) -> None:
+ if self._settings and self._settings.silent:
+ return
+
+ text = " ".join(text) if isinstance(text, (list, tuple)) else text
+ text = " ".join(text.splitlines())
+ self._ipython_display.display(self._ipython_display.HTML(text))
+
+ @property
+ @override
+ def supports_html(self) -> bool:
+ return True
+
+ @property
+ @override
+ def supports_unicode(self) -> bool:
+ return True
+
+ @override
+ def code(self, text: str) -> str:
+ return f"{text}"
+
+ @override
+ def name(self, text: str) -> str:
+ return f'{text}'
+
+ @override
+ def link(self, link: str, text: str | None = None) -> str:
+ return f'{text or link}'
+
+ @override
+ def emoji(self, name: str) -> str:
+ return ""
+
+ @override
+ def secondary_text(self, text: str) -> str:
+ return text
+
+ @override
+ def loading_symbol(self, tick: int) -> str:
+ return ""
+
+ @override
+ def error(self, text: str) -> str:
+ return f'{text}'
+
+ @override
+ def files(self, text: str) -> str:
+ return f"{text}"
+
+ @override
+ def progress_update(
+ self,
+ text: str,
+ percent_done: float | None = None,
+ ) -> None:
+ if (self._settings and self._settings.silent) or not self._progress:
+ return
+
+ if percent_done is None:
+ percent_done = 1.0
+
+ self._progress.update(percent_done, text)
+
+ @override
+ def progress_close(self) -> None:
+ if self._progress:
+ self._progress.close()
+
+ @override
+ def grid(self, rows: list[list[str]], title: str | None = None) -> str:
+ format_row = "".join(["
", "
{}
" * len(rows[0]), "
"])
+ grid = "".join([format_row.format(*row) for row in rows])
+ grid = f'
' for col in columns])
+ return f'{_JUPYTER_PANEL_STYLES}
{row}
'
+
+
+class _DynamicJupyterText(DynamicText):
+ def __init__(self, handle) -> None:
+ from IPython import display
+
+ self._ipython_to_html = display.HTML
+ self._handle: display.DisplayHandle = handle
+
+ @override
+ def set_text(self, text: str) -> None:
+ text = " ".join(text.splitlines())
+ self._handle.update(self._ipython_to_html(text))
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/printer_asyncio.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/printer_asyncio.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c9305047319b06512cee531adc25e33536fb87c
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/printer_asyncio.py
@@ -0,0 +1,48 @@
+import asyncio
+from typing import Callable, TypeVar
+
+from wandb.sdk import wandb_setup
+from wandb.sdk.lib import asyncio_compat, printer
+
+_T = TypeVar("_T")
+
+
+def run_async_with_spinner(
+ spinner_printer: printer.Printer,
+ text: str,
+ func: Callable[[], _T],
+) -> _T:
+ """Run a slow function while displaying a loading icon.
+
+ Args:
+ spinner_printer: The printer to use to display text.
+ text: The text to display next to the spinner while the function runs.
+ func: The function to run.
+
+ Returns:
+ The result of func.
+ """
+
+ async def _loop_run_with_spinner() -> _T:
+ func_running = asyncio.Event()
+
+ async def update_spinner() -> None:
+ tick = 0
+ with spinner_printer.dynamic_text() as text_area:
+ if text_area:
+ while not func_running.is_set():
+ spinner = spinner_printer.loading_symbol(tick)
+ text_area.set_text(f"{spinner} {text}")
+ tick += 1
+ await asyncio.sleep(0.1)
+ else:
+ spinner_printer.display(text)
+
+ async with asyncio_compat.open_task_group() as group:
+ group.start_soon(update_spinner())
+ res = await asyncio.get_running_loop().run_in_executor(None, func)
+ func_running.set()
+ return res
+
+ asyncer = wandb_setup.singleton().asyncer
+ return asyncer.run(_loop_run_with_spinner)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/progress.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/progress.py
new file mode 100644
index 0000000000000000000000000000000000000000..799dbcc1944eeb23d93ea7a5063980c0a8a46c17
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/progress.py
@@ -0,0 +1,256 @@
+"""Defines an object for printing run progress at the end of a script."""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import time
+from typing import Iterable, Iterator, NoReturn
+
+from wandb.proto import wandb_internal_pb2 as pb
+from wandb.sdk.interface import interface
+from wandb.sdk.lib import asyncio_compat
+
+from . import printer as p
+
+
+async def loop_printing_operation_stats(
+ progress: ProgressPrinter,
+ interface: interface.InterfaceBase,
+) -> None:
+ """Poll and display ongoing tasks in the internal service process.
+
+ This never returns and must be cancelled. This is meant to be used with
+ `mailbox.wait_with_progress()`.
+
+ Args:
+ progress: The printer to update with operation stats.
+ interface: The interface to use to poll for updates.
+
+ Raises:
+ HandleAbandonedError: If the mailbox associated with the interface
+ becomes closed.
+ Exception: Any other problem communicating with the service process.
+ """
+ stats: pb.OperationStats | None = None
+
+ async def loop_update_screen() -> NoReturn:
+ while True:
+ if stats:
+ progress.update(stats)
+ await asyncio.sleep(0.1)
+
+ async def loop_poll_stats() -> NoReturn:
+ nonlocal stats
+ while True:
+ start_time = time.monotonic()
+
+ handle = await interface.deliver_async(
+ pb.Record(
+ request=pb.Request(operations=pb.OperationStatsRequest()),
+ )
+ )
+ result = await handle.wait_async(timeout=None)
+ stats = result.response.operations_response.operation_stats
+
+ elapsed_time = time.monotonic() - start_time
+ if elapsed_time < 0.5:
+ await asyncio.sleep(0.5 - elapsed_time)
+
+ async with asyncio_compat.open_task_group() as task_group:
+ task_group.start_soon(loop_update_screen())
+ task_group.start_soon(loop_poll_stats())
+
+
+@contextlib.contextmanager
+def progress_printer(
+ printer: p.Printer,
+ default_text: str,
+) -> Iterator[ProgressPrinter]:
+ """Context manager providing an object for printing run progress.
+
+ Args:
+ printer: The printer to use.
+ default_text: The text to show if no information is available.
+ """
+ with printer.dynamic_text() as text_area:
+ try:
+ yield ProgressPrinter(
+ printer,
+ text_area,
+ default_text=default_text,
+ )
+ finally:
+ printer.progress_close()
+
+
+class ProgressPrinter:
+ """Displays PollExitResponse results to the user."""
+
+ def __init__(
+ self,
+ printer: p.Printer,
+ progress_text_area: p.DynamicText | None,
+ default_text: str,
+ ) -> None:
+ self._printer = printer
+ self._progress_text_area = progress_text_area
+ self._default_text = default_text
+ self._tick = 0
+ self._last_printed_line = ""
+
+ def update(
+ self,
+ progress: list[pb.PollExitResponse] | pb.OperationStats,
+ ) -> None:
+ """Update the displayed information."""
+ if not progress:
+ return
+
+ if isinstance(progress, pb.OperationStats):
+ self._update_operation_stats([progress])
+ else:
+ self._update_operation_stats(
+ list(response.operation_stats for response in progress)
+ )
+
+ self._tick += 1
+
+ def _update_operation_stats(self, stats_list: list[pb.OperationStats]) -> None:
+ if self._progress_text_area:
+ _DynamicOperationStatsPrinter(
+ self._printer,
+ self._progress_text_area,
+ max_lines=6,
+ loading_symbol=self._printer.loading_symbol(self._tick),
+ default_text=self._default_text,
+ ).display(stats_list)
+
+ else:
+ top_level_operations: list[str] = []
+ extra_operations = 0
+ for stats in stats_list:
+ for op in stats.operations:
+ if len(top_level_operations) < 5:
+ top_level_operations.append(op.desc)
+ else:
+ extra_operations += 1
+
+ line = "; ".join(top_level_operations)
+ if extra_operations > 0:
+ line += f" (+ {extra_operations} more)"
+
+ if line and line != self._last_printed_line:
+ self._printer.display(line)
+ self._last_printed_line = line
+
+
+class _DynamicOperationStatsPrinter:
+ """Single-use object that writes operation stats into a text area."""
+
+ def __init__(
+ self,
+ printer: p.Printer,
+ text_area: p.DynamicText,
+ max_lines: int,
+ loading_symbol: str,
+ default_text: str,
+ ) -> None:
+ self._printer = printer
+ self._text_area = text_area
+ self._max_lines = max_lines
+ self._loading_symbol = loading_symbol
+ self._default_text = default_text
+
+ self._lines: list[str] = []
+ self._ops_shown = 0
+
+ def display(
+ self,
+ stats_list: Iterable[pb.OperationStats],
+ ) -> None:
+ """Show the given stats in the text area."""
+ total_operations = 0
+ for stats in stats_list:
+ for op in stats.operations:
+ self._add_operation(op, is_subtask=False, indent="")
+ total_operations += stats.total_operations
+
+ if self._ops_shown < total_operations:
+ if 1 <= self._max_lines <= len(self._lines):
+ self._lines.pop()
+
+ remaining = total_operations - self._ops_shown
+
+ self._lines.append(f"+ {remaining} more task(s)")
+
+ if len(self._lines) == 0:
+ if self._loading_symbol:
+ self._text_area.set_text(f"{self._loading_symbol} {self._default_text}")
+ else:
+ self._text_area.set_text(self._default_text)
+ else:
+ self._text_area.set_text("\n".join(self._lines))
+
+ def _add_operation(self, op: pb.Operation, is_subtask: bool, indent: str) -> None:
+ """Add the operation to `self._lines`."""
+ if len(self._lines) >= self._max_lines:
+ return
+
+ if not is_subtask:
+ self._ops_shown += 1
+
+ parts = []
+
+ # Subtask indicator.
+ if is_subtask and self._printer.supports_unicode:
+ parts.append("↳")
+
+ # Loading symbol.
+ if self._loading_symbol:
+ parts.append(self._loading_symbol)
+
+ # Task name.
+ parts.append(op.desc)
+
+ # Progress information.
+ if op.progress:
+ parts.append(f"{op.progress}")
+
+ # Task duration.
+ parts.append(f"({_time_to_string(seconds=op.runtime_seconds)})")
+
+ # Error status.
+ self._lines.append(indent + " ".join(parts))
+ if op.error_status:
+ error_word = self._printer.error("ERROR")
+ error_desc = self._printer.secondary_text(op.error_status)
+ subtask_indent = " " if is_subtask else ""
+ self._lines.append(
+ f"{indent}{subtask_indent} {error_word} {error_desc}",
+ )
+
+ # Subtasks.
+ if op.subtasks:
+ subtask_indent = indent + " "
+ for task in op.subtasks:
+ self._add_operation(
+ task,
+ is_subtask=True,
+ indent=subtask_indent,
+ )
+
+
+def _time_to_string(seconds: float) -> str:
+ """Returns a short string representing the duration."""
+ if seconds < 10:
+ return f"{seconds:.1f}s"
+ if seconds < 60:
+ return f"{seconds:.0f}s"
+ if seconds < 60 * 60:
+ minutes = seconds / 60
+ return f"{minutes:.1f}m"
+
+ hours = int(seconds / (60 * 60))
+ minutes = int((seconds / 60) % 60)
+ return f"{hours}h{minutes}m"
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/proto_util.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/proto_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3a24fc33ed51e15959178692324c5bcd23096d1
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/lib/proto_util.py
@@ -0,0 +1,90 @@
+#
+import json
+from typing import TYPE_CHECKING, Any, Dict, Union
+
+from wandb.proto import wandb_internal_pb2 as pb
+
+if TYPE_CHECKING: # pragma: no cover
+ from google.protobuf.internal.containers import RepeatedCompositeFieldContainer
+ from google.protobuf.message import Message
+
+ from wandb.proto import wandb_telemetry_pb2 as tpb
+
+
+def dict_from_proto_list(obj_list: "RepeatedCompositeFieldContainer") -> Dict[str, Any]:
+ result: Dict[str, Any] = {}
+
+ for item in obj_list:
+ # Start from the root of the result dict
+ current_level = result
+
+ if len(item.nested_key) > 0:
+ keys = list(item.nested_key)
+ else:
+ keys = [item.key]
+
+ for key in keys[:-1]:
+ if key not in current_level:
+ current_level[key] = {}
+ # Move the reference deeper into the nested dictionary
+ current_level = current_level[key]
+
+ # Set the value at the final key location, parsing JSON from the value_json field
+ final_key = keys[-1]
+ current_level[final_key] = json.loads(item.value_json)
+
+ return result
+
+
+def _result_from_record(record: "pb.Record") -> "pb.Result":
+ result = pb.Result(uuid=record.uuid, control=record.control)
+ return result
+
+
+def _assign_record_num(record: "pb.Record", record_num: int) -> None:
+ record.num = record_num
+
+
+def _assign_end_offset(record: "pb.Record", end_offset: int) -> None:
+ record.control.end_offset = end_offset
+
+
+def proto_encode_to_dict(
+ pb_obj: Union["tpb.TelemetryRecord", "pb.MetricRecord"],
+) -> Dict[int, Any]:
+ data: Dict[int, Any] = dict()
+ fields = pb_obj.ListFields()
+ for desc, value in fields:
+ if desc.name.startswith("_"):
+ continue
+ if desc.type == desc.TYPE_STRING:
+ data[desc.number] = value
+ elif desc.type == desc.TYPE_INT32:
+ data[desc.number] = value
+ elif desc.type == desc.TYPE_ENUM:
+ data[desc.number] = value
+ elif desc.type == desc.TYPE_MESSAGE:
+ nested = value.ListFields()
+ bool_msg = all(d.type == d.TYPE_BOOL for d, _ in nested)
+ if bool_msg:
+ items = [d.number for d, v in nested if v]
+ if items:
+ data[desc.number] = items
+ else:
+ # TODO: for now this code only handles sub-messages with strings
+ md = {}
+ for d, v in nested:
+ if not v or d.type != d.TYPE_STRING:
+ continue
+ md[d.number] = v
+ data[desc.number] = md
+ return data
+
+
+def message_to_dict(
+ message: "Message",
+) -> Dict[str, Any]:
+ """Convert a protobuf message into a dictionary."""
+ from google.protobuf.json_format import MessageToDict
+
+ return MessageToDict(message, preserving_proto_field_name=True)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_alerts.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_alerts.py
new file mode 100644
index 0000000000000000000000000000000000000000..072547ab219e907efede3399d660817926074490
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_alerts.py
@@ -0,0 +1,12 @@
+#
+from enum import Enum
+
+"""
+Call run.alert() to generate an email or Slack notification programmatically.
+"""
+
+
+class AlertLevel(Enum):
+ INFO = "INFO"
+ WARN = "WARN"
+ ERROR = "ERROR"
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_config.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..35a1693bc55cd674a724d1081756e89c20adeedf
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_config.py
@@ -0,0 +1,323 @@
+"""config."""
+
+import logging
+from typing import Optional
+
+import wandb
+from wandb.util import (
+ _is_artifact_representation,
+ check_dict_contains_nested_artifact,
+ json_friendly_val,
+)
+
+from . import wandb_helper
+from .lib import config_util
+
+logger = logging.getLogger("wandb")
+
+
+# TODO(jhr): consider a callback for persisting changes?
+# if this is done right we might make sure this is pickle-able
+# we might be able to do this on other objects like Run?
+class Config:
+ """Config object.
+
+ Config objects are intended to hold all of the hyperparameters associated
+ with a wandb run and are saved with the run object when `wandb.init` is
+ called.
+
+ We recommend setting the config once when initializing your run by passing
+ the `config` parameter to `init`:
+
+ ```
+ wandb.init(config=my_config_dict)
+ ```
+
+ You can create a file called `config-defaults.yaml`, and it will
+ automatically be loaded as each run's config. You can also pass the name
+ of the file as the `config` parameter to `init`:
+
+ ```
+ wandb.init(config="my_config.yaml")
+ ```
+
+ See https://docs.wandb.com/guides/track/config#file-based-configs.
+
+ Examples:
+ Basic usage
+ ```
+ with wandb.init(config={"epochs": 4}) as run:
+ for x in range(run.config.epochs):
+ # train
+ ```
+
+ Nested values
+ ```
+ with wandb.init(config={"train": {"epochs": 4}}) as run:
+ for x in range(run.config["train"]["epochs"]):
+ # train
+ ```
+
+ Using absl flags
+ ```
+ flags.DEFINE_string("model", None, "model to run") # name, default, help
+ with wandb.init() as run:
+ run.config.update(flags.FLAGS) # adds all absl flags to config
+ ```
+
+ Argparse flags
+ ```python
+ with wandb.init(config={"epochs": 4}) as run:
+ parser = argparse.ArgumentParser()
+ parser.add_argument(
+ "-b",
+ "--batch-size",
+ type=int,
+ default=8,
+ metavar="N",
+ help="input batch size for training (default: 8)",
+ )
+ args = parser.parse_args()
+ run.config.update(args)
+ ```
+
+ Using TensorFlow flags (deprecated in tensorflow v2)
+ ```python
+ flags = tf.app.flags
+ flags.DEFINE_string("data_dir", "/tmp/data")
+ flags.DEFINE_integer("batch_size", 128, "Batch size.")
+
+ with wandb.init() as run:
+ run.config.update(flags.FLAGS)
+ ```
+ """
+
+ def __init__(self):
+ object.__setattr__(self, "_items", dict())
+ object.__setattr__(self, "_locked", dict())
+ object.__setattr__(self, "_users", dict())
+ object.__setattr__(self, "_users_inv", dict())
+ object.__setattr__(self, "_users_cnt", 0)
+ object.__setattr__(self, "_callback", None)
+ object.__setattr__(self, "_settings", None)
+ object.__setattr__(self, "_artifact_callback", None)
+
+ self._load_defaults()
+
+ def _set_callback(self, cb):
+ object.__setattr__(self, "_callback", cb)
+
+ def _set_artifact_callback(self, cb):
+ object.__setattr__(self, "_artifact_callback", cb)
+
+ def _set_settings(self, settings):
+ object.__setattr__(self, "_settings", settings)
+
+ def __repr__(self):
+ return str(dict(self))
+
+ def keys(self):
+ return [k for k in self._items.keys() if not k.startswith("_")]
+
+ def _as_dict(self):
+ return self._items
+
+ def as_dict(self):
+ # TODO: add telemetry, deprecate, then remove
+ return dict(self)
+
+ def __getitem__(self, key):
+ return self._items[key]
+
+ def __iter__(self):
+ return iter(self._items)
+
+ def _check_locked(self, key, ignore_locked=False) -> bool:
+ locked = self._locked.get(key)
+ if locked is not None:
+ locked_user = self._users_inv[locked]
+ if not ignore_locked:
+ wandb.termwarn(
+ f"Config item '{key}' was locked by '{locked_user}' (ignored update)."
+ )
+ return True
+ return False
+
+ def __setitem__(self, key, val):
+ if self._check_locked(key):
+ return
+ with wandb.sdk.lib.telemetry.context() as tel:
+ tel.feature.set_config_item = True
+ self._raise_value_error_on_nested_artifact(val, nested=True)
+ key, val = self._sanitize(key, val)
+ self._items[key] = val
+ logger.info("config set %s = %s - %s", key, val, self._callback)
+ if self._callback:
+ self._callback(key=key, val=val)
+
+ def items(self):
+ return [(k, v) for k, v in self._items.items() if not k.startswith("_")]
+
+ __setattr__ = __setitem__
+
+ def __getattr__(self, key):
+ try:
+ return self.__getitem__(key)
+ except KeyError as ke:
+ raise AttributeError(
+ f"{self.__class__!r} object has no attribute {key!r}"
+ ) from ke
+
+ def __contains__(self, key):
+ return key in self._items
+
+ def _update(self, d, allow_val_change=None, ignore_locked=None):
+ parsed_dict = wandb_helper.parse_config(d)
+ locked_keys = set()
+ for key in list(parsed_dict):
+ if self._check_locked(key, ignore_locked=ignore_locked):
+ locked_keys.add(key)
+ sanitized = self._sanitize_dict(
+ parsed_dict, allow_val_change, ignore_keys=locked_keys
+ )
+ self._items.update(sanitized)
+ return sanitized
+
+ def update(self, d, allow_val_change=None):
+ sanitized = self._update(d, allow_val_change)
+ if self._callback:
+ self._callback(data=sanitized)
+
+ def get(self, *args):
+ return self._items.get(*args)
+
+ def persist(self):
+ """Call the callback if it's set."""
+ if self._callback:
+ self._callback(data=self._as_dict())
+
+ def setdefaults(self, d):
+ d = wandb_helper.parse_config(d)
+ # strip out keys already configured
+ d = {k: v for k, v in d.items() if k not in self._items}
+ d = self._sanitize_dict(d)
+ self._items.update(d)
+ if self._callback:
+ self._callback(data=d)
+
+ def _get_user_id(self, user) -> int:
+ if user not in self._users:
+ self._users[user] = self._users_cnt
+ self._users_inv[self._users_cnt] = user
+ object.__setattr__(self, "_users_cnt", self._users_cnt + 1)
+
+ return self._users[user]
+
+ def update_locked(self, d, user=None, _allow_val_change=None):
+ """Shallow-update config with `d` and lock config updates on d's keys."""
+ num = self._get_user_id(user)
+
+ for k, v in d.items():
+ k, v = self._sanitize(k, v, allow_val_change=_allow_val_change)
+ self._locked[k] = num
+ self._items[k] = v
+
+ if self._callback:
+ self._callback(data=d)
+
+ def merge_locked(self, d, user=None, _allow_val_change=None):
+ """Recursively merge-update config with `d` and lock config updates on d's keys."""
+ num = self._get_user_id(user)
+ callback_d = {}
+
+ for k, v in d.items():
+ k, v = self._sanitize(k, v, allow_val_change=_allow_val_change)
+ self._locked[k] = num
+
+ if (
+ k in self._items
+ and isinstance(self._items[k], dict)
+ and isinstance(v, dict)
+ ):
+ self._items[k] = config_util.merge_dicts(self._items[k], v)
+ else:
+ self._items[k] = v
+
+ callback_d[k] = self._items[k]
+
+ if self._callback:
+ self._callback(data=callback_d)
+
+ def _load_defaults(self):
+ conf_dict = config_util.dict_from_config_file("config-defaults.yaml")
+ if conf_dict is not None:
+ self.update(conf_dict)
+
+ def _sanitize_dict(
+ self,
+ config_dict,
+ allow_val_change=None,
+ ignore_keys: Optional[set] = None,
+ ):
+ sanitized = {}
+ self._raise_value_error_on_nested_artifact(config_dict)
+ for k, v in config_dict.items():
+ if ignore_keys and k in ignore_keys:
+ continue
+ k, v = self._sanitize(k, v, allow_val_change)
+ sanitized[k] = v
+ return sanitized
+
+ def _sanitize(self, key, val, allow_val_change=None):
+ # TODO: enable WBValues in the config in the future
+ # refuse all WBValues which is all Media and Histograms
+ if isinstance(val, wandb.sdk.data_types.base_types.wb_value.WBValue):
+ raise TypeError("WBValue objects cannot be added to the run config")
+ # Let jupyter change config freely by default
+ if self._settings and self._settings._jupyter and allow_val_change is None:
+ allow_val_change = True
+ # We always normalize keys by stripping '-'
+ key = key.strip("-")
+ if _is_artifact_representation(val):
+ val = self._artifact_callback(key, val)
+ # if the user inserts an artifact into the config
+ if not isinstance(val, wandb.Artifact):
+ val = json_friendly_val(val)
+ if not allow_val_change:
+ if key in self._items and val != self._items[key]:
+ raise config_util.ConfigError(
+ f'Attempted to change value of key "{key}" '
+ f"from {self._items[key]} to {val}\n"
+ "If you really want to do this, pass"
+ " allow_val_change=True to config.update()"
+ )
+ return key, val
+
+ def _raise_value_error_on_nested_artifact(self, v, nested=False):
+ # we can't swap nested artifacts because their root key can be locked by other values
+ # best if we don't allow nested artifacts until we can lock nested keys in the config
+ if isinstance(v, dict) and check_dict_contains_nested_artifact(v, nested):
+ raise ValueError(
+ "Instances of wandb.Artifact can only be top level keys in"
+ " a run's config"
+ )
+
+
+class ConfigStatic:
+ def __init__(self, config):
+ object.__setattr__(self, "__dict__", dict(config))
+
+ def __setattr__(self, name, value):
+ raise AttributeError("Error: run.config_static is a readonly object")
+
+ def __setitem__(self, key, val):
+ raise AttributeError("Error: run.config_static is a readonly object")
+
+ def keys(self):
+ return self.__dict__.keys()
+
+ def __getitem__(self, key):
+ return self.__dict__[key]
+
+ def __str__(self):
+ return str(self.__dict__)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_helper.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c5e5250f71b2b96db0e1300653ba1f94d62d682
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_helper.py
@@ -0,0 +1,54 @@
+import inspect
+import types
+
+from wandb.errors import UsageError
+
+from .lib import config_util
+
+
+def parse_config(params, exclude=None, include=None):
+ if exclude and include:
+ raise UsageError("Expected at most only one of exclude or include")
+ if isinstance(params, str):
+ params = config_util.dict_from_config_file(params, must_exist=True)
+ params = _to_dict(params)
+ if include:
+ params = {key: value for key, value in params.items() if key in include}
+ if exclude:
+ params = {key: value for key, value in params.items() if key not in exclude}
+ return params
+
+
+def _to_dict(params):
+ if isinstance(params, dict):
+ return params
+
+ # Handle some cases where params is not a dictionary
+ # by trying to convert it into a dictionary
+ meta = inspect.getmodule(params)
+ if meta:
+ is_tf_flags_module = (
+ isinstance(params, types.ModuleType)
+ and meta.__name__ == "tensorflow.python.platform.flags"
+ )
+ if is_tf_flags_module or meta.__name__ == "absl.flags":
+ params = params.FLAGS
+ meta = inspect.getmodule(params)
+
+ # newer tensorflow flags (post 1.4) uses absl.flags
+ if meta and meta.__name__ == "absl.flags._flagvalues":
+ params = {name: params[name].value for name in dir(params)}
+ elif not hasattr(params, "__dict__"):
+ raise TypeError("config must be a dict or have a __dict__ attribute.")
+ elif "__flags" in vars(params):
+ # for older tensorflow flags (pre 1.4)
+ if not "__parsed" not in vars(params):
+ params._parse_flags()
+ params = vars(params)["__flags"]
+ else:
+ # params is a Namespace object (argparse)
+ # or something else
+ params = vars(params)
+
+ # assume argparse Namespace
+ return params
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_init.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_init.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0de2e78d223d55788a138be41ce306f7c4c6077
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_init.py
@@ -0,0 +1,1601 @@
+"""Defines wandb.init() and associated classes and methods.
+
+`wandb.init()` indicates the beginning of a new run. In an ML training pipeline,
+you could add `wandb.init()` to the beginning of your training script as well as
+your evaluation script, and each step would be tracked as a run in W&B.
+
+For more on using `wandb.init()`, including code snippets, check out our
+[guide and FAQs](https://docs.wandb.ai/guides/track/launch).
+"""
+
+from __future__ import annotations
+
+import contextlib
+import dataclasses
+import json
+import logging
+import os
+import pathlib
+import platform
+import sys
+import tempfile
+import time
+from typing import TYPE_CHECKING, Iterable, Iterator, Sequence
+
+from typing_extensions import Any, Literal, Protocol, Self
+
+import wandb
+import wandb.env
+from wandb import env, trigger
+from wandb.errors import CommError, Error, UsageError
+from wandb.errors.links import url_registry
+from wandb.errors.util import ProtobufErrorHandler
+from wandb.integration import sagemaker, weave
+from wandb.proto.wandb_deprecated import Deprecated
+from wandb.sdk.lib import ipython as wb_ipython
+from wandb.sdk.lib import progress, runid, wb_logging
+from wandb.sdk.lib.paths import StrPath
+from wandb.util import _is_artifact_representation
+
+from . import wandb_login, wandb_setup
+from .backend.backend import Backend
+from .lib import SummaryDisabled, filesystem, module, paths, printer, telemetry
+from .lib.deprecate import deprecate
+from .mailbox import wait_with_progress
+from .wandb_helper import parse_config
+from .wandb_run import Run, TeardownHook, TeardownStage
+from .wandb_settings import Settings
+
+if TYPE_CHECKING:
+ import wandb.jupyter
+
+
+def _huggingface_version() -> str | None:
+ if "transformers" in sys.modules:
+ trans = wandb.util.get_module("transformers")
+ if hasattr(trans, "__version__"):
+ return str(trans.__version__)
+ return None
+
+
+def _handle_launch_config(settings: Settings) -> dict[str, Any]:
+ launch_run_config: dict[str, Any] = {}
+ if not settings.launch:
+ return launch_run_config
+ if os.environ.get("WANDB_CONFIG") is not None:
+ try:
+ launch_run_config = json.loads(os.environ.get("WANDB_CONFIG", "{}"))
+ except (ValueError, SyntaxError):
+ wandb.termwarn("Malformed WANDB_CONFIG, using original config")
+ elif settings.launch_config_path and os.path.exists(settings.launch_config_path):
+ with open(settings.launch_config_path) as fp:
+ launch_config = json.loads(fp.read())
+ launch_run_config = launch_config.get("overrides", {}).get("run_config")
+ else:
+ i = 0
+ chunks = []
+ while True:
+ key = f"WANDB_CONFIG_{i}"
+ if key in os.environ:
+ chunks.append(os.environ[key])
+ i += 1
+ else:
+ break
+ if len(chunks) > 0:
+ config_string = "".join(chunks)
+ try:
+ launch_run_config = json.loads(config_string)
+ except (ValueError, SyntaxError):
+ wandb.termwarn("Malformed WANDB_CONFIG, using original config")
+
+ return launch_run_config
+
+
+@dataclasses.dataclass(frozen=True)
+class _ConfigParts:
+ base_no_artifacts: dict[str, Any]
+ """The run config passed to `init()` minus any artifact-valued keys."""
+
+ sweep_no_artifacts: dict[str, Any]
+ """The config loaded as part of a sweep minus any artifact-valued keys."""
+
+ launch_no_artifacts: dict[str, Any]
+ """The config loaded as part of Launch minus any artifact-valued keys."""
+
+ artifacts: dict[str, Any]
+ """Artifact keys removed from config dictionaries.
+
+ Due to implementation details of how a Run is constructed,
+ artifacts must be inserted into its config after initialization.
+ """
+
+
+class _PrinterCallback(Protocol):
+ """A callback for displaying messages after a printer is configured.
+
+ This is used for a few messages that may be generated before run settings
+ are computed, which are necessary for creating a printer.
+ """
+
+ def __call__(self, run_printer: printer.Printer) -> None:
+ """Display information through the given printer."""
+
+
+def _noop_printer_callback() -> _PrinterCallback:
+ """A printer callback that does not print anything."""
+ return lambda _: None
+
+
+def _concat_printer_callbacks(
+ cbs: Iterable[_PrinterCallback],
+) -> _PrinterCallback:
+ """Returns a printer callback that runs the given callbacks in order."""
+
+ def do_callbacks(run_printer: printer.Printer) -> None:
+ for cb in cbs:
+ cb(run_printer)
+
+ return do_callbacks
+
+
+class _WandbInit:
+ def __init__(
+ self,
+ wl: wandb_setup._WandbSetup,
+ telemetry: telemetry.TelemetryRecord,
+ ) -> None:
+ self._wl = wl
+
+ self._telemetry = telemetry
+ """Telemetry gathered before creating a run.
+
+ After the run is created, `telemetry.context()` is used instead.
+ """
+
+ self.kwargs = None
+ self.run: Run | None = None
+ self.backend: Backend | None = None
+
+ self._teardown_hooks: list[TeardownHook] = []
+ self.notebook: wandb.jupyter.Notebook | None = None
+
+ self.deprecated_features_used: dict[str, str] = dict()
+
+ @property
+ def _logger(self) -> wandb_setup.Logger:
+ return self._wl._get_logger()
+
+ def maybe_login(self, init_settings: Settings) -> None:
+ """Log in if we are not creating an offline or disabled run.
+
+ This may change the W&B singleton settings.
+
+ Args:
+ init_settings: Settings passed to `wandb.init()` or set via
+ keyword arguments.
+ """
+ # Allow settings passed to init() to override inferred values.
+ #
+ # Calling login() may change settings on the singleton,
+ # so these may not be the final run settings.
+ run_settings = self._wl.settings.model_copy()
+ run_settings.update_from_settings(init_settings)
+
+ # NOTE: _noop or _offline can become true after _login().
+ # _noop happens if _login hits a timeout.
+ # _offline can be selected by the user at the login prompt.
+ if run_settings._noop or run_settings._offline:
+ return
+
+ wandb_login._login(
+ anonymous=run_settings.anonymous,
+ host=run_settings.base_url,
+ force=run_settings.force,
+ _disable_warning=True,
+ _silent=run_settings.quiet or run_settings.silent,
+ )
+
+ def warn_env_vars_change_after_setup(self) -> _PrinterCallback:
+ """Warn if environment variables changed after `wandb.setup()`.
+
+ Returns:
+ A callback to print any generated warnings.
+ """
+ if not self._wl.did_environment_change():
+ return _noop_printer_callback()
+
+ def print_warning(run_printer: printer.Printer) -> None:
+ line = (
+ "Changes to your `wandb` environment variables will be ignored "
+ "because your `wandb` session has already started. "
+ "For more information on how to modify your settings with "
+ "`wandb.init()` arguments, please refer to "
+ f"{run_printer.link(url_registry.url('wandb-init'), 'the W&B docs')}."
+ )
+ run_printer.display(line, level="warn")
+
+ return print_warning
+
+ def clear_run_path_if_sweep_or_launch(
+ self,
+ init_settings: Settings,
+ ) -> _PrinterCallback:
+ """Clear project/entity/run_id keys if in a Sweep or a Launch context.
+
+ Args:
+ init_settings: Settings specified in the call to `wandb.init()`.
+
+ Returns:
+ A callback to print any generated warnings.
+ """
+ when_doing_thing = ""
+
+ if self._wl.settings.sweep_id:
+ when_doing_thing = "when running a sweep"
+ elif self._wl.settings.launch:
+ when_doing_thing = "when running from a wandb launch context"
+
+ if not when_doing_thing:
+ return _noop_printer_callback()
+
+ warnings = []
+
+ def warn(key: str, value: str) -> None:
+ warnings.append(f"Ignoring {key} {value!r} {when_doing_thing}.")
+
+ if init_settings.project is not None:
+ warn("project", init_settings.project)
+ init_settings.project = None
+ if init_settings.entity is not None:
+ warn("entity", init_settings.entity)
+ init_settings.entity = None
+ if init_settings.run_id is not None:
+ warn("run_id", init_settings.run_id)
+ init_settings.run_id = None
+
+ def print_warnings(run_printer: printer.Printer) -> None:
+ for warning in warnings:
+ run_printer.display(warning, level="warn")
+
+ return print_warnings
+
+ def make_run_settings(
+ self,
+ init_settings: Settings,
+ ) -> tuple[Settings, _PrinterCallback]:
+ """Returns the run's settings and any warnings.
+
+ Args:
+ init_settings: Settings passed to `wandb.init()` or set via
+ keyword arguments.
+ """
+ warning_callbacks: list[_PrinterCallback] = [
+ self.warn_env_vars_change_after_setup(),
+ self.clear_run_path_if_sweep_or_launch(init_settings),
+ ]
+
+ # Inherit global settings.
+ settings = self._wl.settings.model_copy()
+
+ # Apply settings from wandb.init() call.
+ settings.update_from_settings(init_settings)
+
+ # Infer the run ID from SageMaker.
+ if not settings.sagemaker_disable and sagemaker.is_using_sagemaker():
+ if sagemaker.set_run_id(settings):
+ self._logger.info("set run ID and group based on SageMaker")
+ self._telemetry.feature.sagemaker = True
+
+ # get status of code saving before applying user settings
+ save_code_pre_user_settings = settings.save_code
+ if not settings._offline and not settings._noop:
+ user_settings = self._wl._load_user_settings()
+ if user_settings is not None:
+ settings.update_from_dict(user_settings)
+
+ # ensure that user settings don't set saving to true
+ # if user explicitly set these to false in UI
+ if save_code_pre_user_settings is False:
+ settings.save_code = False
+
+ # TODO: remove this once we refactor the client. This is a temporary
+ # fix to make sure that we use the same project name for wandb-core.
+ # The reason this is not going through the settings object is to
+ # avoid failure cases in other parts of the code that will be
+ # removed with the switch to wandb-core.
+ if settings.project is None:
+ settings.project = wandb.util.auto_project_name(settings.program)
+
+ settings.x_start_time = time.time()
+
+ # In shared mode, generate a unique label if not provided.
+ # The label is used to distinguish between system metrics and console logs
+ # from different writers to the same run.
+ if settings._shared and not settings.x_label:
+ # TODO: If executed in a known distributed environment (e.g. Ray or SLURM),
+ # use the env vars to generate a label (e.g. SLURM_JOB_ID or RANK)
+ prefix = settings.host or ""
+ label = runid.generate_id()
+ settings.x_label = f"{prefix}-{label}" if prefix else label
+
+ return settings, _concat_printer_callbacks(warning_callbacks)
+
+ def _load_autoresume_run_id(self, resume_file: pathlib.Path) -> str | None:
+ """Returns the run_id stored in the auto-resume file, if any.
+
+ Returns `None` if the file does not exist or is not in a valid format.
+
+ Args:
+ resume_file: The file path to use for resume='auto' mode.
+ """
+ if not resume_file.exists():
+ return None
+
+ with resume_file.open() as f:
+ try:
+ return json.load(f)["run_id"]
+
+ except json.JSONDecodeError as e:
+ self._logger.exception(
+ f"could not decode {resume_file}, ignoring",
+ exc_info=e,
+ )
+ return None
+
+ except KeyError:
+ self._logger.exception(
+ f"resume file at {resume_file} did not store a run_id"
+ )
+ return None
+
+ def _save_autoresume_run_id(
+ self,
+ *,
+ resume_file: pathlib.Path,
+ run_id: str,
+ ) -> None:
+ """Write the run ID to the auto-resume file."""
+ resume_file.parent.mkdir(exist_ok=True)
+ with resume_file.open("w") as f:
+ json.dump({"run_id": run_id}, f)
+
+ def set_run_id(self, settings: Settings) -> None:
+ """Set the run ID and possibly save it to the auto-resume file.
+
+ After this, `settings.run_id` is guaranteed to be set.
+
+ If a `resume_from` is provided and `run_id` is not set, initialize
+ `run_id` with the `resume_from` run's `run_id`.
+
+ Args:
+ settings: The run's settings derived from the environment
+ and explicit values passed to `wandb.init()`.
+ """
+ if settings.resume == "auto" and settings.resume_fname:
+ resume_path = pathlib.Path(settings.resume_fname)
+ else:
+ resume_path = None
+
+ if resume_path:
+ previous_id = self._load_autoresume_run_id(resume_path)
+
+ if not previous_id:
+ pass
+ elif settings.run_id is None:
+ self._logger.info(f"loaded run ID from {resume_path}")
+ settings.run_id = previous_id
+ elif settings.run_id != previous_id:
+ wandb.termwarn(
+ f"Ignoring ID {previous_id} loaded due to resume='auto'"
+ f" because the run ID is set to {settings.run_id}.",
+ )
+
+ # If no run ID was inferred, explicitly set, or loaded from an
+ # auto-resume file, then we generate a new ID.
+ if settings.run_id is None:
+ # If resume_from is provided and run_id is not already set,
+ # initialize run_id with the value from resume_from.
+ if settings.resume_from:
+ settings.run_id = settings.resume_from.run
+ else:
+ settings.run_id = runid.generate_id()
+
+ if resume_path:
+ self._save_autoresume_run_id(
+ resume_file=resume_path,
+ run_id=settings.run_id,
+ )
+
+ def set_sync_dir_suffix(self, settings: Settings) -> None:
+ """Add a suffix to sync_dir if it already exists.
+
+ The sync_dir uses a timestamp with second-level precision which can
+ result in conflicts if a run with the same ID is initialized within the
+ same second. This is most likely to happen in tests.
+
+ This can't prevent conflicts from multiple processes attempting
+ to create a wandb run simultaneously.
+
+ Args:
+ settings: Fully initialized settings other than the
+ x_sync_dir_suffix setting which will be modified.
+ """
+ index = 1
+ while pathlib.Path(settings.sync_dir).exists():
+ settings.x_sync_dir_suffix = f"{index}"
+ index += 1
+
+ def make_run_config(
+ self,
+ settings: Settings,
+ config: dict | str | None = None,
+ config_exclude_keys: list[str] | None = None,
+ config_include_keys: list[str] | None = None,
+ ) -> _ConfigParts:
+ """Construct the run's config.
+
+ Args:
+ settings: The run's finalized settings.
+ config: The config passed to `init()`.
+ config_exclude_keys: Deprecated. Keys to filter out from `config`.
+ config_include_keys: Deprecated. Keys to include from `config`.
+
+ Returns:
+ Initial values for the run's config.
+ """
+ if config_exclude_keys:
+ self.deprecated_features_used["init__config_exclude_keys"] = (
+ "config_exclude_keys is deprecated. Use"
+ " `config=wandb.helper.parse_config(config_object,"
+ " exclude=('key',))` instead."
+ )
+ if config_include_keys:
+ self.deprecated_features_used["init__config_include_keys"] = (
+ "config_include_keys is deprecated. Use"
+ " `config=wandb.helper.parse_config(config_object,"
+ " include=('key',))` instead."
+ )
+ config = parse_config(
+ config or dict(),
+ include=config_include_keys,
+ exclude=config_exclude_keys,
+ )
+
+ result = _ConfigParts(
+ base_no_artifacts=dict(),
+ sweep_no_artifacts=dict(),
+ launch_no_artifacts=dict(),
+ artifacts=dict(),
+ )
+
+ if not settings.sagemaker_disable and sagemaker.is_using_sagemaker():
+ sagemaker_config = sagemaker.parse_sm_config()
+ self._split_artifacts_from_config(
+ sagemaker_config,
+ config_target=result.base_no_artifacts,
+ artifacts=result.artifacts,
+ )
+ self._telemetry.feature.sagemaker = True
+
+ if self._wl.config:
+ self._split_artifacts_from_config(
+ self._wl.config,
+ config_target=result.base_no_artifacts,
+ artifacts=result.artifacts,
+ )
+
+ if config and isinstance(config, dict):
+ self._split_artifacts_from_config(
+ config,
+ config_target=result.base_no_artifacts,
+ artifacts=result.artifacts,
+ )
+
+ if self._wl._sweep_config:
+ self._split_artifacts_from_config(
+ self._wl._sweep_config,
+ config_target=result.sweep_no_artifacts,
+ artifacts=result.artifacts,
+ )
+
+ if launch_config := _handle_launch_config(settings):
+ self._split_artifacts_from_config(
+ launch_config,
+ config_target=result.launch_no_artifacts,
+ artifacts=result.artifacts,
+ )
+
+ wandb_internal = result.base_no_artifacts.setdefault("_wandb", dict())
+
+ if settings.save_code and settings.program_relpath:
+ wandb_internal["code_path"] = paths.LogicalPath(
+ os.path.join("code", settings.program_relpath)
+ )
+ if settings.fork_from is not None:
+ wandb_internal["branch_point"] = {
+ "run_id": settings.fork_from.run,
+ "step": settings.fork_from.value,
+ }
+ if settings.resume_from is not None:
+ wandb_internal["branch_point"] = {
+ "run_id": settings.resume_from.run,
+ "step": settings.resume_from.value,
+ }
+
+ return result
+
+ def teardown(self) -> None:
+ # TODO: currently this is only called on failed wandb.init attempts
+ # normally this happens on the run object
+ self._logger.info("tearing down wandb.init")
+ for hook in self._teardown_hooks:
+ hook.call()
+
+ def _split_artifacts_from_config(
+ self,
+ config_source: dict,
+ config_target: dict,
+ artifacts: dict,
+ ) -> None:
+ for k, v in config_source.items():
+ if _is_artifact_representation(v):
+ artifacts[k] = v
+ else:
+ config_target.setdefault(k, v)
+
+ def _safe_symlink(
+ self, base: str, target: str, name: str, delete: bool = False
+ ) -> None:
+ # TODO(jhr): do this with relpaths, but i can't figure it out on no sleep
+ if not hasattr(os, "symlink"):
+ return
+
+ pid = os.getpid()
+ tmp_name = os.path.join(base, f"{name}.{pid}")
+
+ if delete:
+ try:
+ os.remove(os.path.join(base, name))
+ except OSError:
+ pass
+ target = os.path.relpath(target, base)
+ try:
+ os.symlink(target, tmp_name)
+ os.rename(tmp_name, os.path.join(base, name))
+ except OSError:
+ pass
+
+ def _pre_run_cell_hook(self, *args, **kwargs) -> None:
+ """Hook for the IPython pre_run_cell event.
+
+ This pauses a run, preventing system metrics from being collected
+ the run's runtime from increasing. It also uploads the notebook's code.
+ """
+ if not self.backend:
+ return
+
+ if self.notebook and self.notebook.save_ipynb():
+ assert self.run is not None
+ res = self.run.log_code(root=None)
+ self._logger.info("saved code: %s", res)
+
+ if self.backend.interface is not None:
+ self._logger.info("pausing backend")
+ self.backend.interface.publish_pause()
+
+ def _post_run_cell_hook(self, *args, **kwargs) -> None:
+ """Hook for the IPython post_run_cell event.
+
+ Resumes collection of system metrics and the run's timer.
+ """
+ if self.backend is None or self.backend.interface is None:
+ return
+
+ self._logger.info("resuming backend")
+ self.backend.interface.publish_resume()
+
+ def _jupyter_teardown(self) -> None:
+ """Teardown hooks and display saving, called with wandb.finish."""
+ assert self.notebook
+ ipython = self.notebook.shell
+
+ if self.run:
+ self.notebook.save_history(self.run)
+
+ if self.notebook.save_ipynb():
+ assert self.run is not None
+ res = self.run.log_code(root=None)
+ self._logger.info("saved code and history: %s", res)
+ self._logger.info("cleaning up jupyter logic")
+
+ ipython.events.unregister("pre_run_cell", self._pre_run_cell_hook)
+ ipython.events.unregister("post_run_cell", self._post_run_cell_hook)
+
+ ipython.display_pub.publish = ipython.display_pub._orig_publish
+ del ipython.display_pub._orig_publish
+
+ def monkeypatch_ipython(self, settings: Settings) -> None:
+ """Add hooks, and session history saving."""
+ self.notebook = wandb.jupyter.Notebook(settings)
+ ipython = self.notebook.shell
+
+ # Monkey patch ipython publish to capture displayed outputs
+ if not hasattr(ipython.display_pub, "_orig_publish"):
+ self._logger.info("configuring jupyter hooks %s", self)
+ ipython.display_pub._orig_publish = ipython.display_pub.publish
+
+ ipython.events.register("pre_run_cell", self._pre_run_cell_hook)
+ ipython.events.register("post_run_cell", self._post_run_cell_hook)
+
+ self._teardown_hooks.append(
+ TeardownHook(self._jupyter_teardown, TeardownStage.EARLY)
+ )
+
+ def publish(data, metadata=None, **kwargs) -> None:
+ ipython.display_pub._orig_publish(data, metadata=metadata, **kwargs)
+ assert self.notebook is not None
+ self.notebook.save_display(
+ ipython.execution_count, {"data": data, "metadata": metadata}
+ )
+
+ ipython.display_pub.publish = publish
+
+ @contextlib.contextmanager
+ def setup_run_log_directory(self, settings: Settings) -> Iterator[None]:
+ """Set up the run's log directory.
+
+ This is a context manager that closes and unregisters the log handler
+ in case of an uncaught exception, so that future logged messages do not
+ modify this run's log file.
+ """
+ filesystem.mkdir_exists_ok(os.path.dirname(settings.log_user))
+ filesystem.mkdir_exists_ok(os.path.dirname(settings.log_internal))
+ filesystem.mkdir_exists_ok(os.path.dirname(settings.sync_file))
+ filesystem.mkdir_exists_ok(settings.files_dir)
+ filesystem.mkdir_exists_ok(settings._tmp_code_dir)
+
+ if settings.symlink:
+ self._safe_symlink(
+ os.path.dirname(settings.sync_symlink_latest),
+ os.path.dirname(settings.sync_file),
+ os.path.basename(settings.sync_symlink_latest),
+ delete=True,
+ )
+ self._safe_symlink(
+ os.path.dirname(settings.log_symlink_user),
+ settings.log_user,
+ os.path.basename(settings.log_symlink_user),
+ delete=True,
+ )
+ self._safe_symlink(
+ os.path.dirname(settings.log_symlink_internal),
+ settings.log_internal,
+ os.path.basename(settings.log_symlink_internal),
+ delete=True,
+ )
+
+ assert settings.run_id
+ handler = wb_logging.add_file_handler(
+ settings.run_id,
+ pathlib.Path(settings.log_user),
+ )
+
+ if env.is_debug():
+ handler.setLevel(logging.DEBUG)
+
+ disposed = False
+
+ def dispose_handler() -> None:
+ nonlocal disposed
+
+ if not disposed:
+ disposed = True
+ logging.getLogger("wandb").removeHandler(handler)
+ handler.close()
+
+ try:
+ self._teardown_hooks.append(
+ TeardownHook(
+ call=dispose_handler,
+ stage=TeardownStage.LATE,
+ )
+ )
+
+ self._wl._early_logger_flush(logging.getLogger("wandb"))
+ self._logger.info(f"Logging user logs to {settings.log_user}")
+ self._logger.info(f"Logging internal logs to {settings.log_internal}")
+
+ yield
+ except Exception:
+ dispose_handler()
+ raise
+
+ def make_disabled_run(self, config: _ConfigParts) -> Run:
+ """Returns a Run-like object where all methods are no-ops.
+
+ This method is used when the `mode` setting is set to "disabled", such as
+ by wandb.init(mode="disabled") or by setting the WANDB_MODE environment
+ variable to "disabled".
+
+ It creates a Run object that mimics the behavior of a normal Run but doesn't
+ communicate with the W&B servers.
+
+ The returned Run object has all expected attributes and methods, but they
+ are no-op versions that don't perform any actual logging or communication.
+ """
+ run_id = runid.generate_id()
+ drun = Run(
+ settings=Settings(
+ mode="disabled",
+ root_dir=tempfile.gettempdir(),
+ run_id=run_id,
+ run_tags=tuple(),
+ run_notes=None,
+ run_group=None,
+ run_name=f"dummy-{run_id}",
+ project="dummy",
+ entity="dummy",
+ )
+ )
+ # config, summary, and metadata objects
+ drun._config = wandb.sdk.wandb_config.Config()
+ drun._config.update(config.sweep_no_artifacts)
+ drun._config.update(config.base_no_artifacts)
+ drun.summary = SummaryDisabled() # type: ignore
+
+ # methods
+ drun.log = lambda data, *_, **__: drun.summary.update(data) # type: ignore[method-assign]
+ drun.finish = lambda *_, **__: module.unset_globals() # type: ignore[method-assign]
+ drun.join = drun.finish # type: ignore[method-assign]
+ drun.define_metric = lambda *_, **__: wandb.sdk.wandb_metric.Metric("dummy") # type: ignore[method-assign]
+ drun.save = lambda *_, **__: False # type: ignore[method-assign]
+ for symbol in (
+ "alert",
+ "finish_artifact",
+ "get_project_url",
+ "get_sweep_url",
+ "get_url",
+ "link_artifact",
+ "link_model",
+ "use_artifact",
+ "log_code",
+ "log_model",
+ "use_model",
+ "mark_preempting",
+ "restore",
+ "status",
+ "watch",
+ "unwatch",
+ "upsert_artifact",
+ "_finish",
+ ):
+ setattr(drun, symbol, lambda *_, **__: None) # type: ignore
+
+ # set properties to None
+ for attr in ("url", "project_url", "sweep_url"):
+ setattr(type(drun), attr, property(lambda _: None))
+
+ class _ChainableNoOp:
+ """An object that allows chaining arbitrary attributes and method calls."""
+
+ def __getattr__(self, _: str) -> Self:
+ return self
+
+ def __call__(self, *_: Any, **__: Any) -> Self:
+ return self
+
+ class _ChainableNoOpField:
+ # This is used to chain arbitrary attributes and method calls.
+ # For example, `run.log_artifact().state` will work in disabled mode.
+ def __init__(self) -> None:
+ self._value = None
+
+ def __set__(self, instance: Any, value: Any) -> None:
+ self._value = value
+
+ def __get__(self, instance: Any, owner: type) -> Any:
+ return _ChainableNoOp() if (self._value is None) else self._value
+
+ def __call__(self, *args: Any, **kwargs: Any) -> _ChainableNoOp:
+ return _ChainableNoOp()
+
+ drun.log_artifact = _ChainableNoOpField() # type: ignore
+ # attributes
+ drun._start_time = time.time()
+ drun._starting_step = 0
+ drun._step = 0
+ drun._attach_id = None
+ drun._backend = None
+
+ # set the disabled run as the global run
+ module.set_global(
+ run=drun,
+ config=drun.config,
+ log=drun.log,
+ summary=drun.summary,
+ save=drun.save,
+ use_artifact=drun.use_artifact,
+ log_artifact=drun.log_artifact,
+ define_metric=drun.define_metric,
+ alert=drun.alert,
+ watch=drun.watch,
+ unwatch=drun.unwatch,
+ )
+ return drun
+
+ def init( # noqa: C901
+ self,
+ settings: Settings,
+ config: _ConfigParts,
+ run_printer: printer.Printer,
+ ) -> Run:
+ self._logger.info("calling init triggers")
+ trigger.call("on_init")
+
+ assert self._wl is not None
+
+ self._logger.info(
+ f"wandb.init called with sweep_config: {config.sweep_no_artifacts}"
+ f"\nconfig: {config.base_no_artifacts}"
+ )
+
+ if previous_run := self._wl.most_recent_active_run:
+ if (
+ settings.reinit in (True, "finish_previous")
+ # calling wandb.init() in notebooks finishes previous runs
+ # by default for user convenience.
+ or (settings.reinit == "default" and wb_ipython.in_notebook())
+ ):
+ run_printer.display(
+ "Finishing previous runs because reinit is set"
+ f" to {settings.reinit!r}."
+ )
+ self._wl.finish_all_active_runs()
+
+ elif settings.reinit == "create_new":
+ self._logger.info(
+ "wandb.init() called while a run is active,"
+ " and reinit is set to 'create_new', so continuing"
+ )
+
+ elif settings.resume == "must":
+ raise wandb.Error(
+ "Cannot resume a run while another run is active."
+ " You must either finish it using run.finish(),"
+ " or use reinit='create_new' when calling wandb.init()."
+ )
+
+ else:
+ run_printer.display(
+ "wandb.init() called while a run is active and reinit is"
+ f" set to {settings.reinit!r}, so returning the previous"
+ " run."
+ )
+
+ with telemetry.context(run=previous_run) as tel:
+ tel.feature.init_return_run = True
+
+ return previous_run
+
+ self._logger.info("starting backend")
+
+ service = self._wl.ensure_service()
+ self._logger.info("sending inform_init request")
+ service.inform_init(
+ settings=settings.to_proto(),
+ run_id=settings.run_id, # type: ignore
+ )
+
+ backend = Backend(settings=settings, service=service)
+ backend.ensure_launched()
+ self._logger.info("backend started and connected")
+
+ run = Run(
+ config=config.base_no_artifacts,
+ settings=settings,
+ sweep_config=config.sweep_no_artifacts,
+ launch_config=config.launch_no_artifacts,
+ )
+
+ # Populate initial telemetry
+ with telemetry.context(run=run, obj=self._telemetry) as tel:
+ tel.cli_version = wandb.__version__
+ tel.python_version = platform.python_version()
+ tel.platform = f"{platform.system()}-{platform.machine()}".lower()
+ hf_version = _huggingface_version()
+ if hf_version:
+ tel.huggingface_version = hf_version
+ if settings._jupyter:
+ tel.env.jupyter = True
+ if settings._ipython:
+ tel.env.ipython = True
+ if settings._colab:
+ tel.env.colab = True
+ if settings._kaggle:
+ tel.env.kaggle = True
+ if settings._windows:
+ tel.env.windows = True
+
+ if settings.launch:
+ tel.feature.launch = True
+
+ for module_name in telemetry.list_telemetry_imports(only_imported=True):
+ setattr(tel.imports_init, module_name, True)
+
+ if os.environ.get("PEX"):
+ tel.env.pex = True
+
+ if settings._aws_lambda:
+ tel.env.aws_lambda = True
+
+ if settings.x_flow_control_disabled:
+ tel.feature.flow_control_disabled = True
+ if settings.x_flow_control_custom:
+ tel.feature.flow_control_custom = True
+ if settings._shared:
+ wandb.termwarn(
+ "The `shared` mode feature is experimental and may change. "
+ "Please contact support@wandb.com for guidance and to report any issues."
+ )
+ tel.feature.shared_mode = True
+
+ if settings.x_label:
+ tel.feature.user_provided_label = True
+
+ if wandb.env.dcgm_profiling_enabled():
+ tel.feature.dcgm_profiling_enabled = True
+
+ if not settings.label_disable:
+ if self.notebook:
+ run._label_probe_notebook(self.notebook)
+ else:
+ run._label_probe_main()
+
+ for deprecated_feature, msg in self.deprecated_features_used.items():
+ deprecate(
+ field_name=getattr(Deprecated, deprecated_feature),
+ warning_message=msg,
+ run=run,
+ )
+
+ self._logger.info("updated telemetry")
+
+ run._set_library(self._wl)
+ run._set_backend(backend)
+ run._set_teardown_hooks(self._teardown_hooks)
+
+ assert backend.interface
+ backend.interface.publish_header()
+
+ # Using GitRepo() blocks & can be slow, depending on user's current git setup.
+ # We don't want to block run initialization/start request, so populate run's git
+ # info beforehand.
+ if not (settings.disable_git or settings.x_disable_machine_info):
+ run._populate_git_info()
+
+ if settings._offline and settings.resume:
+ wandb.termwarn(
+ "`resume` will be ignored since W&B syncing is set to `offline`. "
+ f"Starting a new run with run id {run.id}."
+ )
+ error: wandb.Error | None = None
+
+ timeout = settings.init_timeout
+
+ self._logger.info(
+ f"communicating run to backend with {timeout} second timeout",
+ )
+
+ run_init_handle = backend.interface.deliver_run(run)
+
+ async def display_init_message() -> None:
+ assert backend.interface
+
+ with progress.progress_printer(
+ run_printer,
+ default_text="Waiting for wandb.init()...",
+ ) as progress_printer:
+ await progress.loop_printing_operation_stats(
+ progress_printer,
+ backend.interface,
+ )
+
+ try:
+ result = wait_with_progress(
+ run_init_handle,
+ timeout=timeout,
+ display_progress=display_init_message,
+ )
+
+ except TimeoutError:
+ run_init_handle.cancel(backend.interface)
+
+ # This may either be an issue with the W&B server (a CommError)
+ # or a bug in the SDK (an Error). We cannot distinguish between
+ # the two causes here.
+ raise CommError(
+ f"Run initialization has timed out after {timeout} sec."
+ " Please try increasing the timeout with the `init_timeout`"
+ " setting: `wandb.init(settings=wandb.Settings(init_timeout=120))`."
+ )
+
+ assert result.run_result
+
+ if error := ProtobufErrorHandler.to_exception(result.run_result.error):
+ raise error
+
+ if not result.run_result.HasField("run"):
+ raise Error("Assertion failed: run_result is missing the run field")
+
+ if result.run_result.run.resumed:
+ self._logger.info("run resumed")
+ with telemetry.context(run=run) as tel:
+ tel.feature.resumed = result.run_result.run.resumed
+ run._set_run_obj(result.run_result.run)
+
+ self._logger.info("starting run threads in backend")
+
+ assert backend.interface
+
+ run_start_handle = backend.interface.deliver_run_start(run)
+ try:
+ # TODO: add progress to let user know we are doing something
+ run_start_handle.wait_or(timeout=30)
+ except TimeoutError:
+ pass
+
+ backend.interface.publish_probe_system_info()
+
+ assert self._wl is not None
+ self.run = run
+
+ run._handle_launch_artifact_overrides()
+ if (
+ settings.launch
+ and settings.launch_config_path
+ and os.path.exists(settings.launch_config_path)
+ ):
+ run.save(settings.launch_config_path)
+ # put artifacts in run config here
+ # since doing so earlier will cause an error
+ # as the run is not upserted
+ for k, v in config.artifacts.items():
+ run.config.update({k: v}, allow_val_change=True)
+ job_artifact = run._launch_artifact_mapping.get(
+ wandb.util.LAUNCH_JOB_ARTIFACT_SLOT_NAME
+ )
+ if job_artifact:
+ run.use_artifact(job_artifact)
+
+ self.backend = backend
+
+ if settings.reinit != "create_new":
+ _set_global_run(run)
+
+ run._on_start()
+ self._logger.info("run started, returning control to user process")
+ return run
+
+
+def _attach(
+ attach_id: str | None = None,
+ run_id: str | None = None,
+ *,
+ run: Run | None = None,
+) -> Run | None:
+ """Attach to a run currently executing in another process/thread.
+
+ Args:
+ attach_id: (str, optional) The id of the run or an attach identifier
+ that maps to a run.
+ run_id: (str, optional) The id of the run to attach to.
+ run: (Run, optional) The run instance to attach
+ """
+ attach_id = attach_id or run_id
+ if not ((attach_id is None) ^ (run is None)):
+ raise UsageError("Either (`attach_id` or `run_id`) or `run` must be specified")
+
+ attach_id = attach_id or (run._attach_id if run else None)
+
+ if attach_id is None:
+ raise UsageError(
+ "Either `attach_id` or `run_id` must be specified or `run` must have `_attach_id`"
+ )
+ wandb._assert_is_user_process() # type: ignore
+
+ _wl = wandb_setup.singleton()
+ logger = _wl._get_logger()
+
+ service = _wl.ensure_service()
+
+ try:
+ attach_settings = service.inform_attach(attach_id=attach_id)
+ except Exception as e:
+ raise UsageError(f"Unable to attach to run {attach_id}") from e
+
+ settings = _wl.settings.model_copy()
+ settings.update_from_dict(
+ {
+ "run_id": attach_id,
+ "x_start_time": attach_settings.x_start_time.value,
+ "mode": attach_settings.mode.value,
+ }
+ )
+
+ # TODO: consolidate this codepath with wandb.init()
+ backend = Backend(settings=settings, service=service)
+ backend.ensure_launched()
+ logger.info("attach backend started and connected")
+
+ if run is None:
+ run = Run(settings=settings)
+ else:
+ run._init(settings=settings)
+ run._set_library(_wl)
+ run._set_backend(backend)
+ assert backend.interface
+
+ attach_handle = backend.interface.deliver_attach(attach_id)
+ try:
+ # TODO: add progress to let user know we are doing something
+ attach_result = attach_handle.wait_or(timeout=30)
+ except TimeoutError:
+ raise UsageError("Timeout attaching to run")
+
+ attach_response = attach_result.response.attach_response
+ if attach_response.error and attach_response.error.message:
+ raise UsageError(f"Failed to attach to run: {attach_response.error.message}")
+
+ run._set_run_obj(attach_response.run)
+ _set_global_run(run)
+ run._on_attach()
+ return run
+
+
+def _set_global_run(run: Run) -> None:
+ """Set `wandb.run` and point some top-level functions to its methods.
+
+ Args:
+ run: The run to make global.
+ """
+ module.set_global(
+ run=run,
+ config=run.config,
+ log=run.log,
+ summary=run.summary,
+ save=run.save,
+ use_artifact=run.use_artifact,
+ log_artifact=run.log_artifact,
+ define_metric=run.define_metric,
+ alert=run.alert,
+ watch=run.watch,
+ unwatch=run.unwatch,
+ mark_preempting=run.mark_preempting,
+ log_model=run.log_model,
+ use_model=run.use_model,
+ link_model=run.link_model,
+ )
+
+
+def _monkeypatch_openai_gym() -> None:
+ """Patch OpenAI gym to log to the global `wandb.run`."""
+ if len(wandb.patched["gym"]) > 0:
+ return
+
+ from wandb.integration import gym
+
+ gym.monitor()
+
+
+def _monkeypatch_tensorboard() -> None:
+ """Patch TensorBoard to log to the global `wandb.run`."""
+ if len(wandb.patched["tensorboard"]) > 0:
+ return
+
+ from wandb.integration import tensorboard as tb_module
+
+ tb_module.patch()
+
+
+def try_create_root_dir(settings: Settings) -> None:
+ """Try to create the root directory specified in settings.
+
+ If creation fails due to permissions or other errors,
+ falls back to using the system temp directory.
+
+ Args:
+ settings: The runs settings containing root_dir configuration.
+ This function may update the root_dir to a temporary directory
+ if the parent directory is not writable.
+ """
+ fallback_to_temp_dir = False
+
+ try:
+ os.makedirs(settings.root_dir, exist_ok=True)
+ except OSError:
+ wandb.termwarn(
+ f"Unable to create root directory {settings.root_dir}",
+ repeat=False,
+ )
+ fallback_to_temp_dir = True
+ else:
+ if not os.access(settings.root_dir, os.W_OK | os.R_OK):
+ wandb.termwarn(
+ f"Path {settings.root_dir} wasn't read/writable",
+ repeat=False,
+ )
+ fallback_to_temp_dir = True
+
+ if not fallback_to_temp_dir:
+ return
+
+ tmp_dir = tempfile.gettempdir()
+ if not os.access(tmp_dir, os.W_OK | os.R_OK):
+ raise ValueError(
+ f"System temp directory ({tmp_dir}) is not writable/readable, "
+ "please set the `dir` argument in `wandb.init()` to a writable/readable directory."
+ )
+
+ settings.root_dir = tmp_dir
+ wandb.termwarn(
+ f"Falling back to temporary directory {tmp_dir}.",
+ repeat=False,
+ )
+ os.makedirs(settings.root_dir, exist_ok=True)
+
+
+def init( # noqa: C901
+ entity: str | None = None,
+ project: str | None = None,
+ dir: StrPath | None = None,
+ id: str | None = None,
+ name: str | None = None,
+ notes: str | None = None,
+ tags: Sequence[str] | None = None,
+ config: dict[str, Any] | str | None = None,
+ config_exclude_keys: list[str] | None = None,
+ config_include_keys: list[str] | None = None,
+ allow_val_change: bool | None = None,
+ group: str | None = None,
+ job_type: str | None = None,
+ mode: Literal["online", "offline", "disabled", "shared"] | None = None,
+ force: bool | None = None,
+ anonymous: Literal["never", "allow", "must"] | None = None,
+ reinit: (
+ bool
+ | Literal[
+ None,
+ "default",
+ "return_previous",
+ "finish_previous",
+ "create_new",
+ ]
+ ) = None,
+ resume: bool | Literal["allow", "never", "must", "auto"] | None = None,
+ resume_from: str | None = None,
+ fork_from: str | None = None,
+ save_code: bool | None = None,
+ tensorboard: bool | None = None,
+ sync_tensorboard: bool | None = None,
+ monitor_gym: bool | None = None,
+ settings: Settings | dict[str, Any] | None = None,
+) -> Run:
+ r"""Start a new run to track and log to W&B.
+
+ In an ML training pipeline, you could add `wandb.init()` to the beginning of
+ your training script as well as your evaluation script, and each piece would
+ be tracked as a run in W&B.
+
+ `wandb.init()` spawns a new background process to log data to a run, and it
+ also syncs data to https://wandb.ai by default, so you can see your results
+ in real-time. When you're done logging data, call `wandb.Run.finish()` to end the run.
+ If you don't call `run.finish()`, the run will end when your script exits.
+
+ Run IDs must not contain any of the following special characters `/ \ # ? % :`
+
+ Args:
+ entity: The username or team name the runs are logged to.
+ The entity must already exist, so ensure you create your account
+ or team in the UI before starting to log runs. If not specified, the
+ run will default your default entity. To change the default entity,
+ go to your settings and update the
+ "Default location to create new projects" under "Default team".
+ project: The name of the project under which this run will be logged.
+ If not specified, we use a heuristic to infer the project name based
+ on the system, such as checking the git root or the current program
+ file. If we can't infer the project name, the project will default to
+ `"uncategorized"`.
+ dir: The absolute path to the directory where experiment logs and
+ metadata files are stored. If not specified, this defaults
+ to the `./wandb` directory. Note that this does not affect the
+ location where artifacts are stored when calling `download()`.
+ id: A unique identifier for this run, used for resuming. It must be unique
+ within the project and cannot be reused once a run is deleted. For
+ a short descriptive name, use the `name` field,
+ or for saving hyperparameters to compare across runs, use `config`.
+ name: A short display name for this run, which appears in the UI to help
+ you identify it. By default, we generate a random two-word name
+ allowing easy cross-reference runs from table to charts. Keeping these
+ run names brief enhances readability in chart legends and tables. For
+ saving hyperparameters, we recommend using the `config` field.
+ notes: A detailed description of the run, similar to a commit message in
+ Git. Use this argument to capture any context or details that may
+ help you recall the purpose or setup of this run in the future.
+ tags: A list of tags to label this run in the UI. Tags are helpful for
+ organizing runs or adding temporary identifiers like "baseline" or
+ "production." You can easily add, remove tags, or filter by tags in
+ the UI.
+ If resuming a run, the tags provided here will replace any existing
+ tags. To add tags to a resumed run without overwriting the current
+ tags, use `run.tags += ("new_tag",)` after calling `run = wandb.init()`.
+ config: Sets `wandb.config`, a dictionary-like object for storing input
+ parameters to your run, such as model hyperparameters or data
+ preprocessing settings.
+ The config appears in the UI in an overview page, allowing you to
+ group, filter, and sort runs based on these parameters.
+ Keys should not contain periods (`.`), and values should be
+ smaller than 10 MB.
+ If a dictionary, `argparse.Namespace`, or `absl.flags.FLAGS` is
+ provided, the key-value pairs will be loaded directly into
+ `wandb.config`.
+ If a string is provided, it is interpreted as a path to a YAML file,
+ from which configuration values will be loaded into `wandb.config`.
+ config_exclude_keys: A list of specific keys to exclude from `wandb.config`.
+ config_include_keys: A list of specific keys to include in `wandb.config`.
+ allow_val_change: Controls whether config values can be modified after their
+ initial set. By default, an exception is raised if a config value is
+ overwritten. For tracking variables that change during training, such as
+ a learning rate, consider using `wandb.log()` instead. By default, this
+ is `False` in scripts and `True` in Notebook environments.
+ group: Specify a group name to organize individual runs as part of a larger
+ experiment. This is useful for cases like cross-validation or running
+ multiple jobs that train and evaluate a model on different test sets.
+ Grouping allows you to manage related runs collectively in the UI,
+ making it easy to toggle and review results as a unified experiment.
+ job_type: Specify the type of run, especially helpful when organizing runs
+ within a group as part of a larger experiment. For example, in a group,
+ you might label runs with job types such as "train" and "eval".
+ Defining job types enables you to easily filter and group similar runs
+ in the UI, facilitating direct comparisons.
+ mode: Specifies how run data is managed, with the following options:
+ - `"online"` (default): Enables live syncing with W&B when a network
+ connection is available, with real-time updates to visualizations.
+ - `"offline"`: Suitable for air-gapped or offline environments; data
+ is saved locally and can be synced later. Ensure the run folder
+ is preserved to enable future syncing.
+ - `"disabled"`: Disables all W&B functionality, making the run’s methods
+ no-ops. Typically used in testing to bypass W&B operations.
+ - `"shared"`: (This is an experimental feature). Allows multiple processes,
+ possibly on different machines, to simultaneously log to the same run.
+ In this approach you use a primary node and one or more worker nodes
+ to log data to the same run. Within the primary node you
+ initialize a run. For each worker node, initialize a run
+ using the run ID used by the primary node.
+ force: Determines if a W&B login is required to run the script. If `True`,
+ the user must be logged in to W&B; otherwise, the script will not
+ proceed. If `False` (default), the script can proceed without a login,
+ switching to offline mode if the user is not logged in.
+ anonymous: Specifies the level of control over anonymous data logging.
+ Available options are:
+ - `"never"` (default): Requires you to link your W&B account before
+ tracking the run. This prevents unintentional creation of anonymous
+ runs by ensuring each run is associated with an account.
+ - `"allow"`: Enables a logged-in user to track runs with their account,
+ but also allows someone running the script without a W&B account
+ to view the charts and data in the UI.
+ - `"must"`: Forces the run to be logged to an anonymous account, even
+ if the user is logged in.
+ reinit: Shorthand for the "reinit" setting. Determines the behavior of
+ `wandb.init()` when a run is active.
+ resume: Controls the behavior when resuming a run with the specified `id`.
+ Available options are:
+ - `"allow"`: If a run with the specified `id` exists, it will resume
+ from the last step; otherwise, a new run will be created.
+ - `"never"`: If a run with the specified `id` exists, an error will
+ be raised. If no such run is found, a new run will be created.
+ - `"must"`: If a run with the specified `id` exists, it will resume
+ from the last step. If no run is found, an error will be raised.
+ - `"auto"`: Automatically resumes the previous run if it crashed on
+ this machine; otherwise, starts a new run.
+ - `True`: Deprecated. Use `"auto"` instead.
+ - `False`: Deprecated. Use the default behavior (leaving `resume`
+ unset) to always start a new run.
+ If `resume` is set, `fork_from` and `resume_from` cannot be
+ used. When `resume` is unset, the system will always start a new run.
+ resume_from: Specifies a moment in a previous run to resume a run from,
+ using the format `{run_id}?_step={step}`. This allows users to truncate
+ the history logged to a run at an intermediate step and resume logging
+ from that step. The target run must be in the same project.
+ If an `id` argument is also provided, the `resume_from` argument will
+ take precedence.
+ `resume`, `resume_from` and `fork_from` cannot be used together, only
+ one of them can be used at a time.
+ Note that this feature is in beta and may change in the future.
+ fork_from: Specifies a point in a previous run from which to fork a new
+ run, using the format `{id}?_step={step}`. This creates a new run that
+ resumes logging from the specified step in the target run’s history.
+ The target run must be part of the current project.
+ If an `id` argument is also provided, it must be different from the
+ `fork_from` argument, an error will be raised if they are the same.
+ `resume`, `resume_from` and `fork_from` cannot be used together, only
+ one of them can be used at a time.
+ Note that this feature is in beta and may change in the future.
+ save_code: Enables saving the main script or notebook to W&B, aiding in
+ experiment reproducibility and allowing code comparisons across runs in
+ the UI. By default, this is disabled, but you can change the default to
+ enable on your settings page.
+ tensorboard: Deprecated. Use `sync_tensorboard` instead.
+ sync_tensorboard: Enables automatic syncing of W&B logs from TensorBoard
+ or TensorBoardX, saving relevant event files for viewing in
+ the W&B UI.
+ monitor_gym: Enables automatic logging of videos of the environment when
+ using OpenAI Gym.
+ settings: Specifies a dictionary or `wandb.Settings` object with advanced
+ settings for the run.
+
+ Returns:
+ A `Run` object.
+
+ Raises:
+ Error: If some unknown or internal error happened during the run
+ initialization.
+ AuthenticationError: If the user failed to provide valid credentials.
+ CommError: If there was a problem communicating with the WandB server.
+ UsageError: If the user provided invalid arguments.
+ KeyboardInterrupt: If user interrupts the run.
+
+ Examples:
+ `wandb.init()` returns a `Run` object. Use the run object to log data,
+ save artifacts, and manage the run lifecycle.
+
+ ```python
+ import wandb
+
+ config = {"lr": 0.01, "batch_size": 32}
+ with wandb.init(config=config) as run:
+ # Log accuracy and loss to the run
+ acc = 0.95 # Example accuracy
+ loss = 0.05 # Example loss
+ run.log({"accuracy": acc, "loss": loss})
+ ```
+ """
+ wandb._assert_is_user_process() # type: ignore
+
+ init_telemetry = telemetry.TelemetryRecord()
+
+ init_settings = Settings()
+ if isinstance(settings, dict):
+ init_settings = Settings(**settings)
+ elif isinstance(settings, Settings):
+ init_settings = settings
+
+ # Explicit function arguments take precedence over settings
+ if job_type is not None:
+ init_settings.run_job_type = job_type
+ if dir is not None:
+ init_settings.root_dir = dir # type: ignore
+ if project is not None:
+ init_settings.project = project
+ if entity is not None:
+ init_settings.entity = entity
+ if reinit is not None:
+ init_settings.reinit = reinit
+ if tags is not None:
+ init_settings.run_tags = tuple(tags)
+ if group is not None:
+ init_settings.run_group = group
+ if name is not None:
+ init_settings.run_name = name
+ if notes is not None:
+ init_settings.run_notes = notes
+ if anonymous is not None:
+ init_settings.anonymous = anonymous # type: ignore
+ if mode is not None:
+ init_settings.mode = mode # type: ignore
+ if resume is not None:
+ init_settings.resume = resume # type: ignore
+ if force is not None:
+ init_settings.force = force
+ # TODO: deprecate "tensorboard" in favor of "sync_tensorboard"
+ if tensorboard is not None:
+ init_settings.sync_tensorboard = tensorboard
+ if sync_tensorboard is not None:
+ init_settings.sync_tensorboard = sync_tensorboard
+ if save_code is not None:
+ init_settings.save_code = save_code
+ if id is not None:
+ init_settings.run_id = id
+ if fork_from is not None:
+ init_settings.fork_from = fork_from # type: ignore
+ if resume_from is not None:
+ init_settings.resume_from = resume_from # type: ignore
+
+ if config is not None:
+ init_telemetry.feature.set_init_config = True
+
+ wl: wandb_setup._WandbSetup | None = None
+
+ try:
+ wl = wandb_setup.singleton()
+
+ wi = _WandbInit(wl, init_telemetry)
+
+ wi.maybe_login(init_settings)
+ run_settings, show_warnings = wi.make_run_settings(init_settings)
+
+ if isinstance(run_settings.reinit, bool):
+ wi.deprecated_features_used["run__reinit_bool"] = (
+ "Using a boolean value for 'reinit' is deprecated."
+ " Use 'return_previous' or 'finish_previous' instead."
+ )
+
+ if run_settings.run_id is not None:
+ init_telemetry.feature.set_init_id = True
+ if run_settings.run_name is not None:
+ init_telemetry.feature.set_init_name = True
+ if run_settings.run_tags is not None:
+ init_telemetry.feature.set_init_tags = True
+ if run_settings._offline:
+ init_telemetry.feature.offline = True
+ if run_settings.fork_from is not None:
+ init_telemetry.feature.fork_mode = True
+ if run_settings.resume_from is not None:
+ init_telemetry.feature.rewind_mode = True
+
+ wi.set_run_id(run_settings)
+ wi.set_sync_dir_suffix(run_settings)
+ run_printer = printer.new_printer(run_settings)
+ show_warnings(run_printer)
+
+ with contextlib.ExitStack() as exit_stack:
+ exit_stack.enter_context(wb_logging.log_to_run(run_settings.run_id))
+
+ run_config = wi.make_run_config(
+ settings=run_settings,
+ config=config,
+ config_exclude_keys=config_exclude_keys,
+ config_include_keys=config_include_keys,
+ )
+
+ if run_settings._noop:
+ return wi.make_disabled_run(run_config)
+
+ try_create_root_dir(run_settings)
+ exit_stack.enter_context(wi.setup_run_log_directory(run_settings))
+
+ if run_settings._jupyter:
+ wi.monkeypatch_ipython(run_settings)
+
+ if monitor_gym:
+ _monkeypatch_openai_gym()
+
+ if wandb.patched["tensorboard"]:
+ # NOTE: The user may have called the patch function directly.
+ init_telemetry.feature.tensorboard_patch = True
+ if run_settings.sync_tensorboard:
+ _monkeypatch_tensorboard()
+ init_telemetry.feature.tensorboard_sync = True
+
+ if run_settings.x_server_side_derived_summary:
+ init_telemetry.feature.server_side_derived_summary = True
+
+ run = wi.init(run_settings, run_config, run_printer)
+
+ # Set up automatic Weave integration if Weave is installed
+ weave.setup(run_settings.entity, run_settings.project)
+
+ return run
+
+ except KeyboardInterrupt as e:
+ if wl:
+ wl._get_logger().warning("interrupted", exc_info=e)
+
+ raise
+
+ except Exception as e:
+ if wl:
+ wl._get_logger().exception("error in wandb.init()", exc_info=e)
+
+ # Need to build delay into this sentry capture because our exit hooks
+ # mess with sentry's ability to send out errors before the program ends.
+ wandb._sentry.reraise(e)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_login.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_login.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8b113a47ef6fca306c33424b1d4f4b2b7f103b9
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_login.py
@@ -0,0 +1,358 @@
+"""Log in to Weights & Biases.
+
+This authenticates your machine to log data to your account.
+"""
+
+import enum
+import os
+from typing import Literal, Optional, Tuple
+
+import click
+from requests.exceptions import ConnectionError
+
+import wandb
+from wandb.errors import AuthenticationError, UsageError
+from wandb.old.settings import Settings as OldSettings
+from wandb.sdk import wandb_setup
+
+from ..apis import InternalApi
+from .internal.internal_api import Api
+from .lib import apikey
+
+
+def _handle_host_wandb_setting(host: Optional[str], cloud: bool = False) -> None:
+ """Write the host parameter to the global settings file.
+
+ This takes the parameter from wandb.login or wandb login for use by the
+ application's APIs.
+ """
+ _api = InternalApi()
+ if host == "https://api.wandb.ai" or (host is None and cloud):
+ _api.clear_setting("base_url", globally=True, persist=True)
+ # To avoid writing an empty local settings file, we only clear if it exists
+ if os.path.exists(OldSettings._local_path()):
+ _api.clear_setting("base_url", persist=True)
+ elif host:
+ host = host.rstrip("/")
+ # force relogin if host is specified
+ _api.set_setting("base_url", host, globally=True, persist=True)
+
+
+def login(
+ anonymous: Optional[Literal["must", "allow", "never"]] = None,
+ key: Optional[str] = None,
+ relogin: Optional[bool] = None,
+ host: Optional[str] = None,
+ force: Optional[bool] = None,
+ timeout: Optional[int] = None,
+ verify: bool = False,
+ referrer: Optional[str] = None,
+) -> bool:
+ """Set up W&B login credentials.
+
+ By default, this will only store credentials locally without
+ verifying them with the W&B server. To verify credentials, pass
+ `verify=True`.
+
+ Args:
+ anonymous: Set to "must", "allow", or "never".
+ If set to "must", always log a user in anonymously. If set to
+ "allow", only create an anonymous user if the user
+ isn't already logged in. If set to "never", never log a
+ user anonymously. Default set to "never". Defaults to `None`.
+ key: The API key to use.
+ relogin: If true, will re-prompt for API key.
+ host: The host to connect to.
+ force: If true, will force a relogin.
+ timeout: Number of seconds to wait for user input.
+ verify: Verify the credentials with the W&B server.
+ referrer: The referrer to use in the URL login request.
+
+
+ Returns:
+ bool: If `key` is configured.
+
+ Raises:
+ AuthenticationError: If `api_key` fails verification with the server.
+ UsageError: If `api_key` cannot be configured and no tty.
+ """
+ _handle_host_wandb_setting(host)
+ logged_in, _ = _login(
+ anonymous=anonymous,
+ key=key,
+ relogin=relogin,
+ host=host,
+ force=force,
+ timeout=timeout,
+ verify=verify,
+ referrer=referrer,
+ )
+ return logged_in
+
+
+class ApiKeyStatus(enum.Enum):
+ VALID = 1
+ NOTTY = 2
+ OFFLINE = 3
+ DISABLED = 4
+
+
+class _WandbLogin:
+ def __init__(
+ self,
+ anonymous: Optional[Literal["must", "allow", "never"]] = None,
+ force: Optional[bool] = None,
+ host: Optional[str] = None,
+ key: Optional[str] = None,
+ relogin: Optional[bool] = None,
+ timeout: Optional[int] = None,
+ ):
+ self._relogin = relogin
+
+ login_settings = {
+ "anonymous": anonymous,
+ "api_key": key,
+ "base_url": host,
+ "force": force,
+ "login_timeout": timeout,
+ }
+ self.is_anonymous = anonymous == "must"
+
+ self._wandb_setup = wandb_setup.singleton()
+ self._wandb_setup.settings.update_from_dict(login_settings)
+ self._settings = self._wandb_setup.settings
+
+ def _update_global_anonymous_setting(self) -> None:
+ api = InternalApi()
+ if self.is_anonymous:
+ api.set_setting("anonymous", "must", globally=True, persist=True)
+ else:
+ api.clear_setting("anonymous", globally=True, persist=True)
+
+ def is_apikey_configured(self) -> bool:
+ """Returns whether an API key is set or can be inferred."""
+ return apikey.api_key(settings=self._settings) is not None
+
+ def _print_logged_in_message(self) -> None:
+ """Prints a message telling the user they are logged in."""
+ username = self._wandb_setup._get_username()
+
+ if username:
+ host_str = (
+ f" to {click.style(self._settings.base_url, fg='green')}"
+ if self._settings.base_url
+ else ""
+ )
+
+ # check to see if we got an entity from the setup call or from the user
+ entity = self._settings.entity or self._wandb_setup._get_entity()
+
+ entity_str = ""
+ # check if entity exist, valid (is part of a certain team) and different from the username
+ if (
+ entity
+ and entity in self._wandb_setup._get_teams()
+ and entity != username
+ ):
+ entity_str = f" ({click.style(entity, fg='yellow')})"
+
+ login_state_str = f"Currently logged in as: {click.style(username, fg='yellow')}{entity_str}{host_str}"
+ else:
+ login_state_str = "W&B API key is configured"
+
+ login_info_str = (
+ f"Use {click.style('`wandb login --relogin`', bold=True)} to force relogin"
+ )
+ wandb.termlog(
+ f"{login_state_str}. {login_info_str}",
+ repeat=False,
+ )
+
+ def try_save_api_key(self, key: str) -> None:
+ """Saves the API key to disk for future use."""
+ if self._settings._notebook and not self._settings.silent:
+ wandb.termwarn(
+ "If you're specifying your api key in code, ensure this "
+ "code is not shared publicly.\nConsider setting the "
+ "WANDB_API_KEY environment variable, or running "
+ "`wandb login` from the command line."
+ )
+ if key:
+ try:
+ apikey.write_key(self._settings, key)
+ except apikey.WriteNetrcError as e:
+ wandb.termwarn(str(e))
+
+ def update_session(
+ self,
+ key: Optional[str],
+ status: ApiKeyStatus = ApiKeyStatus.VALID,
+ ) -> None:
+ """Updates mode and API key settings on the global setup object.
+
+ If we're online, this also pulls in user settings from the server.
+ """
+ login_settings = dict()
+ if status == ApiKeyStatus.OFFLINE:
+ login_settings = dict(mode="offline")
+ elif status == ApiKeyStatus.DISABLED:
+ login_settings = dict(mode="disabled")
+ elif key:
+ login_settings = dict(api_key=key)
+ self._wandb_setup.settings.update_from_dict(login_settings)
+ # Whenever the key changes, make sure to pull in user settings
+ # from server.
+ if not self._wandb_setup.settings._offline:
+ self._wandb_setup.update_user_settings()
+
+ def _prompt_api_key(
+ self, referrer: Optional[str] = None
+ ) -> Tuple[Optional[str], ApiKeyStatus]:
+ api = Api(self._settings)
+ while True:
+ try:
+ key = apikey.prompt_api_key(
+ self._settings,
+ api=api,
+ no_offline=self._settings.force if self._settings else None,
+ no_create=self._settings.force if self._settings else None,
+ referrer=referrer,
+ )
+ except ValueError as e:
+ # invalid key provided, try again
+ wandb.termerror(e.args[0])
+ continue
+ except TimeoutError:
+ wandb.termlog("W&B disabled due to login timeout.")
+ return None, ApiKeyStatus.DISABLED
+ if key is False:
+ return None, ApiKeyStatus.NOTTY
+ if not key:
+ return None, ApiKeyStatus.OFFLINE
+ return key, ApiKeyStatus.VALID
+
+ def prompt_api_key(
+ self, referrer: Optional[str] = None
+ ) -> Tuple[Optional[str], ApiKeyStatus]:
+ """Updates the global API key by prompting the user."""
+ key, status = self._prompt_api_key(referrer)
+ if status == ApiKeyStatus.NOTTY:
+ directive = (
+ "wandb login [your_api_key]"
+ if self._settings.x_cli_only_mode
+ else "wandb.login(key=[your_api_key])"
+ )
+ raise UsageError("api_key not configured (no-tty). call " + directive)
+
+ return key, status
+
+
+def _login(
+ *,
+ anonymous: Optional[Literal["allow", "must", "never"]] = None,
+ key: Optional[str] = None,
+ relogin: Optional[bool] = None,
+ host: Optional[str] = None,
+ force: Optional[bool] = None,
+ timeout: Optional[int] = None,
+ verify: bool = False,
+ referrer: str = "models",
+ update_api_key: bool = True,
+ _silent: Optional[bool] = None,
+ _disable_warning: Optional[bool] = None,
+) -> (bool, Optional[str]):
+ """Logs in to W&B.
+
+ This is the internal implementation of wandb.login(),
+ with many of the same arguments as wandb.login().
+ Additional arguments are documented below.
+
+ Args:
+ update_api_key: If true, the api key will be saved or updated
+ in the users .netrc file.
+ _silent: If true, will not print any messages to the console.
+ _disable_warning: If true, no warning will be displayed
+ when calling wandb.login() after wandb.init().
+
+ Returns:
+ bool: If the login was successful
+ or the user is assumed to be already be logged in.
+ str: The API key used to log in,
+ or None if the api key was not verified during the login process.
+ """
+ if wandb.run is not None:
+ if not _disable_warning:
+ wandb.termwarn("Calling wandb.login() after wandb.init() has no effect.")
+ return True, None
+
+ wlogin = _WandbLogin(
+ anonymous=anonymous,
+ force=force,
+ host=host,
+ key=key,
+ relogin=relogin,
+ timeout=timeout,
+ )
+
+ if wlogin._settings._noop:
+ return True, None
+
+ if wlogin._settings._offline and not wlogin._settings.x_cli_only_mode:
+ wandb.termwarn("Unable to verify login in offline mode.")
+ return False, None
+ elif wandb.util._is_kaggle() and not wandb.util._has_internet():
+ wandb.termerror(
+ "To use W&B in kaggle you must enable internet in the settings panel on the right."
+ )
+ return False, None
+
+ if wlogin._settings.identity_token_file:
+ return True, None
+
+ key_is_pre_configured = False
+ key_status = None
+ if key is None:
+ # Check if key is already set in the settings, or configured in the users .netrc file.
+ key = apikey.api_key(settings=wlogin._settings)
+ if key and not relogin:
+ key_is_pre_configured = True
+ else:
+ key, key_status = wlogin.prompt_api_key(referrer=referrer)
+
+ if verify:
+ _verify_login(key, wlogin._settings.base_url)
+
+ if not key_is_pre_configured:
+ if update_api_key:
+ wlogin.try_save_api_key(key)
+ wlogin.update_session(key, status=key_status)
+ wlogin._update_global_anonymous_setting()
+
+ if key and not _silent:
+ wlogin._print_logged_in_message()
+
+ return key is not None, key
+
+
+def _verify_login(key: str, base_url: str) -> None:
+ api = InternalApi(
+ api_key=key,
+ default_settings={"base_url": base_url},
+ )
+
+ try:
+ is_api_key_valid = api.validate_api_key()
+ except ConnectionError:
+ raise AuthenticationError(
+ "Unable to connect to server to verify API token."
+ ) from None
+ except Exception as e:
+ raise AuthenticationError(
+ "An error occurred while verifying the API key."
+ ) from e
+
+ if not is_api_key_valid:
+ raise AuthenticationError(
+ f"API key verification failed for host {base_url}."
+ " Make sure your API key is valid."
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_metric.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_metric.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b9ffd224bd98eda0aa4f594ad1148c9c01b70cb
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_metric.py
@@ -0,0 +1,112 @@
+"""metric."""
+
+import logging
+from typing import Callable, Optional, Sequence, Tuple
+
+from wandb.proto import wandb_internal_pb2 as pb
+
+logger = logging.getLogger("wandb")
+
+
+class Metric:
+ """Metric object."""
+
+ _callback: Optional[Callable[[pb.MetricRecord], None]]
+ _name: str
+ _step_metric: Optional[str]
+ _step_sync: Optional[bool]
+ _hidden: Optional[bool]
+ _summary: Optional[Sequence[str]]
+ _goal: Optional[str]
+ _overwrite: Optional[bool]
+
+ def __init__(
+ self,
+ name: str,
+ step_metric: Optional[str] = None,
+ step_sync: Optional[bool] = None,
+ hidden: Optional[bool] = None,
+ summary: Optional[Sequence[str]] = None,
+ goal: Optional[str] = None,
+ overwrite: Optional[bool] = None,
+ ) -> None:
+ self._callback = None
+ self._name = name
+ self._step_metric = step_metric
+ # default to step_sync=True if step metric is set
+ step_sync = step_sync if step_sync is not None else step_metric is not None
+ self._step_sync = step_sync
+ self._hidden = hidden
+ self._summary = summary
+ self._goal = goal
+ self._overwrite = overwrite
+
+ def _set_callback(self, cb: Callable[[pb.MetricRecord], None]) -> None:
+ self._callback = cb
+
+ @property
+ def name(self) -> str:
+ return self._name
+
+ @property
+ def step_metric(self) -> Optional[str]:
+ return self._step_metric
+
+ @property
+ def step_sync(self) -> Optional[bool]:
+ return self._step_sync
+
+ @property
+ def summary(self) -> Optional[Tuple[str, ...]]:
+ if self._summary is None:
+ return None
+ return tuple(self._summary)
+
+ @property
+ def hidden(self) -> Optional[bool]:
+ return self._hidden
+
+ @property
+ def goal(self) -> Optional[str]:
+ goal_dict = dict(min="minimize", max="maximize")
+ return goal_dict[self._goal] if self._goal else None
+
+ def _commit(self) -> None:
+ m = pb.MetricRecord()
+ m.options.defined = True
+ if self._name.endswith("*"):
+ m.glob_name = self._name
+ else:
+ m.name = self._name
+ if self._step_metric:
+ m.step_metric = self._step_metric
+ if self._step_sync:
+ m.options.step_sync = self._step_sync
+ if self._hidden:
+ m.options.hidden = self._hidden
+ if self._summary:
+ summary_set = set(self._summary)
+ if "min" in summary_set:
+ m.summary.min = True
+ if "max" in summary_set:
+ m.summary.max = True
+ if "mean" in summary_set:
+ m.summary.mean = True
+ if "last" in summary_set:
+ m.summary.last = True
+ if "copy" in summary_set:
+ m.summary.copy = True
+ if "none" in summary_set:
+ m.summary.none = True
+ if "best" in summary_set:
+ m.summary.best = True
+ if "first" in summary_set:
+ m.summary.first = True
+ if self._goal == "min":
+ m.goal = m.GOAL_MINIMIZE
+ if self._goal == "max":
+ m.goal = m.GOAL_MAXIMIZE
+ if self._overwrite:
+ m._control.overwrite = self._overwrite
+ if self._callback:
+ self._callback(m)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_require.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_require.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1540e29afe1156b5ed994d662203c68855ac46a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_require.py
@@ -0,0 +1,88 @@
+"""Feature Flags Module.
+
+This module implements a feature flag system for the wandb library to require experimental features
+and notify the user when features have been deprecated.
+
+Example:
+ import wandb
+ wandb.require("wandb-service@beta")
+ wandb.require("incremental-artifacts@beta")
+"""
+
+from __future__ import annotations
+
+from typing import Iterable
+
+import wandb
+from wandb.errors import UnsupportedError
+
+
+class _Requires:
+ """Internal feature class."""
+
+ _features: tuple[str, ...]
+
+ def __init__(self, features: str | Iterable[str]) -> None:
+ self._features = (
+ tuple([features]) if isinstance(features, str) else tuple(features)
+ )
+
+ def require_require(self) -> None:
+ pass
+
+ def require_service(self) -> None:
+ # Legacy no-op kept solely for backward compatibility:
+ # some integrations (e.g. PyTorch Lightning) still call
+ # `wandb.require('service')`, which routes here.
+ wandb.termwarn(
+ "`wandb.require('service')` is a no-op as it is now the default behavior."
+ )
+
+ def require_core(self) -> None:
+ # Legacy no-op kept solely for backward compatibility:
+ # many public codebases still call `wandb.require('core')`.
+ wandb.termwarn(
+ "`wandb.require('core')` is a no-op as it is now the default behavior."
+ )
+
+ def apply(self) -> None:
+ """Call require_* method for supported features."""
+ last_message: str = ""
+ for feature_item in self._features:
+ full_feature = feature_item.split("@", 2)[0]
+ feature = full_feature.split(":", 2)[0]
+ func_str = "require_{}".format(feature.replace("-", "_"))
+ func = getattr(self, func_str, None)
+ if not func:
+ last_message = f"require() unsupported requirement: {feature}"
+ wandb.termwarn(last_message)
+ continue
+ func()
+
+ if last_message:
+ raise UnsupportedError(last_message)
+
+
+def require(
+ requirement: str | Iterable[str] | None = None,
+ experiment: str | Iterable[str] | None = None,
+) -> None:
+ """Indicate which experimental features are used by the script.
+
+ This should be called before any other `wandb` functions, ideally right
+ after importing `wandb`.
+
+ Args:
+ requirement: The name of a feature to require or an iterable of
+ feature names.
+ experiment: An alias for `requirement`.
+
+ Raises:
+ wandb.errors.UnsupportedError: If a feature name is unknown.
+ """
+ features = requirement or experiment
+ if not features:
+ return
+
+ f = _Requires(features=features)
+ f.apply()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_require_helpers.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_require_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f14583ac53efd1b2b49b76ea1a0a27e65e88627
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_require_helpers.py
@@ -0,0 +1,44 @@
+import os
+from functools import wraps
+from typing import Any, Callable, Dict, TypeVar, cast
+
+FuncT = TypeVar("FuncT", bound=Callable[..., Any])
+
+requirement_env_var_mapping: Dict[str, str] = {
+ "report-editing:v0": "WANDB_REQUIRE_REPORT_EDITING_V0"
+}
+
+
+def requires(requirement: str) -> FuncT: # type: ignore
+ """Decorate functions to gate features with wandb.require."""
+ env_var = requirement_env_var_mapping[requirement]
+
+ def deco(func: FuncT) -> FuncT:
+ @wraps(func)
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ if not os.getenv(env_var):
+ raise Exception(
+ f"You need to enable this feature with `wandb.require({requirement!r})`"
+ )
+ return func(*args, **kwargs)
+
+ return cast(FuncT, wrapper)
+
+ return cast(FuncT, deco)
+
+
+class RequiresMixin:
+ requirement = ""
+
+ def __init__(self) -> None:
+ self._check_if_requirements_met()
+
+ def __post_init__(self) -> None:
+ self._check_if_requirements_met()
+
+ def _check_if_requirements_met(self) -> None:
+ env_var = requirement_env_var_mapping[self.requirement]
+ if not os.getenv(env_var):
+ raise Exception(
+ f'You must explicitly enable this feature with `wandb.require("{self.requirement})"'
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_run.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_run.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb235431e03f909ae44528a8e23043246874e8df
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_run.py
@@ -0,0 +1,4105 @@
+from __future__ import annotations
+
+import asyncio
+import functools
+import glob
+import json
+import logging
+import numbers
+import os
+import pathlib
+import re
+import sys
+import threading
+import time
+import traceback
+from collections.abc import Mapping
+from dataclasses import dataclass, field
+from datetime import datetime, timedelta, timezone
+from enum import IntEnum
+from types import TracebackType
+from typing import TYPE_CHECKING, Callable, Sequence, TextIO, TypeVar
+
+import requests
+from typing_extensions import Any, Concatenate, Literal, NamedTuple, ParamSpec
+
+import wandb
+import wandb.env
+import wandb.util
+from wandb import trigger
+from wandb.apis import internal, public
+from wandb.apis.public import Api as PublicApi
+from wandb.errors import CommError, UsageError
+from wandb.errors.links import url_registry
+from wandb.integration.torch import wandb_torch
+from wandb.plot import CustomChart, Visualize
+from wandb.proto import wandb_internal_pb2 as pb
+from wandb.proto.wandb_deprecated import Deprecated
+from wandb.proto.wandb_internal_pb2 import (
+ MetricRecord,
+ PollExitResponse,
+ Result,
+ RunRecord,
+)
+from wandb.sdk.artifacts._internal_artifact import InternalArtifact
+from wandb.sdk.artifacts.artifact import Artifact
+from wandb.sdk.internal import job_builder
+from wandb.sdk.lib import asyncio_compat, wb_logging
+from wandb.sdk.lib.import_hooks import (
+ register_post_import_hook,
+ unregister_post_import_hook,
+)
+from wandb.sdk.lib.paths import FilePathStr, StrPath
+from wandb.util import (
+ _is_artifact_object,
+ _is_artifact_string,
+ _is_artifact_version_weave_dict,
+ _is_py_requirements_or_dockerfile,
+ _resolve_aliases,
+ add_import_hook,
+ parse_artifact_string,
+)
+
+from . import wandb_config, wandb_metric, wandb_summary
+from .artifacts._validators import (
+ MAX_ARTIFACT_METADATA_KEYS,
+ ArtifactPath,
+ validate_aliases,
+ validate_tags,
+)
+from .data_types._dtypes import TypeRegistry
+from .interface.interface import FilesDict, GlobStr, InterfaceBase, PolicyName
+from .interface.summary_record import SummaryRecord
+from .lib import (
+ config_util,
+ deprecate,
+ filenames,
+ filesystem,
+ interrupt,
+ ipython,
+ module,
+ printer,
+ progress,
+ proto_util,
+ redirect,
+ telemetry,
+)
+from .lib.exit_hooks import ExitHooks
+from .mailbox import (
+ HandleAbandonedError,
+ MailboxClosedError,
+ MailboxHandle,
+ wait_with_progress,
+)
+from .wandb_alerts import AlertLevel
+from .wandb_settings import Settings
+from .wandb_setup import _WandbSetup
+
+if TYPE_CHECKING:
+ from typing import TypedDict
+
+ import torch # type: ignore [import-not-found]
+
+ import wandb.apis.public
+ import wandb.sdk.backend.backend
+ import wandb.sdk.interface.interface_queue
+ from wandb.proto.wandb_internal_pb2 import (
+ GetSummaryResponse,
+ InternalMessagesResponse,
+ SampledHistoryResponse,
+ )
+
+ class GitSourceDict(TypedDict):
+ remote: str
+ commit: str
+ entrypoint: list[str]
+ args: Sequence[str]
+
+ class ArtifactSourceDict(TypedDict):
+ artifact: str
+ entrypoint: list[str]
+ args: Sequence[str]
+
+ class ImageSourceDict(TypedDict):
+ image: str
+ args: Sequence[str]
+
+ class JobSourceDict(TypedDict, total=False):
+ _version: str
+ source_type: str
+ source: GitSourceDict | ArtifactSourceDict | ImageSourceDict
+ input_types: dict[str, Any]
+ output_types: dict[str, Any]
+ runtime: str | None
+ services: dict[str, str]
+
+
+logger = logging.getLogger("wandb")
+EXIT_TIMEOUT = 60
+RE_LABEL = re.compile(r"[a-zA-Z0-9_-]+$")
+
+
+class TeardownStage(IntEnum):
+ EARLY = 1
+ LATE = 2
+
+
+class TeardownHook(NamedTuple):
+ call: Callable[[], None]
+ stage: TeardownStage
+
+
+class RunStatusChecker:
+ """Periodically polls the background process for relevant updates.
+
+ - check if the user has requested a stop.
+ - check the network status.
+ - check the run sync status.
+ """
+
+ _stop_status_lock: threading.Lock
+ _stop_status_handle: MailboxHandle[Result] | None
+ _network_status_lock: threading.Lock
+ _network_status_handle: MailboxHandle[Result] | None
+ _internal_messages_lock: threading.Lock
+ _internal_messages_handle: MailboxHandle[Result] | None
+
+ def __init__(
+ self,
+ run_id: str,
+ interface: InterfaceBase,
+ settings: Settings,
+ stop_polling_interval: int = 15,
+ retry_polling_interval: int = 5,
+ internal_messages_polling_interval: int = 10,
+ ) -> None:
+ self._run_id = run_id
+ self._interface = interface
+ self._stop_polling_interval = stop_polling_interval
+ self._retry_polling_interval = retry_polling_interval
+ self._internal_messages_polling_interval = internal_messages_polling_interval
+ self._settings = settings
+
+ self._join_event = threading.Event()
+
+ self._stop_status_lock = threading.Lock()
+ self._stop_status_handle = None
+ self._stop_thread = threading.Thread(
+ target=self.check_stop_status,
+ name="ChkStopThr",
+ daemon=True,
+ )
+
+ self._network_status_lock = threading.Lock()
+ self._network_status_handle = None
+ self._network_status_thread = threading.Thread(
+ target=self.check_network_status,
+ name="NetStatThr",
+ daemon=True,
+ )
+
+ self._internal_messages_lock = threading.Lock()
+ self._internal_messages_handle = None
+ self._internal_messages_thread = threading.Thread(
+ target=self.check_internal_messages,
+ name="IntMsgThr",
+ daemon=True,
+ )
+
+ def start(self) -> None:
+ self._stop_thread.start()
+ self._network_status_thread.start()
+ self._internal_messages_thread.start()
+
+ @staticmethod
+ def _abandon_status_check(
+ lock: threading.Lock,
+ handle: MailboxHandle[Result] | None,
+ ):
+ with lock:
+ if handle:
+ handle.abandon()
+
+ def _loop_check_status(
+ self,
+ *,
+ lock: threading.Lock,
+ set_handle: Any,
+ timeout: int,
+ request: Any,
+ process: Any,
+ ) -> None:
+ local_handle: MailboxHandle[Result] | None = None
+ join_requested = False
+ while not join_requested:
+ time_probe = time.monotonic()
+ if not local_handle:
+ try:
+ local_handle = request()
+ except MailboxClosedError:
+ # This can happen if the service process dies.
+ break
+ assert local_handle
+
+ with lock:
+ if self._join_event.is_set():
+ break
+ set_handle(local_handle)
+
+ try:
+ result = local_handle.wait_or(timeout=timeout)
+ except HandleAbandonedError:
+ # This can happen if the service process dies.
+ break
+ except TimeoutError:
+ result = None
+
+ with lock:
+ set_handle(None)
+
+ if result:
+ process(result)
+ local_handle = None
+
+ time_elapsed = time.monotonic() - time_probe
+ wait_time = max(timeout - time_elapsed, 0)
+ join_requested = self._join_event.wait(timeout=wait_time)
+
+ def check_network_status(self) -> None:
+ def _process_network_status(result: Result) -> None:
+ network_status = result.response.network_status_response
+ for hr in network_status.network_responses:
+ if (
+ hr.http_status_code == 200 or hr.http_status_code == 0
+ ): # we use 0 for non-http errors (eg wandb errors)
+ wandb.termlog(f"{hr.http_response_text}")
+ else:
+ wandb.termlog(
+ f"{hr.http_status_code} encountered ({hr.http_response_text.rstrip()}), retrying request"
+ )
+
+ with wb_logging.log_to_run(self._run_id):
+ try:
+ self._loop_check_status(
+ lock=self._network_status_lock,
+ set_handle=lambda x: setattr(self, "_network_status_handle", x),
+ timeout=self._retry_polling_interval,
+ request=self._interface.deliver_network_status,
+ process=_process_network_status,
+ )
+ except BrokenPipeError:
+ self._abandon_status_check(
+ self._network_status_lock,
+ self._network_status_handle,
+ )
+
+ def check_stop_status(self) -> None:
+ def _process_stop_status(result: Result) -> None:
+ stop_status = result.response.stop_status_response
+ if stop_status.run_should_stop:
+ # TODO(frz): This check is required
+ # until WB-3606 is resolved on server side.
+ if not wandb.agents.pyagent.is_running(): # type: ignore
+ interrupt.interrupt_main()
+ return
+
+ with wb_logging.log_to_run(self._run_id):
+ try:
+ self._loop_check_status(
+ lock=self._stop_status_lock,
+ set_handle=lambda x: setattr(self, "_stop_status_handle", x),
+ timeout=self._stop_polling_interval,
+ request=self._interface.deliver_stop_status,
+ process=_process_stop_status,
+ )
+ except BrokenPipeError:
+ self._abandon_status_check(
+ self._stop_status_lock,
+ self._stop_status_handle,
+ )
+
+ def check_internal_messages(self) -> None:
+ def _process_internal_messages(result: Result) -> None:
+ if (
+ not self._settings.show_warnings
+ or self._settings.quiet
+ or self._settings.silent
+ ):
+ return
+ internal_messages = result.response.internal_messages_response
+ for msg in internal_messages.messages.warning:
+ wandb.termwarn(msg, repeat=False)
+
+ with wb_logging.log_to_run(self._run_id):
+ try:
+ self._loop_check_status(
+ lock=self._internal_messages_lock,
+ set_handle=lambda x: setattr(self, "_internal_messages_handle", x),
+ timeout=self._internal_messages_polling_interval,
+ request=self._interface.deliver_internal_messages,
+ process=_process_internal_messages,
+ )
+ except BrokenPipeError:
+ self._abandon_status_check(
+ self._internal_messages_lock,
+ self._internal_messages_handle,
+ )
+
+ def stop(self) -> None:
+ self._join_event.set()
+ self._abandon_status_check(
+ self._stop_status_lock,
+ self._stop_status_handle,
+ )
+ self._abandon_status_check(
+ self._network_status_lock,
+ self._network_status_handle,
+ )
+ self._abandon_status_check(
+ self._internal_messages_lock,
+ self._internal_messages_handle,
+ )
+
+ def join(self) -> None:
+ self.stop()
+ self._stop_thread.join()
+ self._network_status_thread.join()
+ self._internal_messages_thread.join()
+
+
+_P = ParamSpec("_P")
+_T = TypeVar("_T")
+
+
+def _log_to_run(
+ func: Callable[Concatenate[Run, _P], _T],
+) -> Callable[Concatenate[Run, _P], _T]:
+ """Decorate a Run method to set the run ID in the logging context.
+
+ Any logs during the execution of the method go to the run's log file
+ and not to other runs' log files.
+
+ This is meant for use on all public methods and some callbacks. Private
+ methods can be assumed to be called from some public method somewhere.
+ The general rule is to use it on methods that can be called from a
+ context that isn't specific to this run (such as all user code or
+ internal methods that aren't run-specific).
+ """
+
+ @functools.wraps(func)
+ def wrapper(self: Run, *args, **kwargs) -> _T:
+ # In "attach" usage, many properties of the Run are not initially
+ # populated.
+ if hasattr(self, "_settings"):
+ run_id = self._settings.run_id
+ else:
+ run_id = self._attach_id
+
+ with wb_logging.log_to_run(run_id):
+ return func(self, *args, **kwargs)
+
+ return wrapper
+
+
+_is_attaching: str = ""
+
+
+def _attach(
+ func: Callable[Concatenate[Run, _P], _T],
+) -> Callable[Concatenate[Run, _P], _T]:
+ """Decorate a Run method to auto-attach when in a new process.
+
+ When in a forked process or using a pickled Run instance, this automatically
+ connects to the service process to "attach" to the existing run.
+ """
+
+ @functools.wraps(func)
+ def wrapper(self: Run, *args, **kwargs) -> _T:
+ global _is_attaching
+
+ # The _attach_id attribute is only None when running in the "disable
+ # service" mode.
+ #
+ # Since it is set early in `__init__` and included in the run's pickled
+ # state, the attribute always exists.
+ is_using_service = self._attach_id is not None
+
+ # The _attach_pid attribute is not pickled, so it might not exist.
+ # It is set when the run is initialized.
+ attach_pid = getattr(self, "_attach_pid", None)
+
+ if is_using_service and attach_pid != os.getpid():
+ if _is_attaching:
+ raise RuntimeError(
+ f"Trying to attach `{func.__name__}`"
+ f" while in the middle of attaching `{_is_attaching}`"
+ )
+
+ _is_attaching = func.__name__
+ try:
+ wandb._attach(run=self) # type: ignore
+ finally:
+ _is_attaching = ""
+
+ return func(self, *args, **kwargs)
+
+ return wrapper
+
+
+def _raise_if_finished(
+ func: Callable[Concatenate[Run, _P], _T],
+) -> Callable[Concatenate[Run, _P], _T]:
+ """Decorate a Run method to raise an error after the run is finished."""
+
+ @functools.wraps(func)
+ def wrapper_fn(self: Run, *args, **kwargs) -> _T:
+ if not getattr(self, "_is_finished", False):
+ return func(self, *args, **kwargs)
+
+ message = (
+ f"Run ({self.id}) is finished. The call to"
+ f" `{func.__name__}` will be ignored."
+ f" Please make sure that you are using an active run."
+ )
+
+ raise UsageError(message)
+
+ return wrapper_fn
+
+
+@dataclass
+class RunStatus:
+ sync_items_total: int = field(default=0)
+ sync_items_pending: int = field(default=0)
+ sync_time: datetime | None = field(default=None)
+
+
+class Run:
+ """A unit of computation logged by W&B. Typically, this is an ML experiment.
+
+ Call [`wandb.init()`](https://docs.wandb.ai/ref/python/init/) to create a
+ new run. `wandb.init()` starts a new run and returns a `wandb.Run` object.
+ Each run is associated with a unique ID (run ID). W&B recommends using
+ a context (`with` statement) manager to automatically finish the run.
+
+ For distributed training experiments, you can either track each process
+ separately using one run per process or track all processes to a single run.
+ See [Log distributed training experiments](https://docs.wandb.ai/guides/track/log/distributed-training)
+ for more information.
+
+ You can log data to a run with `wandb.Run.log()`. Anything you log using
+ `wandb.Run.log()` is sent to that run. See
+ [Create an experiment](https://docs.wandb.ai/guides/track/launch) or
+ [`wandb.init`](https://docs.wandb.ai/ref/python/init/) API reference page
+ or more information.
+
+ There is a another `Run` object in the
+ [`wandb.apis.public`](https://docs.wandb.ai/ref/python/public-api/api/)
+ namespace. Use this object is to interact with runs that have already been
+ created.
+
+ Attributes:
+ summary: (Summary) A summary of the run, which is a dictionary-like
+ object. For more information, see
+ [Log summary metrics](https://docs.wandb.ai/guides/track/log/log-summary/).
+
+ Examples:
+ Create a run with `wandb.init()`:
+
+ ```python
+ import wandb
+
+ # Start a new run and log some data
+ # Use context manager (`with` statement) to automatically finish the run
+ with wandb.init(entity="entity", project="project") as run:
+ run.log({"accuracy": acc, "loss": loss})
+ ```
+
+
+ """
+
+ _telemetry_obj: telemetry.TelemetryRecord
+ _telemetry_obj_active: bool
+ _telemetry_obj_dirty: bool
+ _telemetry_obj_flushed: bytes
+
+ _teardown_hooks: list[TeardownHook]
+
+ _backend: wandb.sdk.backend.backend.Backend | None
+ _internal_run_interface: wandb.sdk.interface.interface_queue.InterfaceQueue | None
+ _wl: _WandbSetup | None
+
+ _out_redir: redirect.RedirectBase | None
+ _err_redir: redirect.RedirectBase | None
+ _redirect_cb: Callable[[str, str], None] | None
+ _redirect_raw_cb: Callable[[str, str], None] | None
+ _output_writer: filesystem.CRDedupedFile | None
+
+ _atexit_cleanup_called: bool
+ _hooks: ExitHooks | None
+ _exit_code: int | None
+
+ _run_status_checker: RunStatusChecker | None
+
+ _sampled_history: SampledHistoryResponse | None
+ _final_summary: GetSummaryResponse | None
+ _poll_exit_handle: MailboxHandle[Result] | None
+ _poll_exit_response: PollExitResponse | None
+ _internal_messages_response: InternalMessagesResponse | None
+
+ _stdout_slave_fd: int | None
+ _stderr_slave_fd: int | None
+ _artifact_slots: list[str]
+
+ _init_pid: int
+ _attach_pid: int
+
+ _attach_id: str | None
+ _is_attached: bool
+ _is_finished: bool
+ _settings: Settings
+
+ _forked: bool
+
+ _launch_artifacts: dict[str, Any] | None
+ _printer: printer.Printer
+
+ summary: wandb_summary.Summary
+
+ def __init__(
+ self,
+ settings: Settings,
+ config: dict[str, Any] | None = None,
+ sweep_config: dict[str, Any] | None = None,
+ launch_config: dict[str, Any] | None = None,
+ ) -> None:
+ # pid is set, so we know if this run object was initialized by this process
+ self._init_pid = os.getpid()
+ self._attach_id = None
+
+ if settings._noop:
+ # TODO: properly handle setting for disabled mode
+ self._settings = settings
+ return
+
+ self._init(
+ settings=settings,
+ config=config,
+ sweep_config=sweep_config,
+ launch_config=launch_config,
+ )
+
+ def _init(
+ self,
+ settings: Settings,
+ config: dict[str, Any] | None = None,
+ sweep_config: dict[str, Any] | None = None,
+ launch_config: dict[str, Any] | None = None,
+ ) -> None:
+ self._settings = settings
+
+ self._config = wandb_config.Config()
+ self._config._set_callback(self._config_callback)
+ self._config._set_artifact_callback(self._config_artifact_callback)
+ self._config._set_settings(self._settings)
+
+ # The _wandb key is always expected on the run config.
+ wandb_key = "_wandb"
+ self._config._update({wandb_key: dict()})
+
+ # TODO: perhaps this should be a property that is a noop on a finished run
+ self.summary = wandb_summary.Summary(
+ self._summary_get_current_summary_callback,
+ )
+ self.summary._set_update_callback(self._summary_update_callback)
+
+ self._step = 0
+ self._starting_step = 0
+ self._start_runtime = 0
+ # TODO: eventually would be nice to make this configurable using self._settings._start_time
+ # need to test (jhr): if you set start time to 2 days ago and run a test for 15 minutes,
+ # does the total time get calculated right (not as 2 days and 15 minutes)?
+ self._start_time = time.time()
+
+ self._printer = printer.new_printer(settings)
+
+ self._torch_history: wandb_torch.TorchHistory | None = None # type: ignore
+
+ self._backend = None
+ self._internal_run_interface = None
+ self._wl = None
+
+ self._hooks = None
+ self._teardown_hooks = []
+
+ self._output_writer = None
+ self._out_redir = None
+ self._err_redir = None
+ self._stdout_slave_fd = None
+ self._stderr_slave_fd = None
+
+ self._exit_code = None
+ self._exit_result = None
+
+ self._used_artifact_slots: dict[str, str] = {}
+
+ # Created when the run "starts".
+ self._run_status_checker = None
+
+ self._sampled_history = None
+ self._final_summary = None
+ self._poll_exit_response = None
+ self._internal_messages_response = None
+ self._poll_exit_handle = None
+
+ # Initialize telemetry object
+ self._telemetry_obj = telemetry.TelemetryRecord()
+ self._telemetry_obj_active = False
+ self._telemetry_obj_flushed = b""
+ self._telemetry_obj_dirty = False
+
+ self._atexit_cleanup_called = False
+
+ # Initial scope setup for sentry.
+ # This might get updated when the actual run comes back.
+ wandb._sentry.configure_scope(
+ tags=dict(self._settings),
+ process_context="user",
+ )
+
+ self._launch_artifact_mapping: dict[str, Any] = {}
+ self._unique_launch_artifact_sequence_names: dict[str, Any] = {}
+
+ # Populate config
+ config = config or dict()
+ self._config._update(config, allow_val_change=True, ignore_locked=True)
+
+ if sweep_config:
+ self._config.merge_locked(
+ sweep_config, user="sweep", _allow_val_change=True
+ )
+
+ if launch_config:
+ self._config.merge_locked(
+ launch_config, user="launch", _allow_val_change=True
+ )
+
+ # if run is from a launch queue, add queue id to _wandb config
+ launch_queue_name = wandb.env.get_launch_queue_name()
+ if launch_queue_name:
+ self._config[wandb_key]["launch_queue_name"] = launch_queue_name
+
+ launch_queue_entity = wandb.env.get_launch_queue_entity()
+ if launch_queue_entity:
+ self._config[wandb_key]["launch_queue_entity"] = launch_queue_entity
+
+ launch_trace_id = wandb.env.get_launch_trace_id()
+ if launch_trace_id:
+ self._config[wandb_key]["launch_trace_id"] = launch_trace_id
+
+ self._attach_id = None
+ self._is_attached = False
+ self._is_finished = False
+
+ self._attach_pid = os.getpid()
+ self._forked = False
+ # for now, use runid as attach id, this could/should be versioned in the future
+ self._attach_id = self._settings.run_id
+
+ def _handle_launch_artifact_overrides(self) -> None:
+ if self._settings.launch and (os.environ.get("WANDB_ARTIFACTS") is not None):
+ try:
+ artifacts: dict[str, Any] = json.loads(
+ os.environ.get("WANDB_ARTIFACTS", "{}")
+ )
+ except (ValueError, SyntaxError):
+ wandb.termwarn("Malformed WANDB_ARTIFACTS, using original artifacts")
+ else:
+ self._initialize_launch_artifact_maps(artifacts)
+
+ elif (
+ self._settings.launch
+ and self._settings.launch_config_path
+ and os.path.exists(self._settings.launch_config_path)
+ ):
+ self.save(self._settings.launch_config_path)
+ with open(self._settings.launch_config_path) as fp:
+ launch_config = json.loads(fp.read())
+ if launch_config.get("overrides", {}).get("artifacts") is not None:
+ artifacts = launch_config.get("overrides").get("artifacts")
+ self._initialize_launch_artifact_maps(artifacts)
+
+ def _initialize_launch_artifact_maps(self, artifacts: dict[str, Any]) -> None:
+ for key, item in artifacts.items():
+ self._launch_artifact_mapping[key] = item
+ artifact_sequence_tuple_or_slot = key.split(":")
+
+ if len(artifact_sequence_tuple_or_slot) == 2:
+ sequence_name = artifact_sequence_tuple_or_slot[0].split("/")[-1]
+ if self._unique_launch_artifact_sequence_names.get(sequence_name):
+ self._unique_launch_artifact_sequence_names.pop(sequence_name)
+ else:
+ self._unique_launch_artifact_sequence_names[sequence_name] = item
+
+ def _telemetry_callback(self, telem_obj: telemetry.TelemetryRecord) -> None:
+ if not hasattr(self, "_telemetry_obj") or self._is_finished:
+ return
+
+ self._telemetry_obj.MergeFrom(telem_obj)
+ self._telemetry_obj_dirty = True
+ self._telemetry_flush()
+
+ def _telemetry_flush(self) -> None:
+ if not hasattr(self, "_telemetry_obj"):
+ return
+ if not self._telemetry_obj_active:
+ return
+ if not self._telemetry_obj_dirty:
+ return
+ if self._backend and self._backend.interface:
+ serialized = self._telemetry_obj.SerializeToString()
+ if serialized == self._telemetry_obj_flushed:
+ return
+ self._backend.interface._publish_telemetry(self._telemetry_obj)
+ self._telemetry_obj_flushed = serialized
+ self._telemetry_obj_dirty = False
+
+ def _freeze(self) -> None:
+ self._frozen = True
+
+ def __setattr__(self, attr: str, value: object) -> None:
+ if getattr(self, "_frozen", None) and not hasattr(self, attr):
+ raise Exception(f"Attribute {attr} is not supported on Run object.")
+ super().__setattr__(attr, value)
+
+ def __deepcopy__(self, memo: dict[int, Any]) -> Run:
+ return self
+
+ def __getstate__(self) -> Any:
+ """Return run state as a custom pickle."""
+ # We only pickle in service mode
+ if not self._settings:
+ return
+
+ _attach_id = self._attach_id
+ if not _attach_id:
+ return
+
+ return dict(
+ _attach_id=_attach_id,
+ _init_pid=self._init_pid,
+ _is_finished=self._is_finished,
+ )
+
+ def __setstate__(self, state: Any) -> None:
+ """Set run state from a custom pickle."""
+ if not state:
+ return
+
+ _attach_id = state.get("_attach_id")
+ if not _attach_id:
+ return
+
+ if state["_init_pid"] == os.getpid():
+ raise RuntimeError("attach in the same process is not supported currently")
+
+ self.__dict__.update(state)
+
+ @property
+ def _torch(self) -> wandb_torch.TorchHistory: # type: ignore
+ if self._torch_history is None:
+ self._torch_history = wandb_torch.TorchHistory() # type: ignore
+ return self._torch_history
+
+ @property
+ @_log_to_run
+ @_attach
+ def settings(self) -> Settings:
+ """A frozen copy of run's Settings object."""
+ return self._settings.model_copy(deep=True)
+
+ @property
+ @_log_to_run
+ @_attach
+ def dir(self) -> str:
+ """The directory where files associated with the run are saved."""
+ return self._settings.files_dir
+
+ @property
+ @_log_to_run
+ @_attach
+ def config(self) -> wandb_config.Config:
+ """Config object associated with this run."""
+ return self._config
+
+ @property
+ @_log_to_run
+ @_attach
+ def config_static(self) -> wandb_config.ConfigStatic:
+ """Static config object associated with this run."""
+ return wandb_config.ConfigStatic(self._config)
+
+ @property
+ @_log_to_run
+ @_attach
+ def name(self) -> str | None:
+ """Display name of the run.
+
+ Display names are not guaranteed to be unique and may be descriptive.
+ By default, they are randomly generated.
+ """
+ return self._settings.run_name
+
+ @name.setter
+ @_log_to_run
+ @_raise_if_finished
+ def name(self, name: str) -> None:
+ with telemetry.context(run=self) as tel:
+ tel.feature.set_run_name = True
+ self._settings.run_name = name
+ if self._backend and self._backend.interface:
+ self._backend.interface.publish_run(self)
+
+ @property
+ @_log_to_run
+ @_attach
+ def notes(self) -> str | None:
+ """Notes associated with the run, if there are any.
+
+ Notes can be a multiline string and can also use markdown and latex
+ equations inside `$$`, like `$x + 3$`.
+ """
+ return self._settings.run_notes
+
+ @notes.setter
+ @_log_to_run
+ @_raise_if_finished
+ def notes(self, notes: str) -> None:
+ self._settings.run_notes = notes
+ if self._backend and self._backend.interface:
+ self._backend.interface.publish_run(self)
+
+ @property
+ @_log_to_run
+ @_attach
+ def tags(self) -> tuple | None:
+ """Tags associated with the run, if there are any."""
+ return self._settings.run_tags or ()
+
+ @tags.setter
+ @_log_to_run
+ @_raise_if_finished
+ def tags(self, tags: Sequence) -> None:
+ with telemetry.context(run=self) as tel:
+ tel.feature.set_run_tags = True
+
+ try:
+ self._settings.run_tags = tuple(tags)
+ except ValueError as e:
+ # For runtime tag setting, warn instead of crash
+ # Extract the core error message without the pydantic wrapper
+ error_msg = str(e)
+ if "Value error," in error_msg:
+ # Extract the actual error message after "Value error, "
+ error_msg = error_msg.split("Value error, ")[1].split(" [type=")[0]
+ wandb.termwarn(f"Invalid tag detected: {error_msg} Tags not updated.")
+ return
+
+ if self._backend and self._backend.interface:
+ self._backend.interface.publish_run(self)
+
+ @property
+ @_log_to_run
+ @_attach
+ def id(self) -> str:
+ """Identifier for this run."""
+ assert self._settings.run_id is not None
+ return self._settings.run_id
+
+ @property
+ @_log_to_run
+ @_attach
+ def sweep_id(self) -> str | None:
+ """Identifier for the sweep associated with the run, if there is one."""
+ return self._settings.sweep_id
+
+ def _get_path(self) -> str:
+ return "/".join(
+ e
+ for e in [
+ self._settings.entity,
+ self._settings.project,
+ self._settings.run_id,
+ ]
+ if e is not None
+ )
+
+ @property
+ @_log_to_run
+ @_attach
+ def path(self) -> str:
+ """Path to the run.
+
+ Run paths include entity, project, and run ID, in the format
+ `entity/project/run_id`.
+ """
+ return self._get_path()
+
+ @property
+ @_log_to_run
+ @_attach
+ def start_time(self) -> float:
+ """Unix timestamp (in seconds) of when the run started."""
+ return self._start_time
+
+ @property
+ @_log_to_run
+ @_attach
+ def starting_step(self) -> int:
+ """The first step of the run.
+
+
+ """
+ return self._starting_step
+
+ @property
+ @_log_to_run
+ @_attach
+ def resumed(self) -> bool:
+ """True if the run was resumed, False otherwise."""
+ return self._settings.resumed
+
+ @property
+ @_log_to_run
+ @_attach
+ def step(self) -> int:
+ """Current value of the step.
+
+ This counter is incremented by `wandb.Run.log()`.
+
+
+ """
+ return self._step
+
+ @property
+ @_log_to_run
+ @_attach
+ def offline(self) -> bool:
+ """True if the run is offline, False otherwise."""
+ return self._settings._offline
+
+ @property
+ @_log_to_run
+ @_attach
+ def disabled(self) -> bool:
+ """True if the run is disabled, False otherwise."""
+ return self._settings._noop
+
+ @property
+ @_log_to_run
+ @_attach
+ def group(self) -> str:
+ """Returns the name of the group associated with this run.
+
+ Grouping runs together allows related experiments to be organized and
+ visualized collectively in the W&B UI. This is especially useful for
+ scenarios such as distributed training or cross-validation, where
+ multiple runs should be viewed and managed as a unified experiment.
+
+ In shared mode, where all processes share the same run object,
+ setting a group is usually unnecessary, since there is only one
+ run and no grouping is required.
+ """
+ return self._settings.run_group or ""
+
+ @property
+ @_log_to_run
+ @_attach
+ def job_type(self) -> str:
+ """Name of the job type associated with the run.
+
+ View a run's job type in the run's Overview page in the W&B App.
+
+ You can use this to categorize runs by their job type, such as
+ "training", "evaluation", or "inference". This is useful for organizing
+ and filtering runs in the W&B UI, especially when you have multiple
+ runs with different job types in the same project. For more
+ information, see [Organize runs](https://docs.wandb.ai/guides/runs/#organize-runs).
+ """
+ return self._settings.run_job_type or ""
+
+ def project_name(self) -> str:
+ """This method is deprecated and will be removed in a future release. Use `run.project` instead.
+
+ Name of the W&B project associated with the run.
+
+
+ """
+ deprecate.deprecate(
+ field_name=Deprecated.run__project_name,
+ warning_message=(
+ "The project_name method is deprecated and will be removed in a"
+ " future release. Please use `run.project` instead."
+ ),
+ )
+ return self.project
+
+ @property
+ @_log_to_run
+ @_attach
+ def project(self) -> str:
+ """Name of the W&B project associated with the run."""
+ assert self._settings.project is not None
+ return self._settings.project
+
+ @_log_to_run
+ def get_project_url(self) -> str | None:
+ """This method is deprecated and will be removed in a future release. Use `run.project_url` instead.
+
+ URL of the W&B project associated with the run, if there is one.
+ Offline runs do not have a project URL.
+
+
+ """
+ deprecate.deprecate(
+ field_name=Deprecated.run__get_project_url,
+ warning_message=(
+ "The get_project_url method is deprecated and will be removed in a"
+ " future release. Please use `run.project_url` instead."
+ ),
+ )
+ return self.project_url
+
+ @property
+ @_log_to_run
+ @_attach
+ def project_url(self) -> str | None:
+ """URL of the W&B project associated with the run, if there is one.
+
+ Offline runs do not have a project URL.
+ """
+ if self._settings._offline:
+ wandb.termwarn("URL not available in offline run")
+ return None
+ return self._settings.project_url
+
+ @_raise_if_finished
+ @_log_to_run
+ @_attach
+ def log_code(
+ self,
+ root: str | None = ".",
+ name: str | None = None,
+ include_fn: Callable[[str, str], bool]
+ | Callable[[str], bool] = _is_py_requirements_or_dockerfile,
+ exclude_fn: Callable[[str, str], bool]
+ | Callable[[str], bool] = filenames.exclude_wandb_fn,
+ ) -> Artifact | None:
+ """Save the current state of your code to a W&B Artifact.
+
+ By default, it walks the current directory and logs all files that end with `.py`.
+
+ Args:
+ root: The relative (to `os.getcwd()`) or absolute path to recursively find code from.
+ name: (str, optional) The name of our code artifact. By default, we'll name
+ the artifact `source-$PROJECT_ID-$ENTRYPOINT_RELPATH`. There may be scenarios where you want
+ many runs to share the same artifact. Specifying name allows you to achieve that.
+ include_fn: A callable that accepts a file path and (optionally) root path and
+ returns True when it should be included and False otherwise. This
+ defaults to `lambda path, root: path.endswith(".py")`.
+ exclude_fn: A callable that accepts a file path and (optionally) root path and
+ returns `True` when it should be excluded and `False` otherwise. This
+ defaults to a function that excludes all files within `/.wandb/`
+ and `/wandb/` directories.
+
+ Examples:
+ Basic usage
+
+ ```python
+ import wandb
+
+ with wandb.init() as run:
+ run.log_code()
+ ```
+
+ Advanced usage
+
+ ```python
+ import wandb
+
+ with wandb.init() as run:
+ run.log_code(
+ root="../",
+ include_fn=lambda path: path.endswith(".py") or path.endswith(".ipynb"),
+ exclude_fn=lambda path, root: os.path.relpath(path, root).startswith(
+ "cache/"
+ ),
+ )
+ ```
+
+ Returns:
+ An `Artifact` object if code was logged
+ """
+ if name is None:
+ if self.settings._jupyter:
+ notebook_name = None
+ if self.settings.notebook_name:
+ notebook_name = self.settings.notebook_name
+ elif self.settings.x_jupyter_path:
+ if self.settings.x_jupyter_path.startswith("fileId="):
+ notebook_name = self.settings.x_jupyter_name
+ else:
+ notebook_name = self.settings.x_jupyter_path
+ name_string = f"{self._settings.project}-{notebook_name}"
+ else:
+ name_string = (
+ f"{self._settings.project}-{self._settings.program_relpath}"
+ )
+ name = wandb.util.make_artifact_name_safe(f"source-{name_string}")
+ art = InternalArtifact(name, "code")
+ files_added = False
+ if root is not None:
+ root = os.path.abspath(root)
+ for file_path in filenames.filtered_dir(root, include_fn, exclude_fn):
+ files_added = True
+ save_name = os.path.relpath(file_path, root)
+ art.add_file(file_path, name=save_name)
+ # Add any manually staged files such as ipynb notebooks
+ for dirpath, _, files in os.walk(self._settings._tmp_code_dir):
+ for fname in files:
+ file_path = os.path.join(dirpath, fname)
+ save_name = os.path.relpath(file_path, self._settings._tmp_code_dir)
+ files_added = True
+ art.add_file(file_path, name=save_name)
+ if not files_added:
+ wandb.termwarn(
+ "No relevant files were detected in the specified directory. No code will be logged to your run."
+ )
+ return None
+
+ artifact = self._log_artifact(art)
+
+ self._config.update(
+ {"_wandb": {"code_path": artifact.name}},
+ allow_val_change=True,
+ )
+
+ return artifact
+
+ @_log_to_run
+ def get_sweep_url(self) -> str | None:
+ """This method is deprecated and will be removed in a future release. Use `run.sweep_url` instead.
+
+ The URL of the sweep associated with the run, if there is one.
+ Offline runs do not have a sweep URL.
+
+
+ """
+ deprecate.deprecate(
+ field_name=Deprecated.run__get_sweep_url,
+ warning_message=(
+ "The get_sweep_url method is deprecated and will be removed in a"
+ " future release. Please use `run.sweep_url` instead."
+ ),
+ )
+ return self.sweep_url
+
+ @property
+ @_attach
+ def sweep_url(self) -> str | None:
+ """URL of the sweep associated with the run, if there is one.
+
+ Offline runs do not have a sweep URL.
+ """
+ if self._settings._offline:
+ wandb.termwarn("URL not available in offline run")
+ return None
+ return self._settings.sweep_url
+
+ @_log_to_run
+ def get_url(self) -> str | None:
+ """This method is deprecated and will be removed in a future release. Use `run.url` instead.
+
+ URL of the W&B run, if there is one. Offline runs do not have a URL.
+
+
+ """
+ deprecate.deprecate(
+ field_name=Deprecated.run__get_url,
+ warning_message=(
+ "The get_url method is deprecated and will be removed in a"
+ " future release. Please use `run.url` instead."
+ ),
+ )
+ return self.url
+
+ @property
+ @_log_to_run
+ @_attach
+ def url(self) -> str | None:
+ """The url for the W&B run, if there is one.
+
+ Offline runs will not have a url.
+ """
+ if self._settings._offline:
+ wandb.termwarn("URL not available in offline run")
+ return None
+ return self._settings.run_url
+
+ @property
+ @_log_to_run
+ @_attach
+ def entity(self) -> str:
+ """The name of the W&B entity associated with the run.
+
+ Entity can be a username or the name of a team or organization.
+ """
+ return self._settings.entity or ""
+
+ def _label_internal(
+ self,
+ code: str | None = None,
+ repo: str | None = None,
+ code_version: str | None = None,
+ ) -> None:
+ with telemetry.context(run=self) as tel:
+ if code and RE_LABEL.match(code):
+ tel.label.code_string = code
+ if repo and RE_LABEL.match(repo):
+ tel.label.repo_string = repo
+ if code_version and RE_LABEL.match(code_version):
+ tel.label.code_version = code_version
+
+ def _label(
+ self,
+ code: str | None = None,
+ repo: str | None = None,
+ code_version: str | None = None,
+ **kwargs: str,
+ ) -> None:
+ if self._settings.label_disable:
+ return
+ for k, v in (("code", code), ("repo", repo), ("code_version", code_version)):
+ if v and not RE_LABEL.match(v):
+ wandb.termwarn(
+ f"Label added for '{k}' with invalid identifier '{v}' (ignored).",
+ repeat=False,
+ )
+ for v in kwargs:
+ wandb.termwarn(
+ f"Label added for unsupported key {v!r} (ignored).",
+ repeat=False,
+ )
+
+ self._label_internal(code=code, repo=repo, code_version=code_version)
+
+ # update telemetry in the backend immediately for _label() callers
+ self._telemetry_flush()
+
+ def _label_probe_lines(self, lines: list[str]) -> None:
+ if not lines:
+ return
+ parsed = telemetry._parse_label_lines(lines)
+ if not parsed:
+ return
+ label_dict = {}
+ code = parsed.get("code") or parsed.get("c")
+ if code:
+ label_dict["code"] = code
+ repo = parsed.get("repo") or parsed.get("r")
+ if repo:
+ label_dict["repo"] = repo
+ code_ver = parsed.get("version") or parsed.get("v")
+ if code_ver:
+ label_dict["code_version"] = code_ver
+ self._label_internal(**label_dict)
+
+ def _label_probe_main(self) -> None:
+ m = sys.modules.get("__main__")
+ if not m:
+ return
+ doc = getattr(m, "__doc__", None)
+ if not doc:
+ return
+
+ doclines = doc.splitlines()
+ self._label_probe_lines(doclines)
+
+ # TODO: annotate jupyter Notebook class
+ def _label_probe_notebook(self, notebook: Any) -> None:
+ logger.info("probe notebook")
+ lines = None
+ try:
+ data = notebook.probe_ipynb()
+ cell0 = data.get("cells", [])[0]
+ lines = cell0.get("source")
+ # kaggle returns a string instead of a list
+ if isinstance(lines, str):
+ lines = lines.split()
+ except Exception as e:
+ logger.info(f"Unable to probe notebook: {e}")
+ return
+ if lines:
+ self._label_probe_lines(lines)
+
+ @_log_to_run
+ @_attach
+ def display(self, height: int = 420, hidden: bool = False) -> bool:
+ """Display this run in Jupyter."""
+ if self._settings.silent:
+ return False
+
+ if not ipython.in_jupyter():
+ return False
+
+ try:
+ from IPython import display
+ except ImportError:
+ wandb.termwarn(".display() only works in jupyter environments")
+ return False
+
+ display.display(display.HTML(self.to_html(height, hidden)))
+ return True
+
+ @_log_to_run
+ @_attach
+ def to_html(self, height: int = 420, hidden: bool = False) -> str:
+ """Generate HTML containing an iframe displaying the current run.
+
+
+ """
+ url = self._settings.run_url + "?jupyter=true"
+ style = f"border:none;width:100%;height:{height}px;"
+ prefix = ""
+ if hidden:
+ style += "display:none;"
+ prefix = ipython.toggle_button()
+ return prefix + f""
+
+ def _repr_mimebundle_(
+ self, include: Any | None = None, exclude: Any | None = None
+ ) -> dict[str, str]:
+ return {"text/html": self.to_html(hidden=True)}
+
+ @_log_to_run
+ @_raise_if_finished
+ def _config_callback(
+ self,
+ key: tuple[str, ...] | str | None = None,
+ val: Any | None = None,
+ data: dict[str, object] | None = None,
+ ) -> None:
+ logger.info(f"config_cb {key} {val} {data}")
+ if self._backend and self._backend.interface:
+ self._backend.interface.publish_config(key=key, val=val, data=data)
+
+ @_log_to_run
+ def _config_artifact_callback(
+ self, key: str, val: str | Artifact | dict
+ ) -> Artifact:
+ # artifacts can look like dicts as they are passed into the run config
+ # since the run config stores them on the backend as a dict with fields shown
+ # in wandb.util.artifact_to_json
+ if _is_artifact_version_weave_dict(val):
+ assert isinstance(val, dict)
+ public_api = self._public_api()
+ artifact = Artifact._from_id(val["id"], public_api.client)
+
+ assert artifact
+ return self.use_artifact(artifact)
+ elif _is_artifact_string(val):
+ # this will never fail, but is required to make mypy happy
+ assert isinstance(val, str)
+ artifact_string, base_url, is_id = parse_artifact_string(val)
+ overrides = {}
+ if base_url is not None:
+ overrides = {"base_url": base_url}
+ public_api = public.Api(overrides)
+ else:
+ public_api = self._public_api()
+ if is_id:
+ artifact = Artifact._from_id(artifact_string, public_api._client)
+ else:
+ artifact = public_api._artifact(name=artifact_string)
+ # in the future we'll need to support using artifacts from
+ # different instances of wandb.
+
+ assert artifact
+ return self.use_artifact(artifact)
+ elif _is_artifact_object(val):
+ return self.use_artifact(val)
+ else:
+ raise ValueError(
+ f"Cannot call _config_artifact_callback on type {type(val)}"
+ )
+
+ def _set_config_wandb(self, key: str, val: Any) -> None:
+ self._config_callback(key=("_wandb", key), val=val)
+
+ @_log_to_run
+ @_raise_if_finished
+ def _summary_update_callback(self, summary_record: SummaryRecord) -> None:
+ with telemetry.context(run=self) as tel:
+ tel.feature.set_summary = True
+ if self._backend and self._backend.interface:
+ self._backend.interface.publish_summary(self, summary_record)
+
+ @_log_to_run
+ def _summary_get_current_summary_callback(self) -> dict[str, Any]:
+ if self._is_finished:
+ # TODO: WB-18420: fetch summary from backend and stage it before run is finished
+ wandb.termwarn("Summary data not available in finished run")
+ return {}
+ if not self._backend or not self._backend.interface:
+ return {}
+ handle = self._backend.interface.deliver_get_summary()
+
+ try:
+ result = handle.wait_or(timeout=self._settings.summary_timeout)
+ except TimeoutError:
+ return {}
+
+ get_summary_response = result.response.get_summary_response
+ return proto_util.dict_from_proto_list(get_summary_response.item)
+
+ @_log_to_run
+ def _metric_callback(self, metric_record: MetricRecord) -> None:
+ if self._backend and self._backend.interface:
+ self._backend.interface._publish_metric(metric_record)
+
+ @_log_to_run
+ def _publish_file(self, fname: str) -> None:
+ """Mark a run file to be uploaded with the run.
+
+ This is a W&B-internal function: it can be used by other internal
+ wandb code.
+
+ Args:
+ fname: The path to the file in the run's files directory, relative
+ to the run's files directory.
+ """
+ if not self._backend or not self._backend.interface:
+ return
+ files: FilesDict = dict(files=[(GlobStr(fname), "now")])
+ self._backend.interface.publish_files(files)
+
+ def _pop_all_charts(
+ self,
+ data: dict[str, Any],
+ key_prefix: str | None = None,
+ ) -> dict[str, Any]:
+ """Pops all charts from a dictionary including nested charts.
+
+ This function will return a mapping of the charts and a dot-separated
+ key for each chart. Indicating the path to the chart in the data dictionary.
+ """
+ keys_to_remove = set()
+ charts: dict[str, Any] = {}
+ for k, v in data.items():
+ key = f"{key_prefix}.{k}" if key_prefix else k
+ if isinstance(v, Visualize):
+ keys_to_remove.add(k)
+ charts[key] = v
+ elif isinstance(v, CustomChart):
+ keys_to_remove.add(k)
+ charts[key] = v
+ elif isinstance(v, dict):
+ nested_charts = self._pop_all_charts(v, key)
+ charts.update(nested_charts)
+
+ for k in keys_to_remove:
+ data.pop(k)
+
+ return charts
+
+ def _serialize_custom_charts(
+ self,
+ data: dict[str, Any],
+ ) -> dict[str, Any]:
+ """Process and replace chart objects with their underlying table values.
+
+ This processes the chart objects passed to `wandb.Run.log()`, replacing their entries
+ in the given dictionary (which is saved to the run's history) and adding them
+ to the run's config.
+
+ Args:
+ data: Dictionary containing data that may include plot objects
+ Plot objects can be nested in dictionaries, which will be processed recursively.
+
+ Returns:
+ The processed dictionary with custom charts transformed into tables.
+ """
+ if not data:
+ return data
+
+ charts = self._pop_all_charts(data)
+ for k, v in charts.items():
+ v.set_key(k)
+ self._config_callback(
+ val=v.spec.config_value,
+ key=v.spec.config_key,
+ )
+
+ if isinstance(v, CustomChart):
+ data[v.spec.table_key] = v.table
+ elif isinstance(v, Visualize):
+ data[k] = v.table
+
+ return data
+
+ @_log_to_run
+ def _partial_history_callback(
+ self,
+ data: dict[str, Any],
+ step: int | None = None,
+ commit: bool | None = None,
+ ) -> None:
+ if not (self._backend and self._backend.interface):
+ return
+
+ data = data.copy() # avoid modifying the original data
+
+ # Serialize custom charts before publishing
+ data = self._serialize_custom_charts(data)
+
+ not_using_tensorboard = len(wandb.patched["tensorboard"]) == 0
+ self._backend.interface.publish_partial_history(
+ self,
+ data,
+ user_step=self._step,
+ step=step,
+ flush=commit,
+ publish_step=not_using_tensorboard,
+ )
+
+ @_log_to_run
+ def _console_callback(self, name: str, data: str) -> None:
+ # logger.info("console callback: %s, %s", name, data)
+ if self._backend and self._backend.interface:
+ self._backend.interface.publish_output(name, data)
+
+ @_log_to_run
+ @_raise_if_finished
+ def _console_raw_callback(self, name: str, data: str) -> None:
+ # logger.info("console callback: %s, %s", name, data)
+
+ # NOTE: console output is only allowed on the process which installed the callback
+ # this will prevent potential corruption in the socket to the service. Other methods
+ # are protected by the _attach run decorator, but this callback was installed on the
+ # write function of stdout and stderr streams.
+ console_pid = getattr(self, "_attach_pid", 0)
+ if console_pid != os.getpid():
+ return
+
+ if self._backend and self._backend.interface:
+ self._backend.interface.publish_output_raw(name, data)
+
+ @_log_to_run
+ def _tensorboard_callback(
+ self, logdir: str, save: bool = True, root_logdir: str = ""
+ ) -> None:
+ logger.info("tensorboard callback: %s, %s", logdir, save)
+ if self._backend and self._backend.interface:
+ self._backend.interface.publish_tbdata(logdir, save, root_logdir)
+
+ def _set_library(self, library: _WandbSetup) -> None:
+ self._wl = library
+
+ def _set_backend(self, backend: wandb.sdk.backend.backend.Backend) -> None:
+ self._backend = backend
+
+ def _set_internal_run_interface(
+ self,
+ interface: wandb.sdk.interface.interface_queue.InterfaceQueue,
+ ) -> None:
+ self._internal_run_interface = interface
+
+ def _set_teardown_hooks(self, hooks: list[TeardownHook]) -> None:
+ self._teardown_hooks = hooks
+
+ def _set_run_obj(self, run_obj: RunRecord) -> None: # noqa: C901
+ if run_obj.starting_step:
+ self._starting_step = run_obj.starting_step
+ self._step = run_obj.starting_step
+
+ if run_obj.start_time:
+ self._start_time = run_obj.start_time.ToMicroseconds() / 1e6
+
+ if run_obj.runtime:
+ self._start_runtime = run_obj.runtime
+
+ # Grab the config from resuming
+ if run_obj.config:
+ c_dict = config_util.dict_no_value_from_proto_list(run_obj.config.update)
+ # We update the config object here without triggering the callback
+ self._config._update(c_dict, allow_val_change=True, ignore_locked=True)
+ # Update the summary, this will trigger an un-needed graphql request :(
+ if run_obj.summary:
+ summary_dict = {}
+ for orig in run_obj.summary.update:
+ summary_dict[orig.key] = json.loads(orig.value_json)
+ if summary_dict:
+ self.summary.update(summary_dict)
+
+ # update settings from run_obj
+ if run_obj.run_id:
+ self._settings.run_id = run_obj.run_id
+ if run_obj.entity:
+ self._settings.entity = run_obj.entity
+ if run_obj.project:
+ self._settings.project = run_obj.project
+ if run_obj.run_group:
+ self._settings.run_group = run_obj.run_group
+ if run_obj.job_type:
+ self._settings.run_job_type = run_obj.job_type
+ if run_obj.display_name:
+ self._settings.run_name = run_obj.display_name
+ if run_obj.notes:
+ self._settings.run_notes = run_obj.notes
+ if run_obj.tags:
+ self._settings.run_tags = tuple(run_obj.tags)
+ if run_obj.sweep_id:
+ self._settings.sweep_id = run_obj.sweep_id
+ if run_obj.host:
+ self._settings.host = run_obj.host
+ if run_obj.resumed:
+ self._settings.resumed = run_obj.resumed
+ if run_obj.git:
+ if run_obj.git.remote_url:
+ self._settings.git_remote_url = run_obj.git.remote_url
+ if run_obj.git.commit:
+ self._settings.git_commit = run_obj.git.commit
+
+ if run_obj.forked:
+ self._forked = run_obj.forked
+
+ wandb._sentry.configure_scope(
+ process_context="user",
+ tags=dict(self._settings),
+ )
+
+ def _populate_git_info(self) -> None:
+ from .lib.gitlib import GitRepo
+
+ # Use user-provided git info if available, otherwise resolve it from the environment
+ try:
+ repo = GitRepo(
+ root=self._settings.git_root,
+ remote=self._settings.git_remote,
+ remote_url=self._settings.git_remote_url,
+ commit=self._settings.git_commit,
+ lazy=False,
+ )
+ self._settings.git_remote_url = repo.remote_url
+ self._settings.git_commit = repo.last_commit
+ except Exception:
+ wandb.termwarn("Cannot find valid git repo associated with this directory.")
+
+ def _add_singleton(
+ self, data_type: str, key: str, value: dict[int | str, str]
+ ) -> None:
+ """Store a singleton item to wandb config.
+
+ A singleton in this context is a piece of data that is continually
+ logged with the same value in each history step, but represented
+ as a single item in the config.
+
+ We do this to avoid filling up history with a lot of repeated unnecessary data
+
+ Add singleton can be called many times in one run, and it will only be
+ updated when the value changes. The last value logged will be the one
+ persisted to the server.
+ """
+ value_extra = {"type": data_type, "key": key, "value": value}
+
+ if data_type not in self._config["_wandb"]:
+ self._config["_wandb"][data_type] = {}
+
+ if data_type in self._config["_wandb"][data_type]:
+ old_value = self._config["_wandb"][data_type][key]
+ else:
+ old_value = None
+
+ if value_extra != old_value:
+ self._config["_wandb"][data_type][key] = value_extra
+ self._config.persist()
+
+ def _log(
+ self,
+ data: dict[str, Any],
+ step: int | None = None,
+ commit: bool | None = None,
+ ) -> None:
+ if not isinstance(data, Mapping):
+ raise TypeError("wandb.log must be passed a dictionary")
+
+ if any(not isinstance(key, str) for key in data.keys()):
+ raise TypeError("Key values passed to `wandb.log` must be strings.")
+
+ self._partial_history_callback(data, step, commit)
+
+ if step is not None:
+ if os.getpid() != self._init_pid or self._is_attached:
+ wandb.termwarn(
+ "Note that setting step in multiprocessing can result in data loss. "
+ "Please use `run.define_metric(...)` to define a custom metric "
+ "to log your step values.",
+ repeat=False,
+ )
+ # if step is passed in when tensorboard_sync is used we honor the step passed
+ # to make decisions about how to close out the history record, but will strip
+ # this history later on in publish_history()
+ if len(wandb.patched["tensorboard"]) > 0:
+ wandb.termwarn(
+ "Step cannot be set when using tensorboard syncing. "
+ "Please use `run.define_metric(...)` to define a custom metric "
+ "to log your step values.",
+ repeat=False,
+ )
+ if step > self._step:
+ self._step = step
+
+ if (step is None and commit is None) or commit:
+ self._step += 1
+
+ @_log_to_run
+ @_raise_if_finished
+ @_attach
+ def log(
+ self,
+ data: dict[str, Any],
+ step: int | None = None,
+ commit: bool | None = None,
+ ) -> None:
+ """Upload run data.
+
+ Use `log` to log data from runs, such as scalars, images, video,
+ histograms, plots, and tables. See [Log objects and media](https://docs.wandb.ai/guides/track/log) for
+ code snippets, best practices, and more.
+
+ Basic usage:
+
+ ```python
+ import wandb
+
+ with wandb.init() as run:
+ run.log({"train-loss": 0.5, "accuracy": 0.9})
+ ```
+
+ The previous code snippet saves the loss and accuracy to the run's
+ history and updates the summary values for these metrics.
+
+ Visualize logged data in a workspace at [wandb.ai](https://wandb.ai),
+ or locally on a [self-hosted instance](https://docs.wandb.ai/guides/hosting)
+ of the W&B app, or export data to visualize and explore locally, such as in a
+ Jupyter notebook, with the [Public API](https://docs.wandb.ai/guides/track/public-api-guide).
+
+ Logged values don't have to be scalars. You can log any
+ [W&B supported Data Type](https://docs.wandb.ai/ref/python/data-types/)
+ such as images, audio, video, and more. For example, you can use
+ `wandb.Table` to log structured data. See
+ [Log tables, visualize and query data](https://docs.wandb.ai/guides/models/tables/tables-walkthrough)
+ tutorial for more details.
+
+ W&B organizes metrics with a forward slash (`/`) in their name
+ into sections named using the text before the final slash. For example,
+ the following results in two sections named "train" and "validate":
+
+ ```python
+ with wandb.init() as run:
+ # Log metrics in the "train" section.
+ run.log(
+ {
+ "train/accuracy": 0.9,
+ "train/loss": 30,
+ "validate/accuracy": 0.8,
+ "validate/loss": 20,
+ }
+ )
+ ```
+
+ Only one level of nesting is supported; `run.log({"a/b/c": 1})`
+ produces a section named "a/b".
+
+ `run.log()` is not intended to be called more than a few times per second.
+ For optimal performance, limit your logging to once every N iterations,
+ or collect data over multiple iterations and log it in a single step.
+
+ By default, each call to `log` creates a new "step".
+ The step must always increase, and it is not possible to log
+ to a previous step. You can use any metric as the X axis in charts.
+ See [Custom log axes](https://docs.wandb.ai/guides/track/log/customize-logging-axes/)
+ for more details.
+
+ In many cases, it is better to treat the W&B step like
+ you'd treat a timestamp rather than a training step.
+
+ ```python
+ with wandb.init() as run:
+ # Example: log an "epoch" metric for use as an X axis.
+ run.log({"epoch": 40, "train-loss": 0.5})
+ ```
+
+ It is possible to use multiple `wandb.Run.log()` invocations to log to
+ the same step with the `step` and `commit` parameters.
+ The following are all equivalent:
+
+ ```python
+ with wandb.init() as run:
+ # Normal usage:
+ run.log({"train-loss": 0.5, "accuracy": 0.8})
+ run.log({"train-loss": 0.4, "accuracy": 0.9})
+
+ # Implicit step without auto-incrementing:
+ run.log({"train-loss": 0.5}, commit=False)
+ run.log({"accuracy": 0.8})
+ run.log({"train-loss": 0.4}, commit=False)
+ run.log({"accuracy": 0.9})
+
+ # Explicit step:
+ run.log({"train-loss": 0.5}, step=current_step)
+ run.log({"accuracy": 0.8}, step=current_step)
+ current_step += 1
+ run.log({"train-loss": 0.4}, step=current_step)
+ run.log({"accuracy": 0.9}, step=current_step)
+ ```
+
+ Args:
+ data: A `dict` with `str` keys and values that are serializable
+ Python objects including: `int`, `float` and `string`;
+ any of the `wandb.data_types`; lists, tuples and NumPy arrays
+ of serializable Python objects; other `dict`s of this
+ structure.
+ step: The step number to log. If `None`, then an implicit
+ auto-incrementing step is used. See the notes in
+ the description.
+ commit: If true, finalize and upload the step. If false, then
+ accumulate data for the step. See the notes in the description.
+ If `step` is `None`, then the default is `commit=True`;
+ otherwise, the default is `commit=False`.
+
+ Examples:
+ For more and more detailed examples, see
+ [our guides to logging](https://docs.wandb.com/guides/track/log).
+
+ Basic usage
+
+ ```python
+ import wandb
+
+ with wandb.init() as run:
+ run.log({"train-loss": 0.5, "accuracy": 0.9
+ ```
+
+ Incremental logging
+
+ ```python
+ import wandb
+
+ with wandb.init() as run:
+ run.log({"loss": 0.2}, commit=False)
+ # Somewhere else when I'm ready to report this step:
+ run.log({"accuracy": 0.8})
+ ```
+
+ Histogram
+
+ ```python
+ import numpy as np
+ import wandb
+
+ # sample gradients at random from normal distribution
+ gradients = np.random.randn(100, 100)
+ with wandb.init() as run:
+ run.log({"gradients": wandb.Histogram(gradients)})
+ ```
+
+ Image from NumPy
+
+ ```python
+ import numpy as np
+ import wandb
+
+ with wandb.init() as run:
+ examples = []
+ for i in range(3):
+ pixels = np.random.randint(low=0, high=256, size=(100, 100, 3))
+ image = wandb.Image(pixels, caption=f"random field {i}")
+ examples.append(image)
+ run.log({"examples": examples})
+ ```
+
+ Image from PIL
+
+ ```python
+ import numpy as np
+ from PIL import Image as PILImage
+ import wandb
+
+ with wandb.init() as run:
+ examples = []
+ for i in range(3):
+ pixels = np.random.randint(
+ low=0,
+ high=256,
+ size=(100, 100, 3),
+ dtype=np.uint8,
+ )
+ pil_image = PILImage.fromarray(pixels, mode="RGB")
+ image = wandb.Image(pil_image, caption=f"random field {i}")
+ examples.append(image)
+ run.log({"examples": examples})
+ ```
+
+ Video from NumPy
+
+ ```python
+ import numpy as np
+ import wandb
+
+ with wandb.init() as run:
+ # axes are (time, channel, height, width)
+ frames = np.random.randint(
+ low=0,
+ high=256,
+ size=(10, 3, 100, 100),
+ dtype=np.uint8,
+ )
+ run.log({"video": wandb.Video(frames, fps=4)})
+ ```
+
+ Matplotlib plot
+
+ ```python
+ from matplotlib import pyplot as plt
+ import numpy as np
+ import wandb
+
+ with wandb.init() as run:
+ fig, ax = plt.subplots()
+ x = np.linspace(0, 10)
+ y = x * x
+ ax.plot(x, y) # plot y = x^2
+ run.log({"chart": fig})
+ ```
+
+ PR Curve
+
+ ```python
+ import wandb
+
+ with wandb.init() as run:
+ run.log({"pr": wandb.plot.pr_curve(y_test, y_probas, labels)})
+ ```
+
+ 3D Object
+
+ ```python
+ import wandb
+
+ with wandb.init() as run:
+ run.log(
+ {
+ "generated_samples": [
+ wandb.Object3D(open("sample.obj")),
+ wandb.Object3D(open("sample.gltf")),
+ wandb.Object3D(open("sample.glb")),
+ ]
+ }
+ )
+ ```
+
+ Raises:
+ wandb.Error: If called before `wandb.init()`.
+ ValueError: If invalid data is passed.
+
+ """
+ if step is not None:
+ with telemetry.context(run=self) as tel:
+ tel.feature.set_step_log = True
+
+ if self._settings._shared and step is not None:
+ wandb.termwarn(
+ "In shared mode, the use of `wandb.log` with the step argument is not supported "
+ f"and will be ignored. Please refer to {url_registry.url('define-metric')} "
+ "on how to customize your x-axis.",
+ repeat=False,
+ )
+ self._log(data=data, step=step, commit=commit)
+
+ @_log_to_run
+ @_raise_if_finished
+ @_attach
+ def save(
+ self,
+ glob_str: str | os.PathLike,
+ base_path: str | os.PathLike | None = None,
+ policy: PolicyName = "live",
+ ) -> bool | list[str]:
+ """Sync one or more files to W&B.
+
+ Relative paths are relative to the current working directory.
+
+ A Unix glob, such as "myfiles/*", is expanded at the time `save` is
+ called regardless of the `policy`. In particular, new files are not
+ picked up automatically.
+
+ A `base_path` may be provided to control the directory structure of
+ uploaded files. It should be a prefix of `glob_str`, and the directory
+ structure beneath it is preserved.
+
+ When given an absolute path or glob and no `base_path`, one
+ directory level is preserved as in the example above.
+
+ Files are automatically deduplicated: calling `save()` multiple times
+ on the same file without modifications will not re-upload it.
+
+ Args:
+ glob_str: A relative or absolute path or Unix glob.
+ base_path: A path to use to infer a directory structure; see examples.
+ policy: One of `live`, `now`, or `end`.
+ - live: upload the file as it changes, overwriting the previous version
+ - now: upload the file once now
+ - end: upload file when the run ends
+
+ Returns:
+ Paths to the symlinks created for the matched files.
+
+ For historical reasons, this may return a boolean in legacy code.
+
+ ```python
+ import wandb
+
+ run = wandb.init()
+
+ run.save("these/are/myfiles/*")
+ # => Saves files in a "these/are/myfiles/" folder in the run.
+
+ run.save("these/are/myfiles/*", base_path="these")
+ # => Saves files in an "are/myfiles/" folder in the run.
+
+ run.save("/Users/username/Documents/run123/*.txt")
+ # => Saves files in a "run123/" folder in the run. See note below.
+
+ run.save("/Users/username/Documents/run123/*.txt", base_path="/Users")
+ # => Saves files in a "username/Documents/run123/" folder in the run.
+
+ run.save("files/*/saveme.txt")
+ # => Saves each "saveme.txt" file in an appropriate subdirectory
+ # of "files/".
+
+ # Explicitly finish the run since a context manager is not used.
+ run.finish()
+ ```
+ """
+ if isinstance(glob_str, bytes):
+ # Preserved for backward compatibility: allow bytes inputs.
+ glob_str = glob_str.decode("utf-8")
+ if isinstance(glob_str, str) and (glob_str.startswith(("gs://", "s3://"))):
+ # Provide a better error message for a common misuse.
+ wandb.termlog(f"{glob_str} is a cloud storage url, can't save file to W&B.")
+ return []
+ # NOTE: We use PurePath instead of Path because WindowsPath doesn't
+ # like asterisks and errors out in resolve(). It also makes logical
+ # sense: globs aren't real paths, they're just path-like strings.
+ glob_path = pathlib.PurePath(glob_str)
+ resolved_glob_path = pathlib.PurePath(os.path.abspath(glob_path))
+
+ if base_path is not None:
+ base_path = pathlib.Path(base_path)
+ elif not glob_path.is_absolute():
+ base_path = pathlib.Path(".")
+ else:
+ # Absolute glob paths with no base path get special handling.
+ wandb.termwarn(
+ "Saving files without folders. If you want to preserve "
+ "subdirectories pass base_path to wandb.save, i.e. "
+ 'wandb.save("/mnt/folder/file.h5", base_path="/mnt")',
+ repeat=False,
+ )
+ base_path = resolved_glob_path.parent.parent
+
+ if policy not in ("live", "end", "now"):
+ raise ValueError(
+ 'Only "live", "end" and "now" policies are currently supported.'
+ )
+
+ resolved_base_path = pathlib.PurePath(os.path.abspath(base_path))
+
+ return self._save(
+ resolved_glob_path,
+ resolved_base_path,
+ policy,
+ )
+
+ def _save(
+ self,
+ glob_path: pathlib.PurePath,
+ base_path: pathlib.PurePath,
+ policy: PolicyName,
+ ) -> list[str]:
+ # Can't use is_relative_to() because that's added in Python 3.9,
+ # but we support down to Python 3.8.
+ if not str(glob_path).startswith(str(base_path)):
+ raise ValueError("Glob may not walk above the base path")
+
+ if glob_path == base_path:
+ raise ValueError("Glob cannot be the same as the base path")
+
+ relative_glob = glob_path.relative_to(base_path)
+ if relative_glob.parts[0] == "*":
+ raise ValueError("Glob may not start with '*' relative to the base path")
+ relative_glob_str = GlobStr(str(relative_glob))
+
+ with telemetry.context(run=self) as tel:
+ tel.feature.save = True
+
+ # Files in the files directory matched by the glob, including old and
+ # new ones.
+ globbed_files = set(
+ pathlib.Path(
+ self._settings.files_dir,
+ ).glob(relative_glob_str)
+ )
+
+ had_symlinked_files = len(globbed_files) > 0
+ is_star_glob = "*" in relative_glob_str
+
+ # The base_path may itself be a glob, so we can't do
+ # base_path.glob(relative_glob_str)
+ for path_str in glob.glob(str(base_path / relative_glob_str)):
+ source_path = pathlib.Path(path_str).absolute()
+
+ # We can't use relative_to() because base_path may be a glob.
+ relative_path = pathlib.Path(*source_path.parts[len(base_path.parts) :])
+
+ target_path = pathlib.Path(self._settings.files_dir, relative_path)
+ globbed_files.add(target_path)
+
+ # If the file is already where it needs to be, don't create a symlink.
+ if source_path.resolve() == target_path.resolve():
+ continue
+
+ target_path.parent.mkdir(parents=True, exist_ok=True)
+
+ # Delete the symlink if it exists.
+ target_path.unlink(missing_ok=True)
+
+ target_path.symlink_to(source_path)
+
+ # Inform users that new files aren't detected automatically.
+ if not had_symlinked_files and is_star_glob:
+ file_str = f"{len(globbed_files)} file"
+ if len(globbed_files) > 1:
+ file_str += "s"
+ wandb.termwarn(
+ f"Symlinked {file_str} into the W&B run directory, "
+ "call wandb.save again to sync new files."
+ )
+
+ files_dict: FilesDict = {
+ "files": [
+ (
+ GlobStr(str(f.relative_to(self._settings.files_dir))),
+ policy,
+ )
+ for f in globbed_files
+ ]
+ }
+ if self._backend and self._backend.interface:
+ self._backend.interface.publish_files(files_dict)
+
+ return [str(f) for f in globbed_files]
+
+ @_log_to_run
+ @_attach
+ def restore(
+ self,
+ name: str,
+ run_path: str | None = None,
+ replace: bool = False,
+ root: str | None = None,
+ ) -> None | TextIO:
+ return restore(
+ name,
+ run_path or self._get_path(),
+ replace,
+ root or self._settings.files_dir,
+ )
+
+ @_log_to_run
+ @_attach
+ def finish(
+ self,
+ exit_code: int | None = None,
+ quiet: bool | None = None,
+ ) -> None:
+ """Finish a run and upload any remaining data.
+
+ Marks the completion of a W&B run and ensures all data is synced to the server.
+ The run's final state is determined by its exit conditions and sync status.
+
+ Run States:
+ - Running: Active run that is logging data and/or sending heartbeats.
+ - Crashed: Run that stopped sending heartbeats unexpectedly.
+ - Finished: Run completed successfully (`exit_code=0`) with all data synced.
+ - Failed: Run completed with errors (`exit_code!=0`).
+ - Killed: Run was forcibly stopped before it could finish.
+
+ Args:
+ exit_code: Integer indicating the run's exit status. Use 0 for success,
+ any other value marks the run as failed.
+ quiet: Deprecated. Configure logging verbosity using `wandb.Settings(quiet=...)`.
+ """
+ if quiet is not None:
+ deprecate.deprecate(
+ field_name=Deprecated.run__finish_quiet,
+ warning_message=(
+ "The `quiet` argument to `wandb.run.finish()` is deprecated, "
+ "use `wandb.Settings(quiet=...)` to set this instead."
+ ),
+ run=self,
+ )
+ return self._finish(exit_code)
+
+ @_log_to_run
+ def _finish(
+ self,
+ exit_code: int | None = None,
+ ) -> None:
+ if self._is_finished:
+ return
+
+ assert self._wl
+
+ logger.info(f"finishing run {self._get_path()}")
+ with telemetry.context(run=self) as tel:
+ tel.feature.finish = True
+
+ # Run hooks that need to happen before the last messages to the
+ # internal service, like Jupyter hooks.
+ for hook in self._teardown_hooks:
+ if hook.stage == TeardownStage.EARLY:
+ hook.call()
+
+ # Early-stage hooks may use methods that require _is_finished
+ # to be False, so we set this after running those hooks.
+ self._is_finished = True
+ self._wl.remove_active_run(self)
+
+ try:
+ self._atexit_cleanup(exit_code=exit_code)
+
+ # Run hooks that should happen after the last messages to the
+ # internal service, like detaching the logger.
+ for hook in self._teardown_hooks:
+ if hook.stage == TeardownStage.LATE:
+ hook.call()
+ self._teardown_hooks = []
+
+ # Inform the service that we're done sending messages for this run.
+ #
+ # TODO: Why not do this in _atexit_cleanup()?
+ if self._settings.run_id:
+ service = self._wl.assert_service()
+ service.inform_finish(run_id=self._settings.run_id)
+
+ finally:
+ if wandb.run is self:
+ module.unset_globals()
+ wandb._sentry.end_session()
+
+ @_log_to_run
+ @_raise_if_finished
+ @_attach
+ def status(
+ self,
+ ) -> RunStatus:
+ """Get sync info from the internal backend, about the current run's sync status."""
+ if not self._backend or not self._backend.interface:
+ return RunStatus()
+
+ handle_run_status = self._backend.interface.deliver_request_run_status()
+ result = handle_run_status.wait_or(timeout=None)
+ sync_data = result.response.run_status_response
+
+ sync_time = None
+ if sync_data.sync_time.seconds:
+ sync_time = datetime.fromtimestamp(
+ sync_data.sync_time.seconds + sync_data.sync_time.nanos / 1e9
+ )
+ return RunStatus(
+ sync_items_total=sync_data.sync_items_total,
+ sync_items_pending=sync_data.sync_items_pending,
+ sync_time=sync_time,
+ )
+
+ def _add_panel(
+ self, visualize_key: str, panel_type: str, panel_config: dict
+ ) -> None:
+ config = {
+ "panel_type": panel_type,
+ "panel_config": panel_config,
+ }
+ self._config_callback(val=config, key=("_wandb", "visualize", visualize_key))
+
+ def _redirect(
+ self,
+ stdout_slave_fd: int | None,
+ stderr_slave_fd: int | None,
+ console: str | None = None,
+ ) -> None:
+ if console is None:
+ console = self._settings.console
+ # only use raw for service to minimize potential changes
+ if console == "wrap":
+ console = "wrap_raw"
+ logger.info("redirect: %s", console)
+
+ out_redir: redirect.RedirectBase
+ err_redir: redirect.RedirectBase
+
+ # raw output handles the output_log writing in the internal process
+ if console in {"redirect", "wrap_emu"}:
+ output_log_path = os.path.join(
+ self._settings.files_dir, filenames.OUTPUT_FNAME
+ )
+ # output writer might have been set up, see wrap_fallback case
+ if not self._output_writer:
+ self._output_writer = filesystem.CRDedupedFile(
+ open(output_log_path, "wb")
+ )
+
+ if console == "redirect":
+ logger.info("Redirecting console.")
+ out_redir = redirect.Redirect(
+ src="stdout",
+ cbs=[
+ lambda data: self._console_callback("stdout", data),
+ self._output_writer.write, # type: ignore
+ ],
+ flush_periodically=(self._settings.mode == "online"),
+ )
+ err_redir = redirect.Redirect(
+ src="stderr",
+ cbs=[
+ lambda data: self._console_callback("stderr", data),
+ self._output_writer.write, # type: ignore
+ ],
+ flush_periodically=(self._settings.mode == "online"),
+ )
+ if os.name == "nt":
+
+ def wrap_fallback() -> None:
+ if self._out_redir:
+ self._out_redir.uninstall()
+ if self._err_redir:
+ self._err_redir.uninstall()
+ msg = (
+ "Tensorflow detected. Stream redirection is not supported "
+ "on Windows when tensorflow is imported. Falling back to "
+ "wrapping stdout/err."
+ )
+ wandb.termlog(msg)
+ self._redirect(None, None, console="wrap")
+
+ add_import_hook("tensorflow", wrap_fallback)
+ elif console == "wrap_emu":
+ logger.info("Wrapping output streams.")
+ out_redir = redirect.StreamWrapper(
+ src="stdout",
+ cbs=[
+ lambda data: self._console_callback("stdout", data),
+ self._output_writer.write, # type: ignore
+ ],
+ flush_periodically=(self._settings.mode == "online"),
+ )
+ err_redir = redirect.StreamWrapper(
+ src="stderr",
+ cbs=[
+ lambda data: self._console_callback("stderr", data),
+ self._output_writer.write, # type: ignore
+ ],
+ flush_periodically=(self._settings.mode == "online"),
+ )
+ elif console == "wrap_raw":
+ logger.info("Wrapping output streams.")
+ out_redir = redirect.StreamRawWrapper(
+ src="stdout",
+ cbs=[
+ lambda data: self._console_raw_callback("stdout", data),
+ ],
+ )
+ err_redir = redirect.StreamRawWrapper(
+ src="stderr",
+ cbs=[
+ lambda data: self._console_raw_callback("stderr", data),
+ ],
+ )
+ elif console == "off":
+ return
+ else:
+ raise ValueError("unhandled console")
+ try:
+ # save stdout and stderr before installing new write functions
+ out_redir.install()
+ err_redir.install()
+ self._out_redir = out_redir
+ self._err_redir = err_redir
+ logger.info("Redirects installed.")
+ except Exception as e:
+ wandb.termwarn(f"Failed to redirect: {e}")
+ logger.exception("Failed to redirect.")
+ return
+
+ def _restore(self) -> None:
+ logger.info("restore")
+ # TODO(jhr): drain and shutdown all threads
+ if self._out_redir:
+ self._out_redir.uninstall()
+ if self._err_redir:
+ self._err_redir.uninstall()
+ logger.info("restore done")
+
+ def _atexit_cleanup(self, exit_code: int | None = None) -> None:
+ if self._backend is None:
+ logger.warning("process exited without backend configured")
+ return
+ if self._atexit_cleanup_called:
+ return
+ self._atexit_cleanup_called = True
+
+ exit_code = exit_code or (self._hooks and self._hooks.exit_code) or 0
+ self._exit_code = exit_code
+ logger.info(f"got exitcode: {exit_code}")
+
+ # Delete this run's "resume" file if the run finished successfully.
+ #
+ # This is used by the "auto" resume mode, which resumes from the last
+ # failed (or unfinished/crashed) run. If we reach this line, then this
+ # run shouldn't be a candidate for "auto" resume.
+ if exit_code == 0:
+ if os.path.exists(self._settings.resume_fname):
+ os.remove(self._settings.resume_fname)
+
+ try:
+ self._on_finish()
+
+ except KeyboardInterrupt:
+ if not wandb.wandb_agent._is_running(): # type: ignore
+ wandb.termerror("Control-C detected -- Run data was not synced")
+ raise
+
+ except Exception:
+ self._console_stop()
+ logger.exception("Problem finishing run")
+ wandb.termerror("Problem finishing run")
+ raise
+
+ Run._footer(
+ sampled_history=self._sampled_history,
+ final_summary=self._final_summary,
+ poll_exit_response=self._poll_exit_response,
+ internal_messages_response=self._internal_messages_response,
+ settings=self._settings,
+ printer=self._printer,
+ )
+
+ def _console_start(self) -> None:
+ logger.info("atexit reg")
+ self._hooks = ExitHooks()
+
+ self._redirect(self._stdout_slave_fd, self._stderr_slave_fd)
+
+ def _console_stop(self) -> None:
+ self._restore()
+ if self._output_writer:
+ self._output_writer.close()
+ self._output_writer = None
+
+ def _on_start(self) -> None:
+ self._header()
+
+ if self._settings.save_code and self._settings.code_dir is not None:
+ self.log_code(self._settings.code_dir)
+
+ if self._settings.x_save_requirements:
+ if self._backend and self._backend.interface:
+ from wandb.util import working_set
+
+ logger.debug(
+ "Saving list of pip packages installed into the current environment"
+ )
+ self._backend.interface.publish_python_packages(working_set())
+
+ if self._backend and self._backend.interface and not self._settings._offline:
+ assert self._settings.run_id
+ self._run_status_checker = RunStatusChecker(
+ self._settings.run_id,
+ interface=self._backend.interface,
+ settings=self._settings,
+ )
+ self._run_status_checker.start()
+
+ self._console_start()
+ self._on_ready()
+
+ def _on_attach(self) -> None:
+ """Event triggered when run is attached to another run."""
+ with telemetry.context(run=self) as tel:
+ tel.feature.attach = True
+
+ self._is_attached = True
+ self._on_ready()
+
+ def _register_telemetry_import_hooks(
+ self,
+ ) -> None:
+ def _telemetry_import_hook(
+ run: Run,
+ module: Any,
+ ) -> None:
+ with telemetry.context(run=run) as tel:
+ try:
+ name = getattr(module, "__name__", None)
+ if name is not None:
+ setattr(tel.imports_finish, name, True)
+ except AttributeError:
+ return
+
+ import_telemetry_set = telemetry.list_telemetry_imports()
+ import_hook_fn = functools.partial(_telemetry_import_hook, self)
+ if not self._settings.run_id:
+ return
+ for module_name in import_telemetry_set:
+ register_post_import_hook(
+ import_hook_fn,
+ self._settings.run_id,
+ module_name,
+ )
+
+ def _on_ready(self) -> None:
+ """Event triggered when run is ready for the user."""
+ assert self._wl
+ self._wl.add_active_run(self)
+
+ self._register_telemetry_import_hooks()
+
+ # start reporting any telemetry changes
+ self._telemetry_obj_active = True
+ self._telemetry_flush()
+
+ try:
+ self._detect_and_apply_job_inputs()
+ except Exception:
+ logger.exception("Problem applying launch job inputs")
+
+ # object is about to be returned to the user, don't let them modify it
+ self._freeze()
+
+ if not self._settings.resume:
+ if os.path.exists(self._settings.resume_fname):
+ os.remove(self._settings.resume_fname)
+
+ def _detect_and_apply_job_inputs(self) -> None:
+ """If the user has staged launch inputs, apply them to the run."""
+ from wandb.sdk.launch.inputs.internal import StagedLaunchInputs
+
+ StagedLaunchInputs().apply(self)
+
+ def _make_job_source_reqs(self) -> tuple[list[str], dict[str, Any], dict[str, Any]]:
+ from wandb.util import working_set
+
+ installed_packages_list = sorted(f"{d.key}=={d.version}" for d in working_set())
+ input_types = TypeRegistry.type_of(self.config.as_dict()).to_json()
+ output_types = TypeRegistry.type_of(self.summary._as_dict()).to_json()
+
+ return installed_packages_list, input_types, output_types
+
+ def _construct_job_artifact(
+ self,
+ name: str,
+ source_dict: JobSourceDict,
+ installed_packages_list: list[str],
+ patch_path: os.PathLike | None = None,
+ ) -> Artifact:
+ job_artifact = InternalArtifact(name, job_builder.JOB_ARTIFACT_TYPE)
+ if patch_path and os.path.exists(patch_path):
+ job_artifact.add_file(FilePathStr(patch_path), "diff.patch")
+ with job_artifact.new_file("requirements.frozen.txt") as f:
+ f.write("\n".join(installed_packages_list))
+ with job_artifact.new_file("wandb-job.json") as f:
+ f.write(json.dumps(source_dict))
+
+ return job_artifact
+
+ def _create_image_job(
+ self,
+ input_types: dict[str, Any],
+ output_types: dict[str, Any],
+ installed_packages_list: list[str],
+ docker_image_name: str | None = None,
+ args: list[str] | None = None,
+ ) -> Artifact | None:
+ docker_image_name = docker_image_name or os.getenv("WANDB_DOCKER")
+
+ if not docker_image_name:
+ return None
+
+ name = wandb.util.make_artifact_name_safe(f"job-{docker_image_name}")
+ s_args: Sequence[str] = args if args is not None else self._settings._args
+ source_info: JobSourceDict = {
+ "_version": "v0",
+ "source_type": "image",
+ "source": {"image": docker_image_name, "args": s_args},
+ "input_types": input_types,
+ "output_types": output_types,
+ "runtime": self._settings._python,
+ }
+ job_artifact = self._construct_job_artifact(
+ name, source_info, installed_packages_list
+ )
+
+ return job_artifact
+
+ def _log_job_artifact_with_image(
+ self, docker_image_name: str, args: list[str] | None = None
+ ) -> Artifact:
+ packages, in_types, out_types = self._make_job_source_reqs()
+ job_artifact = self._create_image_job(
+ in_types,
+ out_types,
+ packages,
+ args=args,
+ docker_image_name=docker_image_name,
+ )
+
+ assert job_artifact
+ artifact = self.log_artifact(job_artifact)
+
+ if not artifact:
+ raise wandb.Error(f"Job Artifact log unsuccessful: {artifact}")
+ else:
+ return artifact
+
+ async def _display_finish_stats(
+ self,
+ progress_printer: progress.ProgressPrinter,
+ ) -> None:
+ last_result: Result | None = None
+
+ async def loop_update_printer() -> None:
+ while True:
+ if last_result:
+ progress_printer.update(
+ [last_result.response.poll_exit_response],
+ )
+ await asyncio.sleep(0.1)
+
+ async def loop_poll_exit() -> None:
+ nonlocal last_result
+ assert self._backend and self._backend.interface
+
+ while True:
+ handle = await self._backend.interface.deliver_async(
+ pb.Record(request=pb.Request(poll_exit=pb.PollExitRequest()))
+ )
+
+ time_start = time.monotonic()
+ last_result = await handle.wait_async(timeout=None)
+
+ # Update at most once a second.
+ time_elapsed = time.monotonic() - time_start
+ if time_elapsed < 1:
+ await asyncio.sleep(1 - time_elapsed)
+
+ async with asyncio_compat.open_task_group() as task_group:
+ task_group.start_soon(loop_update_printer())
+ task_group.start_soon(loop_poll_exit())
+
+ def _on_finish(self) -> None:
+ trigger.call("on_finished")
+
+ if self._run_status_checker is not None:
+ self._run_status_checker.stop()
+
+ self._console_stop() # TODO: there's a race here with jupyter console logging
+
+ assert self._backend and self._backend.interface
+
+ if self._settings.x_update_finish_state:
+ exit_handle = self._backend.interface.deliver_exit(self._exit_code)
+ else:
+ exit_handle = self._backend.interface.deliver_finish_without_exit()
+
+ with progress.progress_printer(
+ self._printer,
+ default_text="Finishing up...",
+ ) as progress_printer:
+ # Wait for the run to complete.
+ wait_with_progress(
+ exit_handle,
+ timeout=None,
+ display_progress=functools.partial(
+ self._display_finish_stats,
+ progress_printer,
+ ),
+ )
+
+ poll_exit_handle = self._backend.interface.deliver_poll_exit()
+ result = poll_exit_handle.wait_or(timeout=None)
+ self._poll_exit_response = result.response.poll_exit_response
+
+ internal_messages_handle = self._backend.interface.deliver_internal_messages()
+ result = internal_messages_handle.wait_or(timeout=None)
+ self._internal_messages_response = result.response.internal_messages_response
+
+ # dispatch all our final requests
+
+ final_summary_handle = self._backend.interface.deliver_get_summary()
+ sampled_history_handle = (
+ self._backend.interface.deliver_request_sampled_history()
+ )
+
+ result = sampled_history_handle.wait_or(timeout=None)
+ self._sampled_history = result.response.sampled_history_response
+
+ result = final_summary_handle.wait_or(timeout=None)
+ self._final_summary = result.response.get_summary_response
+
+ if self._backend:
+ self._backend.cleanup()
+
+ if self._run_status_checker:
+ self._run_status_checker.join()
+
+ if self._settings.run_id:
+ self._unregister_telemetry_import_hooks(self._settings.run_id)
+
+ @staticmethod
+ def _unregister_telemetry_import_hooks(run_id: str) -> None:
+ import_telemetry_set = telemetry.list_telemetry_imports()
+ for module_name in import_telemetry_set:
+ unregister_post_import_hook(module_name, run_id)
+
+ @_log_to_run
+ @_raise_if_finished
+ @_attach
+ def define_metric(
+ self,
+ name: str,
+ step_metric: str | wandb_metric.Metric | None = None,
+ step_sync: bool | None = None,
+ hidden: bool | None = None,
+ summary: str | None = None,
+ goal: str | None = None,
+ overwrite: bool | None = None,
+ ) -> wandb_metric.Metric:
+ """Customize metrics logged with `wandb.Run.log()`.
+
+ Args:
+ name: The name of the metric to customize.
+ step_metric: The name of another metric to serve as the X-axis
+ for this metric in automatically generated charts.
+ step_sync: Automatically insert the last value of step_metric into
+ `wandb.Run.log()` if it is not provided explicitly. Defaults to True
+ if step_metric is specified.
+ hidden: Hide this metric from automatic plots.
+ summary: Specify aggregate metrics added to summary.
+ Supported aggregations include "min", "max", "mean", "last",
+ "first", "best", "copy" and "none". "none" prevents a summary
+ from being generated. "best" is used together with the goal
+ parameter, "best" is deprecated and should not be used, use
+ "min" or "max" instead. "copy" is deprecated and should not be
+ used.
+ goal: Specify how to interpret the "best" summary type.
+ Supported options are "minimize" and "maximize". "goal" is
+ deprecated and should not be used, use "min" or "max" instead.
+ overwrite: If false, then this call is merged with previous
+ `define_metric` calls for the same metric by using their
+ values for any unspecified parameters. If true, then
+ unspecified parameters overwrite values specified by
+ previous calls.
+
+ Returns:
+ An object that represents this call but can otherwise be discarded.
+ """
+ if summary and "copy" in summary:
+ deprecate.deprecate(
+ Deprecated.run__define_metric_copy,
+ "define_metric(summary='copy') is deprecated and will be removed.",
+ self,
+ )
+
+ if (summary and "best" in summary) or goal is not None:
+ deprecate.deprecate(
+ Deprecated.run__define_metric_best_goal,
+ "define_metric(summary='best', goal=...) is deprecated and will be removed. "
+ "Use define_metric(summary='min') or define_metric(summary='max') instead.",
+ self,
+ )
+
+ return self._define_metric(
+ name,
+ step_metric,
+ step_sync,
+ hidden,
+ summary,
+ goal,
+ overwrite,
+ )
+
+ def _define_metric(
+ self,
+ name: str,
+ step_metric: str | wandb_metric.Metric | None = None,
+ step_sync: bool | None = None,
+ hidden: bool | None = None,
+ summary: str | None = None,
+ goal: str | None = None,
+ overwrite: bool | None = None,
+ ) -> wandb_metric.Metric:
+ if not name:
+ raise wandb.Error("define_metric() requires non-empty name argument")
+ if isinstance(step_metric, wandb_metric.Metric):
+ step_metric = step_metric.name
+ for arg_name, arg_val, exp_type in (
+ ("name", name, str),
+ ("step_metric", step_metric, str),
+ ("step_sync", step_sync, bool),
+ ("hidden", hidden, bool),
+ ("summary", summary, str),
+ ("goal", goal, str),
+ ("overwrite", overwrite, bool),
+ ):
+ # NOTE: type checking is broken for isinstance and str
+ if arg_val is not None and not isinstance(arg_val, exp_type):
+ arg_type = type(arg_val).__name__
+ raise wandb.Error(
+ f"Unhandled define_metric() arg: {arg_name} type: {arg_type}"
+ )
+ stripped = name[:-1] if name.endswith("*") else name
+ if "*" in stripped:
+ raise wandb.Error(
+ f"Unhandled define_metric() arg: name (glob suffixes only): {name}"
+ )
+ summary_ops: Sequence[str] | None = None
+ if summary:
+ summary_items = [s.lower() for s in summary.split(",")]
+ summary_ops = []
+ valid = {"min", "max", "mean", "best", "last", "copy", "none", "first"}
+ # TODO: deprecate copy and best
+ for i in summary_items:
+ if i not in valid:
+ raise wandb.Error(f"Unhandled define_metric() arg: summary op: {i}")
+ summary_ops.append(i)
+ with telemetry.context(run=self) as tel:
+ tel.feature.metric_summary = True
+ # TODO: deprecate goal
+ goal_cleaned: str | None = None
+ if goal is not None:
+ goal_cleaned = goal[:3].lower()
+ valid_goal = {"min", "max"}
+ if goal_cleaned not in valid_goal:
+ raise wandb.Error(f"Unhandled define_metric() arg: goal: {goal}")
+ with telemetry.context(run=self) as tel:
+ tel.feature.metric_goal = True
+ if hidden:
+ with telemetry.context(run=self) as tel:
+ tel.feature.metric_hidden = True
+ if step_sync:
+ with telemetry.context(run=self) as tel:
+ tel.feature.metric_step_sync = True
+
+ with telemetry.context(run=self) as tel:
+ tel.feature.metric = True
+
+ m = wandb_metric.Metric(
+ name=name,
+ step_metric=step_metric,
+ step_sync=step_sync,
+ summary=summary_ops,
+ hidden=hidden,
+ goal=goal_cleaned,
+ overwrite=overwrite,
+ )
+ m._set_callback(self._metric_callback)
+ m._commit()
+ return m
+
+ @_log_to_run
+ @_attach
+ def watch(
+ self,
+ models: torch.nn.Module | Sequence[torch.nn.Module],
+ criterion: torch.F | None = None, # type: ignore
+ log: Literal["gradients", "parameters", "all"] | None = "gradients",
+ log_freq: int = 1000,
+ idx: int | None = None,
+ log_graph: bool = False,
+ ) -> None:
+ """Hook into given PyTorch model to monitor gradients and the model's computational graph.
+
+ This function can track parameters, gradients, or both during training.
+
+ Args:
+ models: A single model or a sequence of models to be monitored.
+ criterion: The loss function being optimized (optional).
+ log: Specifies whether to log "gradients", "parameters", or "all".
+ Set to None to disable logging. (default="gradients").
+ log_freq: Frequency (in batches) to log gradients and parameters. (default=1000)
+ idx: Index used when tracking multiple models with `wandb.watch`. (default=None)
+ log_graph: Whether to log the model's computational graph. (default=False)
+
+ Raises:
+ ValueError:
+ If `wandb.init()` has not been called or if any of the models are not instances
+ of `torch.nn.Module`.
+ """
+ wandb.sdk._watch(self, models, criterion, log, log_freq, idx, log_graph)
+
+ @_log_to_run
+ @_attach
+ def unwatch(
+ self, models: torch.nn.Module | Sequence[torch.nn.Module] | None = None
+ ) -> None:
+ """Remove pytorch model topology, gradient and parameter hooks.
+
+ Args:
+ models: Optional list of pytorch models that have had watch called on them.
+ """
+ wandb.sdk._unwatch(self, models=models)
+
+ @_log_to_run
+ @_raise_if_finished
+ @_attach
+ def link_artifact(
+ self,
+ artifact: Artifact,
+ target_path: str,
+ aliases: list[str] | None = None,
+ ) -> Artifact:
+ """Link the given artifact to a portfolio (a promoted collection of artifacts).
+
+ Linked artifacts are visible in the UI for the specified portfolio.
+
+ Args:
+ artifact: the (public or local) artifact which will be linked
+ target_path: `str` - takes the following forms: `{portfolio}`, `{project}/{portfolio}`,
+ or `{entity}/{project}/{portfolio}`
+ aliases: `List[str]` - optional alias(es) that will only be applied on this linked artifact
+ inside the portfolio.
+ The alias "latest" will always be applied to the latest version of an artifact that is linked.
+
+ Returns:
+ The linked artifact.
+
+ """
+ if artifact.is_draft() and not artifact._is_draft_save_started():
+ artifact = self._log_artifact(artifact)
+
+ if self._settings._offline:
+ # TODO: implement offline mode + sync
+ raise NotImplementedError
+
+ # Normalize the target "entity/project/collection" with defaults
+ # inferred from this run's entity and project, if needed.
+ #
+ # HOWEVER, if the target path is a registry collection, avoid setting
+ # the target entity to the run's entity. Instead, delegate to
+ # Artifact.link() to resolve the required org entity.
+ target = ArtifactPath.from_str(target_path)
+ if not target.is_registry_path():
+ target = target.with_defaults(prefix=self.entity, project=self.project)
+
+ return artifact.link(target.to_str(), aliases)
+
+ @_log_to_run
+ @_raise_if_finished
+ @_attach
+ def use_artifact(
+ self,
+ artifact_or_name: str | Artifact,
+ type: str | None = None,
+ aliases: list[str] | None = None,
+ use_as: str | None = None,
+ ) -> Artifact:
+ """Declare an artifact as an input to a run.
+
+ Call `download` or `file` on the returned object to get the contents locally.
+
+ Args:
+ artifact_or_name: The name of the artifact to use. May be prefixed
+ with the name of the project the artifact was logged to
+ ("" or "/"). If no
+ entity is specified in the name, the Run or API setting's entity is used.
+ Valid names can be in the following forms
+ - name:version
+ - name:alias
+ type: The type of artifact to use.
+ aliases: Aliases to apply to this artifact
+ use_as: This argument is deprecated and does nothing.
+
+ Returns:
+ An `Artifact` object.
+
+ Examples:
+ ```python
+ import wandb
+
+ run = wandb.init(project="")
+
+ # Use an artifact by name and alias
+ artifact_a = run.use_artifact(artifact_or_name=":")
+
+ # Use an artifact by name and version
+ artifact_b = run.use_artifact(artifact_or_name=":v")
+
+ # Use an artifact by entity/project/name:alias
+ artifact_c = run.use_artifact(
+ artifact_or_name="//:"
+ )
+
+ # Use an artifact by entity/project/name:version
+ artifact_d = run.use_artifact(
+ artifact_or_name="//:v"
+ )
+
+ # Explicitly finish the run since a context manager is not used.
+ run.finish()
+ ```
+
+ """
+ if self._settings._offline:
+ raise TypeError("Cannot use artifact when in offline mode.")
+
+ api = internal.Api(
+ default_settings={
+ "entity": self._settings.entity,
+ "project": self._settings.project,
+ }
+ )
+ api.set_current_run_id(self._settings.run_id)
+
+ if use_as is not None:
+ deprecate.deprecate(
+ field_name=Deprecated.run__use_artifact_use_as,
+ warning_message=(
+ "`use_as` argument is deprecated and does not affect the behaviour of `run.use_artifact`"
+ ),
+ )
+
+ if isinstance(artifact_or_name, str):
+ name = artifact_or_name
+ public_api = self._public_api()
+ artifact = public_api._artifact(type=type, name=name)
+ if type is not None and type != artifact.type:
+ raise ValueError(
+ f"Supplied type {type} does not match type {artifact.type} of artifact {artifact.name}"
+ )
+ api.use_artifact(
+ artifact.id,
+ entity_name=self._settings.entity,
+ project_name=self._settings.project,
+ artifact_entity_name=artifact.entity,
+ artifact_project_name=artifact.project,
+ )
+ else:
+ artifact = artifact_or_name
+ if aliases is None:
+ aliases = []
+ elif isinstance(aliases, str):
+ aliases = [aliases]
+ if isinstance(artifact_or_name, Artifact) and artifact.is_draft():
+ if use_as is not None:
+ wandb.termwarn(
+ "Indicating use_as is not supported when using a draft artifact"
+ )
+ self._log_artifact(
+ artifact,
+ aliases=aliases,
+ is_user_created=True,
+ use_after_commit=True,
+ )
+ artifact.wait()
+ elif isinstance(artifact, Artifact) and not artifact.is_draft():
+ api.use_artifact(
+ artifact.id,
+ artifact_entity_name=artifact.entity,
+ artifact_project_name=artifact.project,
+ )
+ else:
+ raise ValueError(
+ 'You must pass an artifact name (e.g. "pedestrian-dataset:v1"), '
+ "an instance of `wandb.Artifact`, or `wandb.Api().artifact()` to `use_artifact`"
+ )
+ if self._backend and self._backend.interface:
+ self._backend.interface.publish_use_artifact(artifact)
+ return artifact
+
+ @_log_to_run
+ @_raise_if_finished
+ @_attach
+ def log_artifact(
+ self,
+ artifact_or_path: Artifact | StrPath,
+ name: str | None = None,
+ type: str | None = None,
+ aliases: list[str] | None = None,
+ tags: list[str] | None = None,
+ ) -> Artifact:
+ """Declare an artifact as an output of a run.
+
+ Args:
+ artifact_or_path: (str or Artifact) A path to the contents of this artifact,
+ can be in the following forms:
+ - `/local/directory`
+ - `/local/directory/file.txt`
+ - `s3://bucket/path`
+ You can also pass an Artifact object created by calling
+ `wandb.Artifact`.
+ name: (str, optional) An artifact name. Valid names can be in the following forms:
+ - name:version
+ - name:alias
+ - digest
+ This will default to the basename of the path prepended with the current
+ run id if not specified.
+ type: (str) The type of artifact to log, examples include `dataset`, `model`
+ aliases: (list, optional) Aliases to apply to this artifact,
+ defaults to `["latest"]`
+ tags: (list, optional) Tags to apply to this artifact, if any.
+
+ Returns:
+ An `Artifact` object.
+ """
+ return self._log_artifact(
+ artifact_or_path,
+ name=name,
+ type=type,
+ aliases=aliases,
+ tags=tags,
+ )
+
+ @_log_to_run
+ @_raise_if_finished
+ @_attach
+ def upsert_artifact(
+ self,
+ artifact_or_path: Artifact | str,
+ name: str | None = None,
+ type: str | None = None,
+ aliases: list[str] | None = None,
+ distributed_id: str | None = None,
+ ) -> Artifact:
+ """Declare (or append to) a non-finalized artifact as output of a run.
+
+ Note that you must call run.finish_artifact() to finalize the artifact.
+ This is useful when distributed jobs need to all contribute to the same artifact.
+
+ Args:
+ artifact_or_path: A path to the contents of this artifact,
+ can be in the following forms:
+ - `/local/directory`
+ - `/local/directory/file.txt`
+ - `s3://bucket/path`
+ name: An artifact name. May be prefixed with "entity/project". Defaults
+ to the basename of the path prepended with the current run ID
+ if not specified. Valid names can be in the following forms:
+ - name:version
+ - name:alias
+ - digest
+ type: The type of artifact to log. Common examples include `dataset`, `model`.
+ aliases: Aliases to apply to this artifact, defaults to `["latest"]`.
+ distributed_id: Unique string that all distributed jobs share. If None,
+ defaults to the run's group name.
+
+ Returns:
+ An `Artifact` object.
+ """
+ if self._settings.run_group is None and distributed_id is None:
+ raise TypeError(
+ "Cannot upsert artifact unless run is in a group or distributed_id is provided"
+ )
+ if distributed_id is None:
+ distributed_id = self._settings.run_group or ""
+ return self._log_artifact(
+ artifact_or_path,
+ name=name,
+ type=type,
+ aliases=aliases,
+ distributed_id=distributed_id,
+ finalize=False,
+ )
+
+ @_log_to_run
+ @_raise_if_finished
+ @_attach
+ def finish_artifact(
+ self,
+ artifact_or_path: Artifact | str,
+ name: str | None = None,
+ type: str | None = None,
+ aliases: list[str] | None = None,
+ distributed_id: str | None = None,
+ ) -> Artifact:
+ """Finishes a non-finalized artifact as output of a run.
+
+ Subsequent "upserts" with the same distributed ID will result in a new version.
+
+ Args:
+ artifact_or_path: A path to the contents of this artifact,
+ can be in the following forms:
+ - `/local/directory`
+ - `/local/directory/file.txt`
+ - `s3://bucket/path`
+ You can also pass an Artifact object created by calling
+ `wandb.Artifact`.
+ name: An artifact name. May be prefixed with entity/project.
+ Valid names can be in the following forms:
+ - name:version
+ - name:alias
+ - digest
+ This will default to the basename of the path prepended with the current
+ run id if not specified.
+ type: The type of artifact to log, examples include `dataset`, `model`
+ aliases: Aliases to apply to this artifact,
+ defaults to `["latest"]`
+ distributed_id: Unique string that all distributed jobs share. If None,
+ defaults to the run's group name.
+
+ Returns:
+ An `Artifact` object.
+ """
+ if self._settings.run_group is None and distributed_id is None:
+ raise TypeError(
+ "Cannot finish artifact unless run is in a group or distributed_id is provided"
+ )
+ if distributed_id is None:
+ distributed_id = self._settings.run_group or ""
+
+ return self._log_artifact(
+ artifact_or_path,
+ name,
+ type,
+ aliases,
+ distributed_id=distributed_id,
+ finalize=True,
+ )
+
+ def _log_artifact(
+ self,
+ artifact_or_path: Artifact | StrPath,
+ name: str | None = None,
+ type: str | None = None,
+ aliases: list[str] | None = None,
+ tags: list[str] | None = None,
+ distributed_id: str | None = None,
+ finalize: bool = True,
+ is_user_created: bool = False,
+ use_after_commit: bool = False,
+ ) -> Artifact:
+ if self._settings.anonymous in ["allow", "must"]:
+ wandb.termwarn(
+ "Artifacts logged anonymously cannot be claimed and expire after 7 days."
+ )
+
+ if not finalize and distributed_id is None:
+ raise TypeError("Must provide distributed_id if artifact is not finalize")
+
+ if aliases is not None:
+ aliases = validate_aliases(aliases)
+
+ # Check if artifact tags are supported
+ if tags is not None:
+ tags = validate_tags(tags)
+
+ artifact, aliases = self._prepare_artifact(
+ artifact_or_path, name, type, aliases
+ )
+
+ if len(artifact.metadata) > MAX_ARTIFACT_METADATA_KEYS:
+ raise ValueError(
+ f"Artifact must not have more than {MAX_ARTIFACT_METADATA_KEYS} metadata keys."
+ )
+
+ artifact.distributed_id = distributed_id
+ self._assert_can_log_artifact(artifact)
+ if self._backend and self._backend.interface:
+ if not self._settings._offline:
+ handle = self._backend.interface.deliver_artifact(
+ self,
+ artifact,
+ aliases,
+ tags,
+ self.step,
+ finalize=finalize,
+ is_user_created=is_user_created,
+ use_after_commit=use_after_commit,
+ )
+ artifact._set_save_handle(handle, self._public_api().client)
+ else:
+ self._backend.interface.publish_artifact(
+ self,
+ artifact,
+ aliases,
+ tags,
+ finalize=finalize,
+ is_user_created=is_user_created,
+ use_after_commit=use_after_commit,
+ )
+ elif self._internal_run_interface:
+ self._internal_run_interface.publish_artifact(
+ self,
+ artifact,
+ aliases,
+ tags,
+ finalize=finalize,
+ is_user_created=is_user_created,
+ use_after_commit=use_after_commit,
+ )
+ return artifact
+
+ def _public_api(self, overrides: dict[str, str] | None = None) -> PublicApi:
+ overrides = {"run": self._settings.run_id} # type: ignore
+ if not self._settings._offline:
+ overrides["entity"] = self._settings.entity or ""
+ overrides["project"] = self._settings.project or ""
+ return public.Api(overrides)
+
+ # TODO(jhr): annotate this
+ def _assert_can_log_artifact(self, artifact) -> None: # type: ignore
+ if self._settings._offline:
+ return
+ try:
+ public_api = self._public_api()
+ entity = public_api.settings["entity"]
+ project = public_api.settings["project"]
+ expected_type = Artifact._expected_type(
+ entity, project, artifact.name, public_api.client
+ )
+ except requests.exceptions.RequestException:
+ # Just return early if there is a network error. This is
+ # ok, as this function is intended to help catch an invalid
+ # type early, but not a hard requirement for valid operation.
+ return
+ if expected_type is not None and artifact.type != expected_type:
+ raise ValueError(
+ f"Artifact {artifact.name} already exists with type '{expected_type}'; "
+ f"cannot create another with type '{artifact.type}'"
+ )
+ if entity and artifact._source_entity and entity != artifact._source_entity:
+ raise ValueError(
+ f"Artifact {artifact.name} is owned by entity "
+ f"'{artifact._source_entity}'; it can't be moved to '{entity}'"
+ )
+ if project and artifact._source_project and project != artifact._source_project:
+ raise ValueError(
+ f"Artifact {artifact.name} exists in project "
+ f"'{artifact._source_project}'; it can't be moved to '{project}'"
+ )
+
+ def _prepare_artifact(
+ self,
+ artifact_or_path: Artifact | StrPath,
+ name: str | None = None,
+ type: str | None = None,
+ aliases: list[str] | None = None,
+ ) -> tuple[Artifact, list[str]]:
+ if isinstance(artifact_or_path, (str, os.PathLike)):
+ name = (
+ name
+ or f"run-{self._settings.run_id}-{os.path.basename(artifact_or_path)}"
+ )
+ artifact = Artifact(name, type or "unspecified")
+ if os.path.isfile(artifact_or_path):
+ artifact.add_file(str(artifact_or_path))
+ elif os.path.isdir(artifact_or_path):
+ artifact.add_dir(str(artifact_or_path))
+ elif "://" in str(artifact_or_path):
+ artifact.add_reference(str(artifact_or_path))
+ else:
+ raise ValueError(
+ "path must be a file, directory or external"
+ "reference like s3://bucket/path"
+ )
+ else:
+ artifact = artifact_or_path
+ if not isinstance(artifact, Artifact):
+ raise TypeError(
+ "You must pass an instance of wandb.Artifact or a "
+ "valid file path to log_artifact"
+ )
+
+ artifact.finalize()
+ return artifact, _resolve_aliases(aliases)
+
+ @_log_to_run
+ @_raise_if_finished
+ @_attach
+ def log_model(
+ self,
+ path: StrPath,
+ name: str | None = None,
+ aliases: list[str] | None = None,
+ ) -> None:
+ """Logs a model artifact containing the contents inside the 'path' to a run and marks it as an output to this run.
+
+ The name of model artifact can only contain alphanumeric characters,
+ underscores, and hyphens.
+
+ Args:
+ path: (str) A path to the contents of this model,
+ can be in the following forms:
+ - `/local/directory`
+ - `/local/directory/file.txt`
+ - `s3://bucket/path`
+ name: A name to assign to the model artifact that
+ the file contents will be added to. This will default to the
+ basename of the path prepended with the current run id if
+ not specified.
+ aliases: Aliases to apply to the created model artifact,
+ defaults to `["latest"]`
+
+ Raises:
+ ValueError: If name has invalid special characters.
+
+ Returns:
+ None
+ """
+ self._log_artifact(
+ artifact_or_path=path, name=name, type="model", aliases=aliases
+ )
+
+ @_log_to_run
+ @_raise_if_finished
+ @_attach
+ def use_model(self, name: str) -> FilePathStr:
+ """Download the files logged in a model artifact 'name'.
+
+ Args:
+ name: A model artifact name. 'name' must match the name of an existing logged
+ model artifact. May be prefixed with `entity/project/`. Valid names
+ can be in the following forms
+ - model_artifact_name:version
+ - model_artifact_name:alias
+
+ Returns:
+ path (str): Path to downloaded model artifact file(s).
+
+ Raises:
+ AssertionError: If model artifact 'name' is of a type that does
+ not contain the substring 'model'.
+ """
+ if self._settings._offline:
+ # Downloading artifacts is not supported when offline.
+ raise RuntimeError("`use_model` not supported in offline mode.")
+
+ artifact = self.use_artifact(artifact_or_name=name)
+ if "model" not in str(artifact.type.lower()):
+ raise AssertionError(
+ "You can only use this method for 'model' artifacts."
+ " For an artifact to be a 'model' artifact, its type property"
+ " must contain the substring 'model'."
+ )
+
+ path = artifact.download()
+
+ # If returned directory contains only one file, return path to that file
+ dir_list = os.listdir(path)
+ if len(dir_list) == 1:
+ return FilePathStr(os.path.join(path, dir_list[0]))
+ return path
+
+ @_log_to_run
+ @_raise_if_finished
+ @_attach
+ def link_model(
+ self,
+ path: StrPath,
+ registered_model_name: str,
+ name: str | None = None,
+ aliases: list[str] | None = None,
+ ) -> Artifact | None:
+ """Log a model artifact version and link it to a registered model in the model registry.
+
+ Linked model versions are visible in the UI for the specified registered model.
+
+ This method will:
+ - Check if 'name' model artifact has been logged. If so, use the artifact version that matches the files
+ located at 'path' or log a new version. Otherwise log files under 'path' as a new model artifact, 'name'
+ of type 'model'.
+ - Check if registered model with name 'registered_model_name' exists in the 'model-registry' project.
+ If not, create a new registered model with name 'registered_model_name'.
+ - Link version of model artifact 'name' to registered model, 'registered_model_name'.
+ - Attach aliases from 'aliases' list to the newly linked model artifact version.
+
+ Args:
+ path: (str) A path to the contents of this model, can be in the
+ following forms:
+ - `/local/directory`
+ - `/local/directory/file.txt`
+ - `s3://bucket/path`
+ registered_model_name: The name of the registered model that the
+ model is to be linked to. A registered model is a collection of
+ model versions linked to the model registry, typically
+ representing a team's specific ML Task. The entity that this
+ registered model belongs to will be derived from the run.
+ name: The name of the model artifact that files in 'path' will be
+ logged to. This will default to the basename of the path
+ prepended with the current run id if not specified.
+ aliases: Aliases that will only be applied on this linked artifact
+ inside the registered model. The alias "latest" will always be
+ applied to the latest version of an artifact that is linked.
+
+ Raises:
+ AssertionError: If registered_model_name is a path or
+ if model artifact 'name' is of a type that does not contain
+ the substring 'model'.
+ ValueError: If name has invalid special characters.
+
+ Returns:
+ The linked artifact if linking was successful, otherwise `None`.
+ """
+ name_parts = registered_model_name.split("/")
+ if len(name_parts) != 1:
+ raise AssertionError(
+ "Please provide only the name of the registered model."
+ " Do not append the entity or project name."
+ )
+
+ project = "model-registry"
+ target_path = self.entity + "/" + project + "/" + registered_model_name
+
+ public_api = self._public_api()
+ try:
+ artifact = public_api._artifact(name=f"{name}:latest")
+ if "model" not in str(artifact.type.lower()):
+ raise AssertionError(
+ "You can only use this method for 'model' artifacts."
+ " For an artifact to be a 'model' artifact, its type"
+ " property must contain the substring 'model'."
+ )
+
+ artifact = self._log_artifact(
+ artifact_or_path=path, name=name, type=artifact.type
+ )
+ except (ValueError, CommError):
+ artifact = self._log_artifact(
+ artifact_or_path=path, name=name, type="model"
+ )
+ return self.link_artifact(
+ artifact=artifact, target_path=target_path, aliases=aliases
+ )
+
+ @_log_to_run
+ @_raise_if_finished
+ @_attach
+ def alert(
+ self,
+ title: str,
+ text: str,
+ level: str | AlertLevel | None = None,
+ wait_duration: int | float | timedelta | None = None,
+ ) -> None:
+ """Create an alert with the given title and text.
+
+ Args:
+ title: The title of the alert, must be less than 64 characters long.
+ text: The text body of the alert.
+ level: The alert level to use, either: `INFO`, `WARN`, or `ERROR`.
+ wait_duration: The time to wait (in seconds) before sending another
+ alert with this title.
+ """
+ level = level or AlertLevel.INFO
+ level_str: str = level.value if isinstance(level, AlertLevel) else level
+ if level_str not in {lev.value for lev in AlertLevel}:
+ raise ValueError("level must be one of 'INFO', 'WARN', or 'ERROR'")
+
+ wait_duration = wait_duration or timedelta(minutes=1)
+ if isinstance(wait_duration, int) or isinstance(wait_duration, float):
+ wait_duration = timedelta(seconds=wait_duration)
+ elif not callable(getattr(wait_duration, "total_seconds", None)):
+ raise TypeError(
+ "wait_duration must be an int, float, or datetime.timedelta"
+ )
+ wait_duration = int(wait_duration.total_seconds() * 1000)
+
+ if self._backend and self._backend.interface:
+ self._backend.interface.publish_alert(title, text, level_str, wait_duration)
+
+ def __enter__(self) -> Run:
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException],
+ exc_val: BaseException,
+ exc_tb: TracebackType,
+ ) -> bool:
+ exception_raised = exc_type is not None
+ if exception_raised:
+ traceback.print_exception(exc_type, exc_val, exc_tb)
+ exit_code = 1 if exception_raised else 0
+ self._finish(exit_code=exit_code)
+ return not exception_raised
+
+ @_log_to_run
+ @_raise_if_finished
+ @_attach
+ def mark_preempting(self) -> None:
+ """Mark this run as preempting.
+
+ Also tells the internal process to immediately report this to server.
+ """
+ if self._backend and self._backend.interface:
+ self._backend.interface.publish_preempting()
+
+ @property
+ @_log_to_run
+ @_raise_if_finished
+ @_attach
+ def _system_metrics(self) -> dict[str, list[tuple[datetime, float]]]:
+ """Returns a dictionary of system metrics.
+
+ Returns:
+ A dictionary of system metrics.
+ """
+ from wandb.proto import wandb_internal_pb2
+
+ def pb_to_dict(
+ system_metrics_pb: wandb_internal_pb2.GetSystemMetricsResponse,
+ ) -> dict[str, list[tuple[datetime, float]]]:
+ res = {}
+
+ for metric, records in system_metrics_pb.system_metrics.items():
+ measurements = []
+ for record in records.record:
+ # Convert timestamp to datetime
+ dt = datetime.fromtimestamp(
+ record.timestamp.seconds, tz=timezone.utc
+ )
+ dt = dt.replace(microsecond=record.timestamp.nanos // 1000)
+
+ measurements.append((dt, record.value))
+
+ res[metric] = measurements
+
+ return res
+
+ if not self._backend or not self._backend.interface:
+ return {}
+
+ handle = self._backend.interface.deliver_get_system_metrics()
+
+ try:
+ result = handle.wait_or(timeout=1)
+ except TimeoutError:
+ return {}
+ else:
+ try:
+ response = result.response.get_system_metrics_response
+ return pb_to_dict(response) if response else {}
+ except Exception:
+ logger.exception("Error getting system metrics.")
+ return {}
+
+ # ------------------------------------------------------------------------------
+ # HEADER
+ # ------------------------------------------------------------------------------
+ def _header(self) -> None:
+ self._header_wandb_version_info()
+ self._header_sync_info()
+ self._header_run_info()
+
+ def _header_wandb_version_info(self) -> None:
+ if self._settings.quiet or self._settings.silent:
+ return
+
+ # TODO: add this to a higher verbosity level
+ self._printer.display(f"Tracking run with wandb version {wandb.__version__}")
+
+ def _header_sync_info(self) -> None:
+ sync_location_msg = f"Run data is saved locally in {self._printer.files(self._settings.sync_dir)}"
+
+ if self._settings._offline:
+ offline_warning = (
+ f"W&B syncing is set to {self._printer.code('`offline`')} "
+ f"in this directory. Run {self._printer.code('`wandb online`')} "
+ f"or set {self._printer.code('WANDB_MODE=online')} "
+ "to enable cloud syncing."
+ )
+ self._printer.display([offline_warning, sync_location_msg])
+ else:
+ messages = [sync_location_msg]
+
+ if not self._printer.supports_html:
+ disable_sync_msg = (
+ f"Run {self._printer.code('`wandb offline`')} to turn off syncing."
+ )
+ messages.append(disable_sync_msg)
+
+ if not self._settings.quiet and not self._settings.silent:
+ self._printer.display(messages)
+
+ def _header_run_info(self) -> None:
+ settings, printer = self._settings, self._printer
+
+ if settings._offline or settings.silent:
+ return
+
+ run_url = settings.run_url
+ project_url = settings.project_url
+ sweep_url = settings.sweep_url
+
+ run_state_str = (
+ "Resuming run"
+ if settings.resumed or settings.resume_from
+ else "Syncing run"
+ )
+ run_name = settings.run_name
+ if not run_name:
+ return
+
+ if printer.supports_html:
+ import wandb.jupyter
+
+ if not wandb.jupyter.display_if_magic_is_used(self):
+ run_line = f"{printer.link(run_url, run_name)}"
+ project_line, sweep_line = "", ""
+
+ if not settings.quiet:
+ doc_html = printer.link(url_registry.url("developer-guide"), "docs")
+
+ project_html = printer.link(project_url, "Weights & Biases")
+ project_line = f"to {project_html} ({doc_html})"
+
+ if sweep_url:
+ sweep_line = f"Sweep page: {printer.link(sweep_url, sweep_url)}"
+
+ printer.display(
+ [f"{run_state_str} {run_line} {project_line}", sweep_line],
+ )
+
+ elif run_name:
+ printer.display(f"{run_state_str} {printer.name(run_name)}")
+
+ if not settings.quiet:
+ # TODO: add verbosity levels and add this to higher levels
+ printer.display(
+ f"{printer.emoji('star')} View project at {printer.link(project_url)}"
+ )
+ if sweep_url:
+ printer.display(
+ f"{printer.emoji('broom')} View sweep at {printer.link(sweep_url)}"
+ )
+ printer.display(
+ f"{printer.emoji('rocket')} View run at {printer.link(run_url)}",
+ )
+
+ if run_name and settings.anonymous in ["allow", "must"]:
+ printer.display(
+ (
+ "Do NOT share these links with anyone."
+ " They can be used to claim your runs."
+ ),
+ level="warn",
+ )
+
+ # ------------------------------------------------------------------------------
+ # FOOTER
+ # ------------------------------------------------------------------------------
+ # Note: All the footer methods are static methods since we want to share the printing logic
+ # with the service execution path that doesn't have access to the run instance
+ @staticmethod
+ def _footer(
+ sampled_history: SampledHistoryResponse | None = None,
+ final_summary: GetSummaryResponse | None = None,
+ poll_exit_response: PollExitResponse | None = None,
+ internal_messages_response: InternalMessagesResponse | None = None,
+ *,
+ settings: Settings,
+ printer: printer.Printer,
+ ) -> None:
+ Run._footer_history_summary_info(
+ history=sampled_history,
+ summary=final_summary,
+ settings=settings,
+ printer=printer,
+ )
+
+ Run._footer_sync_info(
+ poll_exit_response=poll_exit_response,
+ settings=settings,
+ printer=printer,
+ )
+ Run._footer_log_dir_info(settings=settings, printer=printer)
+ Run._footer_internal_messages(
+ internal_messages_response=internal_messages_response,
+ settings=settings,
+ printer=printer,
+ )
+
+ @staticmethod
+ def _footer_sync_info(
+ poll_exit_response: PollExitResponse | None = None,
+ *,
+ settings: Settings,
+ printer: printer.Printer,
+ ) -> None:
+ if settings.silent:
+ return
+
+ if settings._offline:
+ if not settings.quiet:
+ printer.display(
+ [
+ "You can sync this run to the cloud by running:",
+ printer.code(f"wandb sync {settings.sync_dir}"),
+ ],
+ )
+ return
+
+ info = []
+ if settings.run_name and settings.run_url:
+ info.append(
+ f"{printer.emoji('rocket')} View run {printer.name(settings.run_name)} at: {printer.link(settings.run_url)}"
+ )
+ if settings.project_url:
+ info.append(
+ f"{printer.emoji('star')} View project at: {printer.link(settings.project_url)}"
+ )
+ if poll_exit_response and poll_exit_response.file_counts:
+ logger.info("logging synced files")
+ file_counts = poll_exit_response.file_counts
+ info.append(
+ f"Synced {file_counts.wandb_count} W&B file(s), {file_counts.media_count} media file(s), "
+ f"{file_counts.artifact_count} artifact file(s) and {file_counts.other_count} other file(s)",
+ )
+ printer.display(info)
+
+ @staticmethod
+ def _footer_log_dir_info(
+ *,
+ settings: Settings,
+ printer: printer.Printer,
+ ) -> None:
+ if settings.quiet or settings.silent:
+ return
+
+ log_dir = settings.log_user or settings.log_internal
+ if log_dir:
+ log_dir = os.path.dirname(log_dir.replace(os.getcwd(), "."))
+ printer.display(
+ f"Find logs at: {printer.files(log_dir)}",
+ )
+
+ @staticmethod
+ def _footer_history_summary_info(
+ history: SampledHistoryResponse | None = None,
+ summary: GetSummaryResponse | None = None,
+ *,
+ settings: Settings,
+ printer: printer.Printer,
+ ) -> None:
+ if settings.quiet or settings.silent:
+ return
+
+ panel: list[str] = []
+
+ if history and (
+ history_grid := Run._footer_history(history, printer, settings)
+ ):
+ panel.append(history_grid)
+
+ if summary and (
+ summary_grid := Run._footer_summary(summary, printer, settings)
+ ):
+ panel.append(summary_grid)
+
+ if panel:
+ printer.display(printer.panel(panel))
+
+ @staticmethod
+ def _footer_history(
+ history: SampledHistoryResponse,
+ printer: printer.Printer,
+ settings: Settings,
+ ) -> str | None:
+ """Returns the run history formatted for printing to the console."""
+ sorted_history_items = sorted(
+ (item for item in history.item if not item.key.startswith("_")),
+ key=lambda item: item.key,
+ )
+
+ history_rows: list[list[str]] = []
+ for item in sorted_history_items:
+ if len(history_rows) >= settings.max_end_of_run_history_metrics:
+ break
+
+ values = wandb.util.downsample(
+ item.values_float or item.values_int,
+ 40,
+ )
+
+ if sparkline := printer.sparklines(values):
+ history_rows.append([item.key, sparkline])
+
+ if not history_rows:
+ return None
+
+ if len(history_rows) < len(sorted_history_items):
+ remaining = len(sorted_history_items) - len(history_rows)
+ history_rows.append([f"+{remaining:,d}", "..."])
+
+ return printer.grid(history_rows, "Run history:")
+
+ @staticmethod
+ def _footer_summary(
+ summary: GetSummaryResponse,
+ printer: printer.Printer,
+ settings: Settings,
+ ) -> str | None:
+ """Returns the run summary formatted for printing to the console."""
+ sorted_summary_items = sorted(
+ (
+ item
+ for item in summary.item
+ if not item.key.startswith("_") and not item.nested_key
+ ),
+ key=lambda item: item.key,
+ )
+
+ summary_rows: list[list[str]] = []
+ skipped = 0
+ for item in sorted_summary_items:
+ if len(summary_rows) >= settings.max_end_of_run_summary_metrics:
+ break
+
+ try:
+ value = json.loads(item.value_json)
+ except json.JSONDecodeError:
+ logger.exception(f"Error decoding summary[{item.key!r}]")
+ skipped += 1
+ continue
+
+ if isinstance(value, str):
+ value = value[:20] + "..." * (len(value) >= 20)
+ summary_rows.append([item.key, value])
+ elif isinstance(value, numbers.Number):
+ value = round(value, 5) if isinstance(value, float) else value
+ summary_rows.append([item.key, str(value)])
+ else:
+ skipped += 1
+
+ if not summary_rows:
+ return None
+
+ if len(summary_rows) < len(sorted_summary_items) - skipped:
+ remaining = len(sorted_summary_items) - len(summary_rows) - skipped
+ summary_rows.append([f"+{remaining:,d}", "..."])
+
+ return printer.grid(summary_rows, "Run summary:")
+
+ @staticmethod
+ def _footer_internal_messages(
+ internal_messages_response: InternalMessagesResponse | None = None,
+ *,
+ settings: Settings,
+ printer: printer.Printer,
+ ) -> None:
+ if settings.quiet or settings.silent:
+ return
+
+ if not internal_messages_response:
+ return
+
+ for message in internal_messages_response.messages.warning:
+ printer.display(message, level="warn")
+
+
+# We define this outside of the run context to support restoring before init
+def restore(
+ name: str,
+ run_path: str | None = None,
+ replace: bool = False,
+ root: str | None = None,
+) -> None | TextIO:
+ """Download the specified file from cloud storage.
+
+ File is placed into the current directory or run directory.
+ By default, will only download the file if it doesn't already exist.
+
+ Args:
+ name: The name of the file.
+ run_path: Optional path to a run to pull files from, i.e. `username/project_name/run_id`
+ if wandb.init has not been called, this is required.
+ replace: Whether to download the file even if it already exists locally
+ root: The directory to download the file to. Defaults to the current
+ directory or the run directory if wandb.init was called.
+
+ Returns:
+ None if it can't find the file, otherwise a file object open for reading.
+
+ Raises:
+ CommError: If W&B can't connect to the W&B backend.
+ ValueError: If the file is not found or can't find run_path.
+ """
+ is_disabled = wandb.run is not None and wandb.run.disabled
+ run = None if is_disabled else wandb.run
+ if run_path is None:
+ if run is not None:
+ run_path = run.path
+ else:
+ raise ValueError(
+ "run_path required when calling wandb.restore before wandb.init"
+ )
+ if root is None:
+ if run is not None:
+ root = run.dir
+ api = public.Api()
+ api_run = api.run(run_path)
+ if root is None:
+ root = os.getcwd()
+ path = os.path.join(root, name)
+ if os.path.exists(path) and replace is False:
+ return open(path)
+ if is_disabled:
+ return None
+ files = api_run.files([name])
+ if len(files) == 0:
+ return None
+ # if the file does not exist, the file has an md5 of 0
+ if files[0].md5 == "0":
+ raise ValueError(f"File {name} not found in {run_path or root}.")
+ return files[0].download(root=root, replace=True)
+
+
+# propagate our doc string to the runs restore method
+try:
+ Run.restore.__doc__ = restore.__doc__
+except AttributeError:
+ pass
+
+
+def finish(
+ exit_code: int | None = None,
+ quiet: bool | None = None,
+) -> None:
+ """Finish a run and upload any remaining data.
+
+ Marks the completion of a W&B run and ensures all data is synced to the server.
+ The run's final state is determined by its exit conditions and sync status.
+
+ Run States:
+ - Running: Active run that is logging data and/or sending heartbeats.
+ - Crashed: Run that stopped sending heartbeats unexpectedly.
+ - Finished: Run completed successfully (`exit_code=0`) with all data synced.
+ - Failed: Run completed with errors (`exit_code!=0`).
+
+ Args:
+ exit_code: Integer indicating the run's exit status. Use 0 for success,
+ any other value marks the run as failed.
+ quiet: Deprecated. Configure logging verbosity using `wandb.Settings(quiet=...)`.
+ """
+ if wandb.run:
+ wandb.run.finish(exit_code=exit_code, quiet=quiet)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_settings.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_settings.py
new file mode 100644
index 0000000000000000000000000000000000000000..a357cdd565b3f8223c3315c54827ed4b30a3305f
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_settings.py
@@ -0,0 +1,2198 @@
+from __future__ import annotations
+
+import configparser
+import json
+import logging
+import os
+import pathlib
+import platform
+import re
+import shutil
+import socket
+import sys
+from datetime import datetime
+
+# Optional and Union are used for type hinting instead of | because
+# the latter is not supported in pydantic<2.6 and Python<3.10.
+# Dict, List, and Tuple are used for backwards compatibility
+# with pydantic v1 and Python<3.9.
+from typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Tuple, Union
+from urllib.parse import quote, unquote, urlencode
+
+from google.protobuf.wrappers_pb2 import BoolValue, DoubleValue, Int32Value, StringValue
+from pydantic import BaseModel, ConfigDict, Field
+from typing_extensions import Self
+
+import wandb
+from wandb import env, util
+from wandb._pydantic import (
+ IS_PYDANTIC_V2,
+ AliasChoices,
+ computed_field,
+ field_validator,
+ model_validator,
+)
+from wandb.errors import UsageError
+from wandb.proto import wandb_settings_pb2
+
+from .lib import apikey, credentials, ipython
+from .lib.gitlib import GitRepo
+from .lib.run_moment import RunMoment
+
+validate_url: Callable[[str], None]
+
+if IS_PYDANTIC_V2:
+ from pydantic_core import SchemaValidator, core_schema
+
+ def validate_url(url: str) -> None:
+ """Validate a URL string."""
+ url_validator = SchemaValidator(
+ core_schema.url_schema(
+ allowed_schemes=["http", "https"],
+ strict=True,
+ )
+ )
+ url_validator.validate_python(url)
+else:
+ from pydantic import root_validator
+
+ def validate_url(url: str) -> None:
+ """Validate the base url of the wandb server.
+
+ param value: URL to validate
+
+ Based on the Django URLValidator, but with a few additional checks.
+
+ Copyright (c) Django Software Foundation and individual contributors.
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modification,
+ are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ 3. Neither the name of Django nor the names of its contributors may be used
+ to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ """
+ from urllib.parse import urlparse, urlsplit
+
+ if url is None:
+ return
+
+ ul = "\u00a1-\uffff" # Unicode letters range (must not be a raw string).
+
+ # IP patterns
+ ipv4_re = (
+ r"(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)"
+ r"(?:\.(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)){3}"
+ )
+ ipv6_re = r"\[[0-9a-f:.]+\]" # (simple regex, validated later)
+
+ # Host patterns
+ hostname_re = (
+ r"[a-z" + ul + r"0-9](?:[a-z" + ul + r"0-9-]{0,61}[a-z" + ul + r"0-9])?"
+ )
+ # Max length for domain name labels is 63 characters per RFC 1034 sec. 3.1
+ domain_re = r"(?:\.(?!-)[a-z" + ul + r"0-9-]{1,63}(? 253:
+ raise ValueError("hostname is invalid")
+
+
+def _path_convert(*args: str) -> str:
+ """Join path and apply os.path.expanduser to it."""
+ return os.path.expanduser(os.path.join(*args))
+
+
+CLIENT_ONLY_SETTINGS = (
+ "files_dir",
+ "max_end_of_run_history_metrics",
+ "max_end_of_run_summary_metrics",
+ "reinit",
+ "x_files_dir",
+ "x_sync_dir_suffix",
+)
+"""Python-only keys that are not fields on the settings proto."""
+
+
+class Settings(BaseModel, validate_assignment=True):
+ """Settings for the W&B SDK.
+
+ This class manages configuration settings for the W&B SDK,
+ ensuring type safety and validation of all settings. Settings are accessible
+ as attributes and can be initialized programmatically, through environment
+ variables (`WANDB_ prefix`), and with configuration files.
+
+ The settings are organized into three categories:
+ 1. Public settings: Core configuration options that users can safely modify to customize
+ W&B's behavior for their specific needs.
+ 2. Internal settings: Settings prefixed with 'x_' that handle low-level SDK behavior.
+ These settings are primarily for internal use and debugging. While they can be modified,
+ they are not considered part of the public API and may change without notice in future
+ versions.
+ 3. Computed settings: Read-only settings that are automatically derived from other settings or
+ the environment.
+ """
+
+ # Pydantic Model configuration.
+ model_config = ConfigDict(
+ extra="forbid", # throw an error if extra fields are provided
+ validate_default=True, # validate default values
+ use_attribute_docstrings=True, # for field descriptions
+ revalidate_instances="always",
+ )
+
+ # Public settings.
+
+ allow_offline_artifacts: bool = True
+ """Flag to allow table artifacts to be synced in offline mode.
+
+ To revert to the old behavior, set this to False.
+ """
+
+ allow_val_change: bool = False
+ """Flag to allow modification of `Config` values after they've been set."""
+
+ anonymous: Optional[Literal["allow", "must", "never"]] = None
+ """Controls anonymous data logging.
+
+ Possible values are:
+ - "never": requires you to link your W&B account before
+ tracking the run, so you don't accidentally create an anonymous
+ run.
+ - "allow": lets a logged-in user track runs with their account, but
+ lets someone who is running the script without a W&B account see
+ the charts in the UI.
+ - "must": sends the run to an anonymous account instead of to a
+ signed-up user account.
+ """
+
+ api_key: Optional[str] = None
+ """The W&B API key."""
+
+ azure_account_url_to_access_key: Optional[Dict[str, str]] = None
+ """Mapping of Azure account URLs to their corresponding access keys for Azure integration."""
+
+ base_url: str = "https://api.wandb.ai"
+ """The URL of the W&B backend for data synchronization."""
+
+ code_dir: Optional[str] = None
+ """Directory containing the code to be tracked by W&B."""
+
+ config_paths: Optional[Sequence[str]] = None
+ """Paths to files to load configuration from into the `Config` object."""
+
+ console: Literal["auto", "off", "wrap", "redirect", "wrap_raw", "wrap_emu"] = Field(
+ default="auto",
+ validate_default=True,
+ )
+ """The type of console capture to be applied.
+
+ Possible values are:
+ - "auto" - Automatically selects the console capture method based on the
+ system environment and settings.
+ - "off" - Disables console capture.
+ - "redirect" - Redirects low-level file descriptors for capturing output.
+ - "wrap" - Overrides the write methods of sys.stdout/sys.stderr. Will be
+ mapped to either "wrap_raw" or "wrap_emu" based on the state of the system.
+ - "wrap_raw" - Same as "wrap" but captures raw output directly instead of
+ through an emulator. Derived from the `wrap` setting and should not be set manually.
+ - "wrap_emu" - Same as "wrap" but captures output through an emulator.
+ Derived from the `wrap` setting and should not be set manually.
+ """
+
+ console_multipart: bool = False
+ """Whether to produce multipart console log files."""
+
+ credentials_file: str = Field(
+ default_factory=lambda: str(credentials.DEFAULT_WANDB_CREDENTIALS_FILE)
+ )
+ """Path to file for writing temporary access tokens."""
+
+ disable_code: bool = False
+ """Whether to disable capturing the code."""
+
+ disable_git: bool = False
+ """Whether to disable capturing the git state."""
+
+ disable_job_creation: bool = True
+ """Whether to disable the creation of a job artifact for W&B Launch."""
+
+ docker: Optional[str] = None
+ """The Docker image used to execute the script."""
+
+ email: Optional[str] = None
+ """The email address of the user."""
+
+ entity: Optional[str] = None
+ """The W&B entity, such as a user or a team."""
+
+ organization: Optional[str] = None
+ """The W&B organization."""
+
+ force: bool = False
+ """Whether to pass the `force` flag to `wandb.login()`."""
+
+ fork_from: Optional[RunMoment] = None
+ """Specifies a point in a previous execution of a run to fork from.
+
+ The point is defined by the run ID, a metric, and its value.
+ Currently, only the metric '_step' is supported.
+ """
+
+ git_commit: Optional[str] = None
+ """The git commit hash to associate with the run."""
+
+ git_remote: str = "origin"
+ """The git remote to associate with the run."""
+
+ git_remote_url: Optional[str] = None
+ """The URL of the git remote repository."""
+
+ git_root: Optional[str] = None
+ """Root directory of the git repository."""
+
+ heartbeat_seconds: int = 30
+ """Interval in seconds between heartbeat signals sent to the W&B servers.
+
+
+ """
+
+ host: Optional[str] = None
+ """Hostname of the machine running the script."""
+
+ http_proxy: Optional[str] = None
+ """Custom proxy servers for http requests to W&B."""
+
+ https_proxy: Optional[str] = None
+ """Custom proxy servers for https requests to W&B."""
+
+ identity_token_file: Optional[str] = None
+ """Path to file containing an identity token (JWT) for authentication."""
+
+ ignore_globs: Sequence[str] = ()
+ """Unix glob patterns relative to `files_dir` specifying files to exclude from upload."""
+
+ init_timeout: float = 90.0
+ """Time in seconds to wait for the `wandb.init` call to complete before timing out."""
+
+ insecure_disable_ssl: bool = False
+ """Whether to insecurely disable SSL verification."""
+
+ job_name: Optional[str] = None
+ """Name of the Launch job running the script."""
+
+ job_source: Optional[Literal["repo", "artifact", "image"]] = None
+ """Source type for Launch."""
+
+ label_disable: bool = False
+ """Whether to disable automatic labeling features."""
+
+ launch: bool = False
+ """Flag to indicate if the run is being launched through W&B Launch.
+
+
+ """
+
+ launch_config_path: Optional[str] = None
+ """Path to the launch configuration file."""
+
+ login_timeout: Optional[float] = None
+ """Time in seconds to wait for login operations before timing out."""
+
+ mode: Literal["online", "offline", "shared", "disabled", "dryrun", "run"] = Field(
+ default="online",
+ validate_default=True,
+ )
+ """The operating mode for W&B logging and synchronization."""
+
+ notebook_name: Optional[str] = None
+ """Name of the notebook if running in a Jupyter-like environment."""
+
+ program: Optional[str] = None
+ """Path to the script that created the run, if available."""
+
+ program_abspath: Optional[str] = None
+ """The absolute path from the root repository directory to the script that
+ created the run.
+
+ Root repository directory is defined as the directory containing the
+ .git directory, if it exists. Otherwise, it's the current working directory.
+ """
+
+ program_relpath: Optional[str] = None
+ """The relative path to the script that created the run."""
+
+ project: Optional[str] = None
+ """The W&B project ID."""
+
+ quiet: bool = False
+ """Flag to suppress non-essential output."""
+
+ reinit: Union[
+ Literal[
+ "default",
+ "return_previous",
+ "finish_previous",
+ "create_new",
+ ],
+ bool,
+ ] = "default"
+ """What to do when `wandb.init()` is called while a run is active.
+
+ Options:
+ - "default": Use "finish_previous" in notebooks and "return_previous"
+ otherwise.
+ - "return_previous": Return the most recently created run
+ that is not yet finished. This does not update `wandb.run`; see
+ the "create_new" option.
+ - "finish_previous": Finish all active runs, then return a new run.
+ - "create_new": Create a new run without modifying other active runs.
+ Does not update `wandb.run` and top-level functions like `wandb.log`.
+ Because of this, some older integrations that rely on the global run
+ will not work.
+
+ Can also be a boolean, but this is deprecated. False is the same as
+ "return_previous", and True is the same as "finish_previous".
+ """
+
+ relogin: bool = False
+ """Flag to force a new login attempt."""
+
+ resume: Optional[Literal["allow", "must", "never", "auto"]] = None
+ """Specifies the resume behavior for the run.
+
+ Options:
+ - "must": Resumes from an existing run with the same ID. If no such run exists,
+ it will result in failure.
+ - "allow": Attempts to resume from an existing run with the same ID. If none is
+ found, a new run will be created.
+ - "never": Always starts a new run. If a run with the same ID already exists,
+ it will result in failure.
+ - "auto": Automatically resumes from the most recent failed run on the same
+ machine.
+ """
+
+ resume_from: Optional[RunMoment] = None
+ """Specifies a point in a previous execution of a run to resume from.
+
+ The point is defined by the run ID, a metric, and its value.
+ Currently, only the metric '_step' is supported.
+ """
+
+ resumed: bool = False
+ """Indication from the server about the state of the run.
+
+ This is different from resume, a user provided flag.
+
+ """
+
+ root_dir: str = Field(default_factory=lambda: os.path.abspath(os.getcwd()))
+ """The root directory to use as the base for all run-related paths.
+
+ In particular, this is used to derive the wandb directory and the run directory.
+ """
+
+ run_group: Optional[str] = None
+ """Group identifier for related runs.
+
+ Used for grouping runs in the UI.
+ """
+
+ run_id: Optional[str] = None
+ """The ID of the run."""
+
+ run_job_type: Optional[str] = None
+ """Type of job being run (e.g., training, evaluation)."""
+
+ run_name: Optional[str] = None
+ """Human-readable name for the run."""
+
+ run_notes: Optional[str] = None
+ """Additional notes or description for the run."""
+
+ run_tags: Optional[Tuple[str, ...]] = None
+ """Tags to associate with the run for organization and filtering."""
+
+ sagemaker_disable: bool = False
+ """Flag to disable SageMaker-specific functionality."""
+
+ save_code: Optional[bool] = None
+ """Whether to save the code associated with the run."""
+
+ settings_system: Optional[str] = None
+ """Path to the system-wide settings file."""
+
+ max_end_of_run_history_metrics: int = 10
+ """Maximum number of history sparklines to display at the end of a run."""
+
+ max_end_of_run_summary_metrics: int = 10
+ """Maximum number of summary metrics to display at the end of a run."""
+
+ show_colors: Optional[bool] = None
+ """Whether to use colored output in the console.
+
+
+ """
+
+ show_emoji: Optional[bool] = None
+ """Whether to show emoji in the console output.
+
+
+ """
+
+ show_errors: bool = True
+ """Whether to display error messages."""
+
+ show_info: bool = True
+ """Whether to display informational messages."""
+
+ show_warnings: bool = True
+ """Whether to display warning messages."""
+
+ silent: bool = False
+ """Flag to suppress all output."""
+
+ start_method: Optional[str] = None
+ """Method to use for starting subprocesses.
+
+ This is deprecated and will be removed in a future release.
+
+ """
+
+ strict: Optional[bool] = None
+ """Whether to enable strict mode for validation and error checking."""
+
+ summary_timeout: int = 60
+ """Time in seconds to wait for summary operations before timing out."""
+
+ summary_warnings: int = 5
+ """Maximum number of summary warnings to display.
+
+
+ """
+
+ sweep_id: Optional[str] = None
+ """Identifier of the sweep this run belongs to."""
+
+ sweep_param_path: Optional[str] = None
+ """Path to the sweep parameters configuration."""
+
+ symlink: bool = Field(
+ default_factory=lambda: False if platform.system() == "Windows" else True
+ )
+ """Whether to use symlinks (True by default except on Windows)."""
+
+ sync_tensorboard: Optional[bool] = None
+ """Whether to synchronize TensorBoard logs with W&B."""
+
+ table_raise_on_max_row_limit_exceeded: bool = False
+ """Whether to raise an exception when table row limits are exceeded."""
+
+ username: Optional[str] = None
+ """Username."""
+
+ # Internal settings.
+ #
+ # These are typically not meant to be set by the user and should not be considered
+ # a part of the public API as they may change or be removed in future versions.
+
+ x_cli_only_mode: bool = False
+ """Flag to indicate that the SDK is running in CLI-only mode.
+
+
+ """
+
+ x_disable_meta: bool = False
+ """Flag to disable the collection of system metadata."""
+
+ x_disable_stats: bool = False
+ """Flag to disable the collection of system metrics."""
+
+ x_disable_viewer: bool = False
+ """Flag to disable the early viewer query.
+
+
+ """
+
+ x_disable_machine_info: bool = False
+ """Flag to disable automatic machine info collection.
+
+
+ """
+
+ x_executable: Optional[str] = None
+ """Path to the Python executable.
+
+
+ """
+
+ x_extra_http_headers: Optional[Dict[str, str]] = None
+ """Additional headers to add to all outgoing HTTP requests."""
+
+ x_file_stream_max_bytes: Optional[int] = None
+ """An approximate maximum request size for the filestream API.
+
+ Its purpose is to prevent HTTP requests from failing due to
+ containing too much data. This number is approximate:
+ requests will be slightly larger.
+
+ """
+
+ x_file_stream_max_line_bytes: Optional[int] = None
+ """Maximum line length for filestream JSONL files.
+
+
+ """
+
+ x_file_stream_transmit_interval: Optional[float] = None
+ """Interval in seconds between filestream transmissions.
+
+
+ """
+
+ # Filestream retry client configuration.
+
+ x_file_stream_retry_max: Optional[int] = None
+ """Max number of retries for filestream operations.
+
+
+ """
+
+ x_file_stream_retry_wait_min_seconds: Optional[float] = None
+ """Minimum wait time between retries for filestream operations.
+
+
+ """
+
+ x_file_stream_retry_wait_max_seconds: Optional[float] = None
+ """Maximum wait time between retries for filestream operations.
+
+
+ """
+
+ x_file_stream_timeout_seconds: Optional[float] = None
+ """Timeout in seconds for individual filestream HTTP requests.
+
+
+ """
+
+ # file transfer retry client configuration
+
+ x_file_transfer_retry_max: Optional[int] = None
+ """Max number of retries for file transfer operations.
+
+
+ """
+
+ x_file_transfer_retry_wait_min_seconds: Optional[float] = None
+ """Minimum wait time between retries for file transfer operations.
+
+
+ """
+
+ x_file_transfer_retry_wait_max_seconds: Optional[float] = None
+ """Maximum wait time between retries for file transfer operations.
+
+
+ """
+
+ x_file_transfer_timeout_seconds: Optional[float] = None
+ """Timeout in seconds for individual file transfer HTTP requests.
+
+
+ """
+
+ x_files_dir: Optional[str] = None
+ """Override setting for the computed files_dir.
+
+ DEPRECATED, DO NOT USE. This private setting is not respected by wandb-core
+ but will continue to work for some legacy Python code.
+
+
+ """
+
+ x_flow_control_custom: Optional[bool] = None
+ """Flag indicating custom flow control for filestream.
+
+ TODO: Not implemented in wandb-core.
+
+ """
+
+ x_flow_control_disabled: Optional[bool] = None
+ """Flag indicating flow control is disabled for filestream.
+
+ TODO: Not implemented in wandb-core.
+
+ """
+
+ # graphql retry client configuration
+
+ x_graphql_retry_max: Optional[int] = None
+ """Max number of retries for GraphQL operations.
+
+
+ """
+
+ x_graphql_retry_wait_min_seconds: Optional[float] = None
+ """Minimum wait time between retries for GraphQL operations.
+
+
+ """
+
+ x_graphql_retry_wait_max_seconds: Optional[float] = None
+ """Maximum wait time between retries for GraphQL operations.
+
+
+ """
+
+ x_graphql_timeout_seconds: Optional[float] = None
+ """Timeout in seconds for individual GraphQL requests.
+
+
+ """
+
+ x_internal_check_process: float = 8.0
+ """Interval for internal process health checks in seconds.
+
+
+ """
+
+ x_jupyter_name: Optional[str] = None
+ """Name of the Jupyter notebook.
+
+
+ """
+
+ x_jupyter_path: Optional[str] = None
+ """Path to the Jupyter notebook.
+
+
+ """
+
+ x_jupyter_root: Optional[str] = None
+ """Root directory of the Jupyter notebook.
+
+
+ """
+
+ x_label: Optional[str] = None
+ """Label to assign to system metrics and console logs collected for the run.
+
+ This is used to group data by on the frontend and can be used to distinguish data
+ from different processes in a distributed training job.
+ """
+
+ x_live_policy_rate_limit: Optional[int] = None
+ """Rate limit for live policy updates in seconds.
+
+
+ """
+
+ x_live_policy_wait_time: Optional[int] = None
+ """Wait time between live policy updates in seconds.
+
+
+ """
+
+ x_log_level: int = logging.INFO
+ """Logging level for internal operations.
+
+
+ """
+
+ x_network_buffer: Optional[int] = None
+ """Size of the network buffer used in flow control.
+
+ TODO: Not implemented in wandb-core.
+
+ """
+
+ x_primary: bool = Field(
+ default=True, validation_alias=AliasChoices("x_primary", "x_primary_node")
+ )
+ """Determines whether to save internal wandb files and metadata.
+
+ In a distributed setting, this is useful for avoiding file overwrites
+ from secondary processes when only system metrics and logs are needed,
+ as the primary process handles the main logging.
+ """
+
+ x_proxies: Optional[Dict[str, str]] = None
+ """Custom proxy servers for requests to W&B.
+
+ This is deprecated and will be removed in a future release.
+ Please use `http_proxy` and `https_proxy` instead.
+
+ """
+
+ x_runqueue_item_id: Optional[str] = None
+ """ID of the Launch run queue item being processed.
+
+
+ """
+
+ x_save_requirements: bool = True
+ """Flag to save the requirements file."""
+
+ x_server_side_derived_summary: bool = False
+ """Flag to delegate automatic computation of summary from history to the server.
+
+ This does not disable user-provided summary updates.
+ """
+
+ x_server_side_expand_glob_metrics: bool = True
+ """Flag to delegate glob matching of metrics in define_metric to the server.
+
+ If the server does not support this, the client will perform the glob matching.
+
+ """
+
+ x_service_transport: Optional[str] = None
+ """Transport method for communication with the wandb service.
+
+
+ """
+
+ x_service_wait: float = 30.0
+ """Time in seconds to wait for the wandb-core internal service to start."""
+
+ x_skip_transaction_log: bool = False
+ """Whether to skip saving the run events to the transaction log.
+
+ This is only relevant for online runs. Can be used to reduce the amount of
+ data written to disk.
+
+ Should be used with caution, as it removes the gurantees about
+ recoverability.
+ """
+
+ x_start_time: Optional[float] = None
+ """The start time of the run in seconds since the Unix epoch.
+
+
+ """
+
+ x_stats_pid: int = os.getpid()
+ """PID of the process that started the wandb-core process to collect system stats for.
+
+
+ """
+
+ x_stats_sampling_interval: float = Field(default=15.0)
+ """Sampling interval for the system monitor in seconds."""
+
+ x_stats_neuron_monitor_config_path: Optional[str] = None
+ """Path to the default config file for the neuron-monitor tool.
+
+ This is used to monitor AWS Trainium devices.
+
+ """
+
+ x_stats_dcgm_exporter: Optional[str] = None
+ """Endpoint to extract Nvidia DCGM metrics from.
+
+ Options:
+ - Extract DCGM-related metrics from a query to the Prometheus `/api/v1/query` endpoint.
+ It is a common practice to aggregate metrics reported by the instances of the DCGM Exporter
+ running on different nodes in a cluster using Prometheus.
+ - TODO: Parse metrics directly from the `/metrics` endpoint of the DCGM Exporter.
+
+ Examples:
+ - `http://localhost:9400/api/v1/query?query=DCGM_FI_DEV_GPU_TEMP{node="l1337", cluster="globular"}`.
+ - TODO: `http://192.168.0.1:9400/metrics`.
+
+ """
+
+ x_stats_open_metrics_endpoints: Optional[Dict[str, str]] = None
+ """OpenMetrics `/metrics` endpoints to monitor for system metrics."""
+
+ x_stats_open_metrics_filters: Union[
+ Dict[str, Dict[str, str]], Sequence[str], None
+ ] = None
+ """Filter to apply to metrics collected from OpenMetrics `/metrics` endpoints.
+
+ Supports two formats:
+ - {"metric regex pattern, including endpoint name as prefix": {"label": "label value regex pattern"}}
+ - ("metric regex pattern 1", "metric regex pattern 2", ...)
+ """
+
+ x_stats_open_metrics_http_headers: Optional[Dict[str, str]] = None
+ """HTTP headers to add to OpenMetrics requests."""
+
+ x_stats_disk_paths: Optional[Sequence[str]] = ("/",)
+ """System paths to monitor for disk usage."""
+
+ x_stats_cpu_count: Optional[int] = None
+ """System CPU count.
+
+ If set, overrides the auto-detected value in the run metadata.
+ """
+
+ x_stats_cpu_logical_count: Optional[int] = None
+ """Logical CPU count.
+
+ If set, overrides the auto-detected value in the run metadata.
+ """
+
+ x_stats_gpu_count: Optional[int] = None
+ """GPU device count.
+
+ If set, overrides the auto-detected value in the run metadata.
+ """
+
+ x_stats_gpu_type: Optional[str] = None
+ """GPU device type.
+
+ If set, overrides the auto-detected value in the run metadata.
+ """
+
+ x_stats_gpu_device_ids: Optional[Sequence[int]] = None
+ """GPU device indices to monitor.
+
+ If not set, the system monitor captures metrics for all GPUs.
+ Assumes 0-based indexing matching CUDA/ROCm device enumeration.
+ """
+
+ x_stats_buffer_size: int = 0
+ """Number of system metric samples to buffer in memory in the wandb-core process.
+
+ Can be accessed via run._system_metrics.
+
+ """
+
+ x_stats_coreweave_metadata_base_url: str = "http://169.254.169.254"
+ """The scheme and hostname for contacting the CoreWeave metadata server.
+
+ Only accessible from within a CoreWeave cluster.
+
+ """
+
+ x_stats_coreweave_metadata_endpoint: str = "/api/v2/cloud-init/meta-data"
+ """The relative path on the CoreWeave metadata server to which to make requests.
+
+ This must not include the schema and hostname prefix.
+ Only accessible from within a CoreWeave cluster.
+
+ """
+
+ x_stats_track_process_tree: bool = False
+ """Monitor the entire process tree for resource usage, starting from `x_stats_pid`.
+
+ When `True`, the system monitor aggregates the RSS, CPU%, and thread count
+ from the process with PID `x_stats_pid` and all of its descendants.
+ This can have a performance overhead and is disabled by default.
+ """
+
+ x_sync: bool = False
+ """Flag to indicate whether we are syncing a run from the transaction log.
+
+
+ """
+
+ x_sync_dir_suffix: str = ""
+ """Suffix to add to the run's directory name (sync_dir).
+
+ This is set in wandb.init() to avoid naming conflicts.
+ If set, it is joined to the default name with a dash.
+ """
+
+ x_update_finish_state: bool = True
+ """Flag to indicate whether this process can update the run's final state on the server.
+
+ Set to False in distributed training when only the main process should determine the final state.
+ """
+
+ # Model validator to catch legacy settings.
+ @model_validator(mode="before")
+ @classmethod
+ def catch_private_settings(cls, values):
+ """Check if a private field is provided and assign to the corresponding public one.
+
+ This is a compatibility layer to handle previous versions of the settings.
+
+
+ """
+ new_values = {}
+ for key in values:
+ # Internal settings are prefixed with "x_" instead of "_"
+ # as Pydantic does not allow "_" in field names.
+ if key.startswith("_"):
+ new_values["x" + key] = values[key]
+ else:
+ new_values[key] = values[key]
+ return new_values
+
+ if IS_PYDANTIC_V2:
+
+ @model_validator(mode="after")
+ def validate_mutual_exclusion_of_branching_args(self) -> Self:
+ """Check if `fork_from`, `resume`, and `resume_from` are mutually exclusive.
+
+
+ """
+ if (
+ sum(
+ o is not None
+ for o in [self.fork_from, self.resume, self.resume_from]
+ )
+ > 1
+ ):
+ raise ValueError(
+ "`fork_from`, `resume`, or `resume_from` are mutually exclusive. "
+ "Please specify only one of them."
+ )
+ return self
+
+ @model_validator(mode="after")
+ def validate_skip_transaction_log(self):
+ """Validate x_skip_transaction_log.
+
+
+ """
+ if self._offline and self.x_skip_transaction_log:
+ raise ValueError("Cannot skip transaction log in offline mode")
+ return self
+ else:
+
+ @root_validator(pre=False) # type: ignore [call-overload]
+ @classmethod
+ def validate_mutual_exclusion_of_branching_args(cls, values):
+ if (
+ sum(
+ values.get(o) is not None
+ for o in ["fork_from", "resume", "resume_from"]
+ )
+ > 1
+ ):
+ raise ValueError(
+ "`fork_from`, `resume`, or `resume_from` are mutually exclusive. "
+ "Please specify only one of them."
+ )
+ return values
+
+ @root_validator(pre=False) # type: ignore [call-overload]
+ @classmethod
+ def validate_skip_transaction_log(cls, values):
+ if values.get("_offline") and values.get("x_skip_transaction_log"):
+ raise ValueError("Cannot skip transaction log in offline mode")
+ return values
+
+ # Field validators.
+ @field_validator("api_key", mode="after")
+ @classmethod
+ def validate_api_key(cls, value):
+ """Validate the API key.
+
+
+ """
+ if value is not None and (len(value) > len(value.strip())):
+ raise UsageError("API key cannot start or end with whitespace")
+ return value
+
+ @field_validator("base_url", mode="after")
+ @classmethod
+ def validate_base_url(cls, value):
+ """Validate the base URL.
+
+
+ """
+ validate_url(value)
+ # wandb.ai-specific checks
+ if re.match(r".*wandb\.ai[^\.]*$", value) and "api." not in value:
+ # user might guess app.wandb.ai or wandb.ai is the default cloud server
+ raise ValueError(
+ f"{value} is not a valid server address, did you mean https://api.wandb.ai?"
+ )
+ elif re.match(r".*wandb\.ai[^\.]*$", value) and not value.startswith("https"):
+ raise ValueError("http is not secure, please use https://api.wandb.ai")
+ return value.rstrip("/")
+
+ @field_validator("code_dir", mode="before")
+ @classmethod
+ def validate_code_dir(cls, value):
+ """Validate the code directory.
+
+
+ """
+ # TODO: add native support for pathlib.Path
+ if isinstance(value, pathlib.Path):
+ return str(value)
+ return value
+
+ @field_validator("console", mode="after")
+ @classmethod
+ def validate_console(cls, value, values):
+ """Validate the console capture method.
+
+
+ """
+ if value != "auto":
+ return value
+
+ return "wrap"
+
+ @field_validator("x_executable", mode="before")
+ @classmethod
+ def validate_x_executable(cls, value):
+ """Validate the Python executable path.
+
+
+ """
+ # TODO: add native support for pathlib.Path
+ if isinstance(value, pathlib.Path):
+ return str(value)
+ return value
+
+ @field_validator("x_extra_http_headers", mode="before")
+ @classmethod
+ def validate_x_extra_http_headers(cls, value):
+ if isinstance(value, str):
+ return json.loads(value)
+ return value
+
+ @field_validator("x_file_stream_max_line_bytes", mode="after")
+ @classmethod
+ def validate_file_stream_max_line_bytes(cls, value):
+ """Validate the maximum line length for filestream JSONL files.
+
+
+ """
+ if value is not None and value < 1:
+ raise ValueError("File stream max line bytes must be greater than 0")
+ return value
+
+ @field_validator("x_files_dir", mode="before")
+ @classmethod
+ def validate_x_files_dir(cls, value):
+ """Validate the files directory.
+
+
+ """
+ # TODO: add native support for pathlib.Path
+ if isinstance(value, pathlib.Path):
+ return str(value)
+ return value
+
+ @field_validator("fork_from", mode="before")
+ @classmethod
+ def validate_fork_from(cls, value, values) -> Optional[RunMoment]:
+ """Validate the fork_from field.
+
+
+ """
+ run_moment = cls._runmoment_preprocessor(value)
+
+ if hasattr(values, "data"):
+ # pydantic v2
+ values = values.data
+ else:
+ # pydantic v1
+ values = values
+
+ if (
+ run_moment
+ and values.get("run_id") is not None
+ and values.get("run_id") == run_moment.run
+ ):
+ raise ValueError(
+ "Provided `run_id` is the same as the run to `fork_from`. "
+ "Please provide a different `run_id` or remove the `run_id` argument. "
+ "If you want to rewind the current run, please use `resume_from` instead."
+ )
+ return run_moment
+
+ @field_validator("http_proxy", mode="after")
+ @classmethod
+ def validate_http_proxy(cls, value):
+ """Validate the HTTP proxy.
+
+
+ """
+ if value is None:
+ return None
+ validate_url(value)
+ return value.rstrip("/")
+
+ @field_validator("https_proxy", mode="after")
+ @classmethod
+ def validate_https_proxy(cls, value):
+ """Validate the HTTPS proxy.
+
+
+ """
+ if value is None:
+ return None
+ validate_url(value)
+ return value.rstrip("/")
+
+ @field_validator("ignore_globs", mode="after")
+ @classmethod
+ def validate_ignore_globs(cls, value):
+ """Validate the ignore globs.
+
+
+ """
+ return tuple(value) if not isinstance(value, tuple) else value
+
+ @field_validator("program", mode="before")
+ @classmethod
+ def validate_program(cls, value):
+ """Validate the program path.
+
+
+ """
+ # TODO: add native support for pathlib.Path
+ if isinstance(value, pathlib.Path):
+ return str(value)
+ return value
+
+ @field_validator("program_abspath", mode="before")
+ @classmethod
+ def validate_program_abspath(cls, value):
+ """Validate the absolute program path.
+
+
+ """
+ # TODO: add native support for pathlib.Path
+ if isinstance(value, pathlib.Path):
+ return str(value)
+ return value
+
+ @field_validator("program_relpath", mode="before")
+ @classmethod
+ def validate_program_relpath(cls, value):
+ """Validate the relative program path.
+
+
+ """
+ # TODO: add native support for pathlib.Path
+ if isinstance(value, pathlib.Path):
+ return str(value)
+ return value
+
+ @field_validator("project", mode="after")
+ @classmethod
+ def validate_project(cls, value, values):
+ """Validate the project name.
+
+
+ """
+ if value is None:
+ return None
+ invalid_chars_list = list("/\\#?%:")
+ if len(value) > 128:
+ raise UsageError(f"Invalid project name {value!r}: exceeded 128 characters")
+ invalid_chars = {char for char in invalid_chars_list if char in value}
+ if invalid_chars:
+ raise UsageError(
+ f"Invalid project name {value!r}: "
+ f"cannot contain characters {','.join(invalid_chars_list)!r}, "
+ f"found {','.join(invalid_chars)!r}"
+ )
+ return value
+
+ @field_validator("resume", mode="before")
+ @classmethod
+ def validate_resume(cls, value):
+ """Validate the resume behavior.
+
+
+ """
+ if value is False:
+ return None
+ if value is True:
+ return "auto"
+ return value
+
+ @field_validator("resume_from", mode="before")
+ @classmethod
+ def validate_resume_from(cls, value, values) -> Optional[RunMoment]:
+ """Validate the resume_from field.
+
+
+ """
+ run_moment = cls._runmoment_preprocessor(value)
+
+ if hasattr(values, "data"):
+ # pydantic v2
+ values = values.data
+ else:
+ # pydantic v1
+ values = values
+
+ if (
+ run_moment
+ and values.get("run_id") is not None
+ and values.get("run_id") != run_moment.run
+ ):
+ raise ValueError(
+ "Both `run_id` and `resume_from` have been specified with different ids."
+ )
+ return run_moment
+
+ @field_validator("root_dir", mode="before")
+ @classmethod
+ def validate_root_dir(cls, value):
+ """Validate the root directory.
+
+
+ """
+ # TODO: add native support for pathlib.Path
+ if isinstance(value, pathlib.Path):
+ return str(value)
+ return value
+
+ @field_validator("run_id", mode="after")
+ @classmethod
+ def validate_run_id(cls, value, values):
+ """Validate the run ID.
+
+
+ """
+ if value is None:
+ return None
+
+ if len(value) == 0:
+ raise UsageError("Run ID cannot be empty")
+ if len(value) > len(value.strip()):
+ raise UsageError("Run ID cannot start or end with whitespace")
+ if not bool(value.strip()):
+ raise UsageError("Run ID cannot contain only whitespace")
+
+ # check if the run id contains any reserved characters
+ reserved_chars = ":;,#?/'"
+ if any(char in reserved_chars for char in value):
+ raise UsageError(f"Run ID cannot contain the characters: {reserved_chars}")
+ return value
+
+ @field_validator("settings_system", mode="after")
+ @classmethod
+ def validate_settings_system(cls, value):
+ """Validate the system settings file path.
+
+
+ """
+ if value is None:
+ return None
+ elif isinstance(value, pathlib.Path):
+ return str(_path_convert(value))
+ else:
+ return _path_convert(value)
+
+ @field_validator("x_service_wait", mode="after")
+ @classmethod
+ def validate_service_wait(cls, value):
+ """Validate the service wait time.
+
+
+ """
+ if value < 0:
+ raise UsageError("Service wait time cannot be negative")
+ return value
+
+ @field_validator("start_method", mode="after")
+ @classmethod
+ def validate_start_method(cls, value):
+ """Validate the start method for subprocesses.
+
+
+ """
+ if value is None:
+ return value
+ wandb.termwarn(
+ "`start_method` is deprecated and will be removed in a future version "
+ "of wandb. This setting is currently non-functional and safely ignored.",
+ repeat=False,
+ )
+ return value
+
+ @field_validator("x_stats_coreweave_metadata_base_url", mode="after")
+ @classmethod
+ def validate_x_stats_coreweave_metadata_base_url(cls, value):
+ validate_url(value)
+ return value.rstrip("/")
+
+ @field_validator("x_stats_gpu_device_ids", mode="before")
+ @classmethod
+ def validate_x_stats_gpu_device_ids(cls, value):
+ """Validate the GPU device IDs.
+
+
+ """
+ if isinstance(value, str):
+ return json.loads(value)
+ return value
+
+ @field_validator("x_stats_neuron_monitor_config_path", mode="before")
+ @classmethod
+ def validate_x_stats_neuron_monitor_config_path(cls, value):
+ """Validate the path to the neuron-monitor config file.
+
+
+ """
+ # TODO: add native support for pathlib.Path
+ if isinstance(value, pathlib.Path):
+ return str(value)
+ return value
+
+ @field_validator("x_stats_open_metrics_endpoints", mode="before")
+ @classmethod
+ def validate_stats_open_metrics_endpoints(cls, value):
+ """Validate the OpenMetrics endpoints.
+
+
+ """
+ if isinstance(value, str):
+ return json.loads(value)
+ return value
+
+ @field_validator("x_stats_open_metrics_filters", mode="before")
+ @classmethod
+ def validate_stats_open_metrics_filters(cls, value):
+ """Validate the OpenMetrics filters.
+
+
+ """
+ if isinstance(value, str):
+ return json.loads(value)
+ return value
+
+ @field_validator("x_stats_open_metrics_http_headers", mode="before")
+ @classmethod
+ def validate_stats_open_metrics_http_headers(cls, value):
+ """Validate the OpenMetrics HTTP headers.
+
+
+ """
+ if isinstance(value, str):
+ return json.loads(value)
+ return value
+
+ @field_validator("x_stats_sampling_interval", mode="after")
+ @classmethod
+ def validate_stats_sampling_interval(cls, value):
+ """Validate the stats sampling interval.
+
+
+ """
+ if value < 0.1:
+ raise UsageError("Stats sampling interval cannot be less than 0.1 seconds")
+ return value
+
+ @field_validator("sweep_id", mode="after")
+ @classmethod
+ def validate_sweep_id(cls, value):
+ """Validate the sweep ID.
+
+
+ """
+ if value is None:
+ return None
+ if len(value) == 0:
+ raise UsageError("Sweep ID cannot be empty")
+ if len(value) > len(value.strip()):
+ raise UsageError("Sweep ID cannot start or end with whitespace")
+ if not bool(value.strip()):
+ raise UsageError("Sweep ID cannot contain only whitespace")
+ return value
+
+ @field_validator("run_tags", mode="before")
+ @classmethod
+ def validate_run_tags(cls, value):
+ """Validate run tags.
+
+ Validates that each tag:
+ - Is between 1 and 64 characters in length (inclusive)
+ - Converts single string values to tuple format
+ - Preserves None values
+
+
+
+ Args:
+ value: A string, list, tuple, or None representing tags
+
+ Returns:
+ tuple: A tuple of validated tags, or None
+
+ Raises:
+ ValueError: If any tag is empty or exceeds 64 characters
+ """
+ if value is None:
+ return None
+
+ # Convert to tuple if needed
+ if isinstance(value, str):
+ tags = (value,)
+ else:
+ tags = tuple(value)
+
+ # Validate each tag and accumulate errors
+ errors = []
+ for i, tag in enumerate(tags):
+ tag_str = str(tag)
+ if len(tag_str) == 0:
+ errors.append(
+ f"Tag at index {i} is empty. Tags must be between 1 and 64 characters"
+ )
+ elif len(tag_str) > 64:
+ # Truncate long tags for display
+ display_tag = (
+ f"{tag_str[:20]}...{tag_str[-20:]}"
+ if len(tag_str) > 43
+ else tag_str
+ )
+ errors.append(
+ f"Tag '{display_tag}' is {len(tag_str)} characters. Tags must be between 1 and 64 characters"
+ )
+
+ # Raise combined error if any validation issues were found
+ if errors:
+ raise ValueError("; ".join(errors))
+
+ return tags
+
+ @field_validator("sweep_param_path", mode="before")
+ @classmethod
+ def validate_sweep_param_path(cls, value):
+ """Validate the sweep parameter path.
+
+
+ """
+ # TODO: add native support for pathlib.Path
+ if isinstance(value, pathlib.Path):
+ return str(value)
+ return value
+
+ # Computed fields.
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def _args(self) -> List[str]:
+ if not self._jupyter:
+ return sys.argv[1:]
+ return []
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def _aws_lambda(self) -> bool:
+ """Check if we are running in a lambda environment."""
+ from sentry_sdk.integrations.aws_lambda import ( # type: ignore[import-not-found]
+ get_lambda_bootstrap,
+ )
+
+ lambda_bootstrap = get_lambda_bootstrap()
+ if not lambda_bootstrap or not hasattr(
+ lambda_bootstrap, "handle_event_request"
+ ):
+ return False
+ return True
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def _code_path_local(self) -> Optional[str]:
+ """The relative path from the current working directory to the code path.
+
+ For example, if the code path is /home/user/project/example.py, and the
+ current working directory is /home/user/project, then the code path local
+ is example.py.
+
+ If couldn't find the relative path, this will be an empty string.
+ """
+ return self._get_program_relpath(self.program) if self.program else None
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def _colab(self) -> bool:
+ return "google.colab" in sys.modules
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def _ipython(self) -> bool:
+ return ipython.in_ipython()
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def _jupyter(self) -> bool:
+ return ipython.in_jupyter()
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def _kaggle(self) -> bool:
+ return util._is_likely_kaggle()
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def _noop(self) -> bool:
+ return self.mode == "disabled"
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def _notebook(self) -> bool:
+ return self._ipython or self._jupyter or self._colab or self._kaggle
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def _offline(self) -> bool:
+ return self.mode in ("offline", "dryrun")
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def _os(self) -> str:
+ """The operating system of the machine running the script."""
+ return platform.platform(aliased=True)
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def _platform(self) -> str:
+ return f"{platform.system()}-{platform.machine()}".lower()
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def _python(self) -> str:
+ return f"{platform.python_implementation()} {platform.python_version()}"
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def _shared(self) -> bool:
+ """Whether we are in shared mode.
+
+ In "shared" mode, multiple processes can write to the same run,
+ for example from different machines.
+ """
+ return self.mode == "shared"
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def _start_datetime(self) -> str:
+ if self.x_start_time is None:
+ return ""
+ datetime_now = datetime.fromtimestamp(self.x_start_time)
+ return datetime_now.strftime("%Y%m%d_%H%M%S")
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def _tmp_code_dir(self) -> str:
+ return _path_convert(self.sync_dir, "tmp", "code")
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def _windows(self) -> bool:
+ return platform.system() == "Windows"
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def colab_url(self) -> Optional[str]:
+ """The URL to the Colab notebook, if running in Colab."""
+ if not self._colab:
+ return None
+ if self.x_jupyter_path and self.x_jupyter_path.startswith("fileId="):
+ unescaped = unquote(self.x_jupyter_path)
+ return "https://colab.research.google.com/notebook#" + unescaped
+ return None
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def deployment(self) -> Literal["local", "cloud"]:
+ return "local" if self.is_local else "cloud"
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def files_dir(self) -> str:
+ """Absolute path to the local directory where the run's files are stored."""
+ # Must match the logic in settings.go in the service process.
+ return self.x_files_dir or _path_convert(self.sync_dir, "files")
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def is_local(self) -> bool:
+ return str(self.base_url) != "https://api.wandb.ai"
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def log_dir(self) -> str:
+ """The directory for storing log files."""
+ return _path_convert(self.sync_dir, "logs")
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def log_internal(self) -> str:
+ """The path to the file to use for internal logs."""
+ return _path_convert(self.log_dir, "debug-internal.log")
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def log_symlink_internal(self) -> str:
+ """The path to the symlink to the internal log file of the most recent run."""
+ return _path_convert(self.wandb_dir, "debug-internal.log")
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def log_symlink_user(self) -> str:
+ """The path to the symlink to the user-process log file of the most recent run."""
+ return _path_convert(self.wandb_dir, "debug.log")
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def log_user(self) -> str:
+ """The path to the file to use for user-process logs."""
+ return _path_convert(self.log_dir, "debug.log")
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def project_url(self) -> str:
+ """The W&B URL where the project can be viewed."""
+ project_url = self._project_url_base()
+ if not project_url:
+ return ""
+
+ query = self._get_url_query_string()
+
+ return f"{project_url}{query}"
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def resume_fname(self) -> str:
+ """The path to the resume file."""
+ return _path_convert(self.wandb_dir, "wandb-resume.json")
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def run_mode(self) -> Literal["run", "offline-run"]:
+ """The mode of the run. Can be either "run" or "offline-run"."""
+ return "run" if not self._offline else "offline-run"
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def run_url(self) -> str:
+ """The W&B URL where the run can be viewed."""
+ project_url = self._project_url_base()
+ if not all([project_url, self.run_id]):
+ return ""
+
+ query = self._get_url_query_string()
+ # Exclude specific safe characters from URL encoding to prevent 404 errors
+ safe_chars = "=+&$@"
+ return f"{project_url}/runs/{quote(self.run_id or '', safe=safe_chars)}{query}"
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def settings_workspace(self) -> str:
+ """The path to the workspace settings file."""
+ return _path_convert(self.wandb_dir, "settings")
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def sweep_url(self) -> str:
+ """The W&B URL where the sweep can be viewed."""
+ project_url = self._project_url_base()
+ if not all([project_url, self.sweep_id]):
+ return ""
+
+ query = self._get_url_query_string()
+ return f"{project_url}/sweeps/{quote(self.sweep_id or '')}{query}"
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def sync_dir(self) -> str:
+ """The directory for storing the run's files."""
+ name = f"{self.run_mode}-{self.timespec}-{self.run_id}"
+
+ if self.x_sync_dir_suffix:
+ name += f"-{self.x_sync_dir_suffix}"
+
+ return _path_convert(self.wandb_dir, name)
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def sync_file(self) -> str:
+ """Path to the append-only binary transaction log file."""
+ return _path_convert(self.sync_dir, f"run-{self.run_id}.wandb")
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def sync_symlink_latest(self) -> str:
+ """Path to the symlink to the most recent run's transaction log file."""
+ return _path_convert(self.wandb_dir, "latest-run")
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def timespec(self) -> str:
+ """The time specification for the run."""
+ return self._start_datetime
+
+ @computed_field # type: ignore[prop-decorator]
+ @property
+ def wandb_dir(self) -> str:
+ """Full path to the wandb directory."""
+ stage_dir = (
+ ".wandb" + os.sep
+ if os.path.exists(os.path.join(self.root_dir, ".wandb"))
+ else "wandb" + os.sep
+ )
+ path = os.path.join(self.root_dir, stage_dir)
+ return os.path.expanduser(path)
+
+ # Methods to collect and update settings from different sources.
+ #
+ # The Settings class does not track the source of the settings,
+ # so it is up to the developer to ensure that the settings are applied
+ # in the correct order. Most of the updates are done in
+ # wandb/sdk/wandb_setup.py::_WandbSetup._settings_setup.
+
+ def update_from_system_config_file(self):
+ """Update settings from the system config file.
+
+
+ """
+ if not self.settings_system or not os.path.exists(self.settings_system):
+ return
+ for key, value in self._load_config_file(self.settings_system).items():
+ if value is not None:
+ setattr(self, key, value)
+
+ def update_from_workspace_config_file(self):
+ """Update settings from the workspace config file.
+
+
+ """
+ if not self.settings_workspace or not os.path.exists(self.settings_workspace):
+ return
+ for key, value in self._load_config_file(self.settings_workspace).items():
+ if value is not None:
+ setattr(self, key, value)
+
+ def update_from_env_vars(self, environ: Dict[str, Any]):
+ """Update settings from environment variables.
+
+
+ """
+ env_prefix: str = "WANDB_"
+ private_env_prefix: str = env_prefix + "_"
+ special_env_var_names = {
+ "WANDB_SERVICE_TRANSPORT": "x_service_transport",
+ "WANDB_DIR": "root_dir",
+ "WANDB_NAME": "run_name",
+ "WANDB_NOTES": "run_notes",
+ "WANDB_TAGS": "run_tags",
+ "WANDB_JOB_TYPE": "run_job_type",
+ "WANDB_HTTP_TIMEOUT": "x_graphql_timeout_seconds",
+ "WANDB_FILE_PUSHER_TIMEOUT": "x_file_transfer_timeout_seconds",
+ "WANDB_USER_EMAIL": "email",
+ }
+ env = dict()
+ for setting, value in environ.items():
+ if not setting.startswith(env_prefix):
+ continue
+
+ if setting in special_env_var_names:
+ key = special_env_var_names[setting]
+ elif setting.startswith(private_env_prefix):
+ key = "x_" + setting[len(private_env_prefix) :].lower()
+ else:
+ # otherwise, strip the prefix and convert to lowercase
+ key = setting[len(env_prefix) :].lower()
+
+ if key in self.__dict__:
+ if key in ("ignore_globs", "run_tags"):
+ value = value.split(",")
+ env[key] = value
+
+ for key, value in env.items():
+ if value is not None:
+ setattr(self, key, value)
+
+ def update_from_system_environment(self):
+ """Update settings from the system environment.
+
+
+ """
+ # For code saving, only allow env var override if value from server is true, or
+ # if no preference was specified.
+ if (self.save_code is True or self.save_code is None) and (
+ os.getenv(env.SAVE_CODE) is not None
+ or os.getenv(env.DISABLE_CODE) is not None
+ ):
+ self.save_code = env.should_save_code()
+
+ if os.getenv(env.DISABLE_GIT) is not None:
+ self.disable_git = env.disable_git()
+
+ # Attempt to get notebook information if not already set by the user
+ if self._jupyter and (self.notebook_name is None or self.notebook_name == ""):
+ meta = wandb.jupyter.notebook_metadata(self.silent) # type: ignore
+ self.x_jupyter_path = meta.get("path")
+ self.x_jupyter_name = meta.get("name")
+ self.x_jupyter_root = meta.get("root")
+ elif (
+ self._jupyter
+ and self.notebook_name is not None
+ and os.path.exists(self.notebook_name)
+ ):
+ self.x_jupyter_path = self.notebook_name
+ self.x_jupyter_name = self.notebook_name
+ self.x_jupyter_root = os.getcwd()
+ elif self._jupyter:
+ wandb.termwarn(
+ "WANDB_NOTEBOOK_NAME should be a path to a notebook file, "
+ f"couldn't find {self.notebook_name}.",
+ )
+
+ # host is populated by update_from_env_vars if the corresponding env
+ # vars exist -- but if they don't, we'll fill them in here.
+ if self.host is None:
+ self.host = socket.gethostname() # type: ignore
+
+ _executable = (
+ self.x_executable
+ or os.environ.get(env._EXECUTABLE)
+ or sys.executable
+ or shutil.which("python3")
+ or "python3"
+ )
+ self.x_executable = _executable
+
+ if self.docker is None:
+ self.docker = env.get_docker(util.image_id_from_k8s())
+
+ # proceed if not in CLI mode
+ if self.x_cli_only_mode:
+ return
+
+ program = self.program or self._get_program()
+
+ if program is not None:
+ try:
+ root = (
+ GitRepo().root or os.getcwd()
+ if not self.disable_git
+ else os.getcwd()
+ )
+ except Exception:
+ # if the git command fails, fall back to the current working directory
+ root = os.getcwd()
+
+ self.program_relpath = self.program_relpath or self._get_program_relpath(
+ program, root
+ )
+ program_abspath = os.path.abspath(
+ os.path.join(root, os.path.relpath(os.getcwd(), root), program)
+ )
+ if os.path.exists(program_abspath):
+ self.program_abspath = program_abspath
+ else:
+ program = ""
+
+ self.program = program
+
+ def update_from_dict(self, settings: Dict[str, Any]) -> None:
+ """Update settings from a dictionary.
+
+
+ """
+ for key, value in dict(settings).items():
+ if value is not None:
+ setattr(self, key, value)
+
+ def update_from_settings(self, settings: Settings) -> None:
+ """Update settings from another instance of `Settings`.
+
+
+ """
+ d = {field: getattr(settings, field) for field in settings.model_fields_set}
+ if d:
+ self.update_from_dict(d)
+
+ # Helper methods.
+
+ def to_proto(self) -> wandb_settings_pb2.Settings:
+ """Generate a protobuf representation of the settings.
+
+
+ """
+ settings_proto = wandb_settings_pb2.Settings()
+ for k, v in self.model_dump(exclude_none=True).items():
+ if k in CLIENT_ONLY_SETTINGS:
+ continue
+
+ # Special case for x_stats_open_metrics_filters.
+ if k == "x_stats_open_metrics_filters":
+ if isinstance(v, (list, set, tuple)):
+ setting = getattr(settings_proto, k)
+ setting.sequence.value.extend(v)
+ elif isinstance(v, dict):
+ setting = getattr(settings_proto, k)
+ for key, value in v.items():
+ for kk, vv in value.items():
+ setting.mapping.value[key].value[kk] = vv
+ else:
+ raise TypeError(f"Unsupported type {type(v)} for setting {k}")
+ continue
+
+ # Special case for RunMoment fields.
+ if k in ("fork_from", "resume_from"):
+ run_moment = (
+ v
+ if isinstance(v, RunMoment)
+ else RunMoment(
+ run=v.get("run"),
+ value=v.get("value"),
+ metric=v.get("metric"),
+ )
+ )
+ getattr(settings_proto, k).CopyFrom(
+ wandb_settings_pb2.RunMoment(
+ run=run_moment.run,
+ value=run_moment.value,
+ metric=run_moment.metric,
+ )
+ )
+ continue
+
+ if isinstance(v, bool):
+ getattr(settings_proto, k).CopyFrom(BoolValue(value=v))
+ elif isinstance(v, int):
+ getattr(settings_proto, k).CopyFrom(Int32Value(value=v))
+ elif isinstance(v, float):
+ getattr(settings_proto, k).CopyFrom(DoubleValue(value=v))
+ elif isinstance(v, str):
+ getattr(settings_proto, k).CopyFrom(StringValue(value=v))
+ elif isinstance(v, (list, set, tuple)):
+ # we only support sequences of strings for now
+ sequence = getattr(settings_proto, k)
+ sequence.value.extend(v)
+ elif isinstance(v, dict):
+ mapping = getattr(settings_proto, k)
+ for key, value in v.items():
+ # we only support dicts with string values for now
+ mapping.value[key] = value
+ elif v is None:
+ # None means that the setting value was not set.
+ pass
+ else:
+ raise TypeError(f"Unsupported type {type(v)} for setting {k}")
+
+ return settings_proto
+
+ def _get_program(self) -> Optional[str]:
+ """Get the program that started the current process."""
+ if self._jupyter:
+ # If in a notebook, try to get the program from the notebook metadata.
+ if self.notebook_name:
+ return self.notebook_name
+
+ if not self.x_jupyter_path:
+ return self.program
+
+ if self.x_jupyter_path.startswith("fileId="):
+ return self.x_jupyter_name
+
+ return self.x_jupyter_path
+
+ # If not in a notebook, try to get the program from the environment
+ # or the __main__ module for scripts run as `python -m ...`.
+ program = os.getenv(env.PROGRAM)
+ if program is not None:
+ return program
+
+ try:
+ import __main__
+ except ImportError:
+ return None
+
+ try:
+ if __main__.__spec__ is None:
+ python_args = __main__.__file__
+ else:
+ python_args = f"-m {__main__.__spec__.name}"
+ except AttributeError:
+ return None
+
+ return python_args
+
+ @staticmethod
+ def _get_program_relpath(program: str, root: Optional[str] = None) -> Optional[str]:
+ """Get the relative path to the program from the root directory."""
+ if not program:
+ return None
+
+ root = root or os.getcwd()
+ if not root:
+ return None
+
+ # For windows if the root and program are on different drives,
+ # os.path.relpath will raise a ValueError.
+ if not util.are_paths_on_same_drive(root, program):
+ return None
+
+ full_path_to_program = os.path.join(
+ root, os.path.relpath(os.getcwd(), root), program
+ )
+ if os.path.exists(full_path_to_program):
+ relative_path = os.path.relpath(full_path_to_program, start=root)
+ if "../" in relative_path:
+ return None
+ return relative_path
+
+ return None
+
+ @staticmethod
+ def _load_config_file(file_name: str, section: str = "default") -> dict:
+ """Load a config file and return the settings for a given section."""
+ parser = configparser.ConfigParser()
+ parser.add_section(section)
+ parser.read(file_name)
+ config: Dict[str, Any] = dict()
+ for k in parser[section]:
+ config[k] = parser[section][k]
+ if k == "ignore_globs":
+ config[k] = config[k].split(",")
+ return config
+
+ def _project_url_base(self) -> str:
+ """Construct the base URL for the project."""
+ if not all([self.entity, self.project]):
+ return ""
+
+ app_url = util.app_url(self.base_url)
+ return f"{app_url}/{quote(self.entity or '')}/{quote(self.project or '')}"
+
+ def _get_url_query_string(self) -> str:
+ """Construct the query string for project, run, and sweep URLs."""
+ # TODO: remove dependency on Api()
+ if self.anonymous not in ["allow", "must"]:
+ return ""
+
+ api_key = apikey.api_key(settings=self)
+
+ return f"?{urlencode({'apiKey': api_key})}"
+
+ @staticmethod
+ def _runmoment_preprocessor(
+ val: Union[RunMoment, str, None],
+ ) -> Optional[RunMoment]:
+ """Preprocess the setting for forking or resuming a run."""
+ if isinstance(val, RunMoment) or val is None:
+ return val
+ elif isinstance(val, str):
+ return RunMoment.from_uri(val)
+
+ if not IS_PYDANTIC_V2:
+
+ def model_copy(self, *args, **kwargs):
+ return self.copy(*args, **kwargs)
+
+ def model_dump(self, **kwargs):
+ """Compatibility method for Pydantic v1 to mimic v2's model_dump.
+
+ In v1, this is equivalent to dict() but also includes computed properties.
+
+ Args:
+ **kwargs: Options passed to the dict method
+ - exclude_none: Whether to exclude fields with None values
+
+ Returns:
+ A dictionary of the model's fields and computed properties
+ """
+ # Handle exclude_none separately since it's named differently in v1
+ exclude_none = kwargs.pop("exclude_none", False)
+
+ # Start with regular fields from dict()
+ result = self.dict(**kwargs)
+
+ # Get all computed properties
+ for name in dir(self.__class__):
+ attr = getattr(self.__class__, name, None)
+ if isinstance(attr, property):
+ try:
+ # Only include properties that don't raise errors
+ value = getattr(self, name)
+ result[name] = value
+ except (AttributeError, NotImplementedError, TypeError, ValueError):
+ # Skip properties that can't be accessed or raise errors
+ pass
+ elif isinstance(attr, RunMoment):
+ value = getattr(self, name)
+ result[name] = value
+
+ # Special Pydantic attributes that should always be excluded
+ exclude_fields = {
+ "model_config",
+ "model_fields",
+ "model_fields_set",
+ "__fields__",
+ "__model_fields_set",
+ "__pydantic_self__",
+ "__pydantic_initialised__",
+ }
+
+ # Remove special Pydantic attributes
+ for field in exclude_fields:
+ if field in result:
+ del result[field]
+
+ if exclude_none:
+ # Remove None values from the result
+ return {k: v for k, v in result.items() if v is not None}
+
+ return result
+
+ @property
+ def model_fields_set(self) -> set:
+ """Return a set of fields that have been explicitly set.
+
+ This is a compatibility property for Pydantic v1 to mimic v2's model_fields_set.
+ """
+ return getattr(self, "__fields_set__", set())
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_setup.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..ace1ddd3f9e62a9802ffe5d0e723f3aea5df6af3
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_setup.py
@@ -0,0 +1,560 @@
+"""Global W&B library state.
+
+This module manages global state, which for wandb includes:
+
+- Settings configured through `wandb.setup()`
+- The list of active runs
+- A subprocess ("the internal service") that asynchronously uploads metrics
+
+This module is fork-aware: in a forked process such as that spawned by the
+`multiprocessing` module, `wandb.singleton()` returns a new object, not the
+one inherited from the parent process. This requirement comes from backward
+compatibility with old design choices: the hardest one to fix is that wandb
+was originally designed to have a single run for the entire process that
+`wandb.init()` was meant to return. Back then, the only way to create
+multiple simultaneous runs in a single script was to run subprocesses, and since
+the built-in `multiprocessing` module forks by default, this required a PID
+check to make `wandb.init()` ignore the inherited global run.
+
+Another reason for fork-awareness is that the process that starts up
+the internal service owns it and is responsible for shutting it down,
+and child processes shouldn't also try to do that. This is easier to
+redesign.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import pathlib
+import sys
+import threading
+from typing import TYPE_CHECKING, Any, Union
+
+import wandb
+import wandb.integration.sagemaker as sagemaker
+from wandb.env import CONFIG_DIR
+from wandb.sdk.lib import asyncio_manager, import_hooks, wb_logging
+
+from . import wandb_settings
+from .lib import config_util, server
+
+if TYPE_CHECKING:
+ from wandb.sdk import wandb_run
+ from wandb.sdk.lib.service.service_connection import ServiceConnection
+ from wandb.sdk.wandb_settings import Settings
+
+
+class _EarlyLogger:
+ """Early logger which captures logs in memory until logging can be configured."""
+
+ def __init__(self) -> None:
+ self._log: list[tuple] = []
+ self._exception: list[tuple] = []
+ # support old warn() as alias of warning()
+ self.warn = self.warning
+
+ def debug(self, msg: str, *args: Any, **kwargs: Any) -> None:
+ self._log.append((logging.DEBUG, msg, args, kwargs))
+
+ def info(self, msg: str, *args: Any, **kwargs: Any) -> None:
+ self._log.append((logging.INFO, msg, args, kwargs))
+
+ def warning(self, msg: str, *args: Any, **kwargs: Any) -> None:
+ self._log.append((logging.WARNING, msg, args, kwargs))
+
+ def error(self, msg: str, *args: Any, **kwargs: Any) -> None:
+ self._log.append((logging.ERROR, msg, args, kwargs))
+
+ def critical(self, msg: str, *args: Any, **kwargs: Any) -> None:
+ self._log.append((logging.CRITICAL, msg, args, kwargs))
+
+ def exception(self, msg: str, *args: Any, **kwargs: Any) -> None:
+ self._exception.append((msg, args, kwargs))
+
+ def log(self, level: str, msg: str, *args: Any, **kwargs: Any) -> None:
+ self._log.append((level, msg, args, kwargs))
+
+ def _flush(self, new_logger: Logger) -> None:
+ assert self is not new_logger
+ for level, msg, args, kwargs in self._log:
+ new_logger.log(level, msg, *args, **kwargs)
+ for msg, args, kwargs in self._exception:
+ new_logger.exception(msg, *args, **kwargs)
+
+
+Logger = Union[logging.Logger, _EarlyLogger]
+
+
+class _WandbSetup:
+ """W&B library singleton."""
+
+ def __init__(self, pid: int) -> None:
+ self._asyncer = asyncio_manager.AsyncioManager()
+ self._asyncer.start()
+
+ self._connection: ServiceConnection | None = None
+
+ self._active_runs: list[wandb_run.Run] = []
+ self._active_runs_lock = threading.Lock()
+
+ self._sweep_config: dict | None = None
+ self._server: server.Server | None = None
+ self._pid = pid
+
+ # TODO(jhr): defer strict checks until settings are fully initialized
+ # and logging is ready
+ self._logger: Logger = _EarlyLogger()
+
+ self._settings: Settings | None = None
+ self._settings_environ: dict[str, str] | None = None
+
+ @property
+ def asyncer(self) -> asyncio_manager.AsyncioManager:
+ """The internal asyncio thread used by wandb."""
+ return self._asyncer
+
+ def add_active_run(self, run: wandb_run.Run) -> None:
+ """Append a run to the active runs list.
+
+ This must be called when a run is initialized.
+
+ Args:
+ run: A newly initialized run.
+ """
+ with self._active_runs_lock:
+ if run not in self._active_runs:
+ self._active_runs.append(run)
+
+ def remove_active_run(self, run: wandb_run.Run) -> None:
+ """Remove the run from the active runs list.
+
+ This must be called when a run is finished.
+
+ Args:
+ run: A run that is finished or crashed.
+ """
+ try:
+ with self._active_runs_lock:
+ self._active_runs.remove(run)
+ except ValueError:
+ pass # Removing a run multiple times is not an error.
+
+ @property
+ def most_recent_active_run(self) -> wandb_run.Run | None:
+ """The most recently initialized run that is not yet finished."""
+ with self._active_runs_lock:
+ if not self._active_runs:
+ return None
+
+ return self._active_runs[-1]
+
+ def finish_all_active_runs(self) -> None:
+ """Finish all unfinished runs.
+
+ NOTE: This is slightly inefficient as it finishes runs one at a time.
+ This only exists to support using the `reinit="finish_previous"`
+ setting together with `reinit="create_new"` which does not seem to be a
+ useful pattern. Since `"create_new"` should eventually become the
+ default and only behavior, it does not seem worth optimizing.
+ """
+ # Take a snapshot as each call to `finish()` modifies `_active_runs`.
+ with self._active_runs_lock:
+ runs_copy = list(self._active_runs)
+
+ for run in runs_copy:
+ run.finish()
+
+ def did_environment_change(self) -> bool:
+ """Check if os.environ has changed since settings were initialized."""
+ if not self._settings_environ:
+ return False
+
+ exclude_env_vars = {"WANDB_SERVICE", "WANDB_KUBEFLOW_URL"}
+ singleton_env = {
+ k: v
+ for k, v in self._settings_environ.items()
+ if k.startswith("WANDB_") and k not in exclude_env_vars
+ }
+ os_env = {
+ k: v
+ for k, v in os.environ.items()
+ if k.startswith("WANDB_") and k not in exclude_env_vars
+ }
+
+ return (
+ set(singleton_env.keys()) != set(os_env.keys()) #
+ or set(singleton_env.values()) != set(os_env.values())
+ )
+
+ def _load_settings(
+ self,
+ *,
+ system_settings_path: str | None,
+ disable_sagemaker: bool,
+ overrides: Settings | None = None,
+ ) -> None:
+ """Load settings from environment variables, config files, etc.
+
+ Args:
+ system_settings_path: Location of system settings file to use.
+ If not provided, reads the WANDB_CONFIG_DIR environment
+ variable or uses the default location.
+ disable_sagemaker: If true, skips modifying settings based on
+ SageMaker.
+ overrides: Additional settings to apply to the global settings.
+ """
+ self._settings = wandb_settings.Settings()
+
+ # the pid of the process to monitor for system stats
+ pid = os.getpid()
+ self._logger.info(f"Current SDK version is {wandb.__version__}")
+ self._logger.info(f"Configure stats pid to {pid}")
+ self._settings.x_stats_pid = pid
+
+ if system_settings_path:
+ self._settings.settings_system = system_settings_path
+ elif config_dir_str := os.getenv(CONFIG_DIR, None):
+ config_dir = pathlib.Path(config_dir_str).expanduser()
+ self._settings.settings_system = str(config_dir / "settings")
+ else:
+ self._settings.settings_system = str(
+ pathlib.Path("~", ".config", "wandb", "settings").expanduser()
+ )
+
+ # load settings from the system config
+ if self._settings.settings_system:
+ self._logger.info(
+ f"Loading settings from {self._settings.settings_system}",
+ )
+ self._settings.update_from_system_config_file()
+
+ # load settings from the workspace config
+ if self._settings.settings_workspace:
+ self._logger.info(
+ f"Loading settings from {self._settings.settings_workspace}",
+ )
+ self._settings.update_from_workspace_config_file()
+
+ # load settings from the environment variables
+ self._logger.info("Loading settings from environment variables")
+ self._settings_environ = os.environ.copy()
+ self._settings.update_from_env_vars(self._settings_environ)
+
+ # infer settings from the system environment
+ self._settings.update_from_system_environment()
+
+ # load SageMaker settings
+ if (
+ not self._settings.sagemaker_disable
+ and not disable_sagemaker
+ and sagemaker.is_using_sagemaker()
+ ):
+ self._logger.info("Loading SageMaker settings")
+ sagemaker.set_global_settings(self._settings)
+
+ # load settings from the passed init/setup settings
+ if overrides:
+ self._settings.update_from_settings(overrides)
+
+ wandb.termsetup(self._settings, None)
+
+ def _update(self, settings: Settings | None) -> None:
+ """Update settings, initializing them if necessary.
+
+ Args:
+ settings: Overrides to apply, if any.
+ """
+ if not self._settings:
+ system_settings_path = settings.settings_system if settings else None
+ disable_sagemaker = settings.sagemaker_disable if settings else False
+ self._load_settings(
+ system_settings_path=system_settings_path,
+ disable_sagemaker=disable_sagemaker,
+ overrides=settings,
+ )
+
+ # This is 'elif' because load_settings already applies overrides.
+ elif settings:
+ self._settings.update_from_settings(settings)
+
+ def update_user_settings(self) -> None:
+ # Get rid of cached results to force a refresh.
+ self._server = None
+ user_settings = self._load_user_settings()
+ if user_settings is not None:
+ self.settings.update_from_dict(user_settings)
+
+ def _early_logger_flush(self, new_logger: Logger) -> None:
+ if self._logger is new_logger:
+ return
+
+ if isinstance(self._logger, _EarlyLogger):
+ self._logger._flush(new_logger)
+ self._logger = new_logger
+
+ def _get_logger(self) -> Logger:
+ return self._logger
+
+ @property
+ def settings(self) -> wandb_settings.Settings:
+ """The global wandb settings.
+
+ Initializes settings if they have not yet been loaded.
+ """
+ if not self._settings:
+ self._load_settings(
+ system_settings_path=None,
+ disable_sagemaker=False,
+ )
+ assert self._settings
+
+ return self._settings
+
+ @property
+ def settings_if_loaded(self) -> wandb_settings.Settings | None:
+ """The global wandb settings, or None if not yet loaded."""
+ return self._settings
+
+ def _get_entity(self) -> str | None:
+ if self._settings and self._settings._offline:
+ return None
+ entity = self.viewer.get("entity")
+ return entity
+
+ def _get_username(self) -> str | None:
+ if self._settings and self._settings._offline:
+ return None
+ return self.viewer.get("username")
+
+ def _get_teams(self) -> list[str]:
+ if self._settings and self._settings._offline:
+ return []
+ teams = self.viewer.get("teams")
+ if teams:
+ teams = [team["node"]["name"] for team in teams["edges"]]
+ return teams or []
+
+ @property
+ def viewer(self) -> dict[str, Any]:
+ if self._server is None:
+ self._server = server.Server(settings=self.settings)
+
+ return self._server.viewer
+
+ def _load_user_settings(self) -> dict[str, Any] | None:
+ # offline?
+ if self._server is None:
+ return None
+
+ flags = self._server._flags
+ user_settings = dict()
+ if "code_saving_enabled" in flags:
+ user_settings["save_code"] = flags["code_saving_enabled"]
+
+ email = self.viewer.get("email", None)
+ if email:
+ user_settings["email"] = email
+
+ return user_settings
+
+ @property
+ def config(self) -> dict:
+ sweep_path = self.settings.sweep_param_path
+ if sweep_path:
+ self._sweep_config = config_util.dict_from_config_file(
+ sweep_path, must_exist=True
+ )
+
+ config = {}
+
+ # if config_paths was set, read in config dict
+ if self.settings.config_paths:
+ # TODO(jhr): handle load errors, handle list of files
+ for config_path in self.settings.config_paths:
+ config_dict = config_util.dict_from_config_file(config_path)
+ if config_dict:
+ config.update(config_dict)
+
+ return config
+
+ def _teardown(self, exit_code: int | None = None) -> None:
+ import_hooks.unregister_all_post_import_hooks()
+
+ if self._connection:
+ internal_exit_code = self._connection.teardown(exit_code or 0)
+ else:
+ internal_exit_code = None
+
+ self._asyncer.join()
+
+ if internal_exit_code not in (None, 0):
+ sys.exit(internal_exit_code)
+
+ def ensure_service(self) -> ServiceConnection:
+ """Returns a connection to the service process creating it if needed."""
+ if self._connection:
+ return self._connection
+
+ from wandb.sdk.lib.service import service_connection
+
+ self._connection = service_connection.connect_to_service(
+ self._asyncer,
+ self.settings,
+ )
+ return self._connection
+
+ def assert_service(self) -> ServiceConnection:
+ """Returns a connection to the service process, asserting it exists.
+
+ Unlike ensure_service(), this will not start up a service process
+ if it didn't already exist.
+ """
+ if not self._connection:
+ raise AssertionError("Expected service process to exist.")
+
+ return self._connection
+
+
+_singleton: _WandbSetup | None = None
+"""The W&B library singleton, or None if not yet set up.
+
+The value is invalid and must not be used if `os.getpid() != _singleton._pid`.
+"""
+
+_singleton_lock = threading.Lock()
+
+
+def singleton() -> _WandbSetup:
+ """The W&B singleton for the current process.
+
+ The first call to this in this process (which may be a fork of another
+ process) creates the singleton, and all subsequent calls return it
+ until teardown(). This does not start the service process.
+ """
+ return _setup(start_service=False, load_settings=False)
+
+
+@wb_logging.log_to_all_runs()
+def _setup(
+ settings: Settings | None = None,
+ start_service: bool = True,
+ load_settings: bool = True,
+) -> _WandbSetup:
+ """Set up library context.
+
+ Args:
+ settings: Global settings to set, or updates to the global settings
+ if the singleton has already been initialized.
+ start_service: Whether to start up the service process.
+ NOTE: A service process will only be started if allowed by the
+ global settings (after the given updates). The service will not
+ start up if the mode resolves to "disabled".
+ load_settings: Whether to load settings from the environment
+ if creating a new singleton. If False, then settings and
+ start_service must be None.
+ """
+ global _singleton
+
+ if not load_settings and settings:
+ raise ValueError("Cannot pass settings if load_settings is False.")
+ if not load_settings and start_service:
+ raise ValueError("Cannot use start_service if load_settings is False.")
+
+ pid = os.getpid()
+ with _singleton_lock:
+ if _singleton and _singleton._pid == pid:
+ current_singleton = _singleton
+ else:
+ current_singleton = _WandbSetup(pid=pid)
+
+ if load_settings:
+ current_singleton._update(settings)
+
+ if start_service and not current_singleton.settings._noop:
+ current_singleton.ensure_service()
+
+ _singleton = current_singleton
+
+ return _singleton
+
+
+def setup(settings: Settings | None = None) -> _WandbSetup:
+ """Prepares W&B for use in the current process and its children.
+
+ You can usually ignore this as it is implicitly called by `wandb.init()`.
+
+ When using wandb in multiple processes, calling `wandb.setup()`
+ in the parent process before starting child processes may improve
+ performance and resource utilization.
+
+ Note that `wandb.setup()` modifies `os.environ`, and it is important
+ that child processes inherit the modified environment variables.
+
+ See also `wandb.teardown()`.
+
+ Args:
+ settings: Configuration settings to apply globally. These can be
+ overridden by subsequent `wandb.init()` calls.
+
+ Example:
+ ```python
+ import multiprocessing
+
+ import wandb
+
+
+ def run_experiment(params):
+ with wandb.init(config=params):
+ # Run experiment
+ pass
+
+
+ if __name__ == "__main__":
+ # Start backend and set global config
+ wandb.setup(settings={"project": "my_project"})
+
+ # Define experiment parameters
+ experiment_params = [
+ {"learning_rate": 0.01, "epochs": 10},
+ {"learning_rate": 0.001, "epochs": 20},
+ ]
+
+ # Start multiple processes, each running a separate experiment
+ processes = []
+ for params in experiment_params:
+ p = multiprocessing.Process(target=run_experiment, args=(params,))
+ p.start()
+ processes.append(p)
+
+ # Wait for all processes to complete
+ for p in processes:
+ p.join()
+
+ # Optional: Explicitly shut down the backend
+ wandb.teardown()
+ ```
+ """
+ return _setup(settings=settings)
+
+
+@wb_logging.log_to_all_runs()
+def teardown(exit_code: int | None = None) -> None:
+ """Waits for W&B to finish and frees resources.
+
+ Completes any runs that were not explicitly finished
+ using `run.finish()` and waits for all data to be uploaded.
+
+ It is recommended to call this at the end of a session
+ that used `wandb.setup()`. It is invoked automatically
+ in an `atexit` hook, but this is not reliable in certain setups
+ such as when using Python's `multiprocessing` module.
+ """
+ global _singleton
+
+ with _singleton_lock:
+ orig_singleton = _singleton
+ _singleton = None
+
+ if orig_singleton:
+ orig_singleton._teardown(exit_code=exit_code)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_summary.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_summary.py
new file mode 100644
index 0000000000000000000000000000000000000000..f15c7cc041959115b0cfc0024f5ec2b690209558
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_summary.py
@@ -0,0 +1,150 @@
+import abc
+import typing as t
+
+from .interface.summary_record import SummaryItem, SummaryRecord
+
+
+def _get_dict(d):
+ if isinstance(d, dict):
+ return d
+ # assume argparse Namespace
+ return vars(d)
+
+
+class SummaryDict(metaclass=abc.ABCMeta):
+ """dict-like wrapper for the nested dictionaries in a SummarySubDict.
+
+ Triggers self._root._callback on property changes.
+ """
+
+ @abc.abstractmethod
+ def _as_dict(self):
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _update(self, record: SummaryRecord):
+ raise NotImplementedError
+
+ def keys(self):
+ return [k for k in self._as_dict().keys() if k != "_wandb"]
+
+ def get(self, key, default=None):
+ return self._as_dict().get(key, default)
+
+ def __getitem__(self, key):
+ item = self._as_dict()[key]
+
+ if isinstance(item, dict):
+ # this nested dict needs to be wrapped:
+ wrapped_item = SummarySubDict()
+ object.__setattr__(wrapped_item, "_items", item)
+ object.__setattr__(wrapped_item, "_parent", self)
+ object.__setattr__(wrapped_item, "_parent_key", key)
+
+ return wrapped_item
+
+ # this item isn't a nested dict
+ return item
+
+ __getattr__ = __getitem__
+
+ def __setitem__(self, key, val):
+ self.update({key: val})
+
+ __setattr__ = __setitem__
+
+ def __delattr__(self, key):
+ record = SummaryRecord()
+ item = SummaryItem()
+ item.key = (key,)
+ record.remove = (item,)
+ self._update(record)
+
+ __delitem__ = __delattr__
+
+ def update(self, d: t.Dict):
+ # import ipdb; ipdb.set_trace()
+ record = SummaryRecord()
+ for key, value in d.items():
+ item = SummaryItem()
+ item.key = (key,)
+ item.value = value
+ record.update.append(item)
+
+ self._update(record)
+
+
+class Summary(SummaryDict):
+ """Track single values for each metric for each run.
+
+ By default, a metric's summary is the last value of its History.
+
+ For example, `wandb.log({'accuracy': 0.9})` will add a new step to History and
+ update Summary to the latest value. In some cases, it's more useful to have
+ the maximum or minimum of a metric instead of the final value. You can set
+ history manually `(wandb.summary['accuracy'] = best_acc)`.
+
+ In the UI, summary metrics appear in the table to compare across runs.
+ Summary metrics are also used in visualizations like the scatter plot and
+ parallel coordinates chart.
+
+ After training has completed, you may want to save evaluation metrics to a
+ run. Summary can handle numpy arrays and PyTorch/TensorFlow tensors. When
+ you save one of these types to Summary, we persist the entire tensor in a
+ binary file and store high level metrics in the summary object, such as min,
+ mean, variance, and 95th percentile.
+
+ Examples:
+ ```python
+ wandb.init(config=args)
+
+ best_accuracy = 0
+ for epoch in range(1, args.epochs + 1):
+ test_loss, test_accuracy = test()
+ if test_accuracy > best_accuracy:
+ wandb.run.summary["best_accuracy"] = test_accuracy
+ best_accuracy = test_accuracy
+ ```
+ """
+
+ _update_callback: t.Callable
+ _get_current_summary_callback: t.Callable
+
+ def __init__(self, get_current_summary_callback: t.Callable):
+ super().__init__()
+ object.__setattr__(self, "_update_callback", None)
+ object.__setattr__(
+ self, "_get_current_summary_callback", get_current_summary_callback
+ )
+
+ def _set_update_callback(self, update_callback: t.Callable):
+ object.__setattr__(self, "_update_callback", update_callback)
+
+ def _as_dict(self):
+ return self._get_current_summary_callback()
+
+ def _update(self, record: SummaryRecord):
+ if self._update_callback: # type: ignore
+ self._update_callback(record)
+
+
+class SummarySubDict(SummaryDict):
+ """Non-root node of the summary data structure.
+
+ Contains a path to itself from the root.
+ """
+
+ _items: t.Dict
+ _parent: SummaryDict
+ _parent_key: str
+
+ def __init__(self):
+ object.__setattr__(self, "_items", dict())
+ object.__setattr__(self, "_parent", None)
+ object.__setattr__(self, "_parent_key", None)
+
+ def _as_dict(self):
+ return self._items
+
+ def _update(self, record: SummaryRecord):
+ return self._parent._update(record._add_next_parent(self._parent_key))
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_sweep.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_sweep.py
new file mode 100644
index 0000000000000000000000000000000000000000..98707a32345dc34a055a34668714cd3d4b7a6008
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_sweep.py
@@ -0,0 +1,120 @@
+import urllib.parse
+from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Union
+
+import wandb
+from wandb import env
+from wandb.apis import InternalApi
+from wandb.sdk.launch.sweeps.utils import handle_sweep_config_violations
+
+from . import wandb_login
+
+if TYPE_CHECKING:
+ from wandb.wandb_controller import _WandbController
+
+
+def _get_sweep_url(api, sweep_id):
+ """Return sweep url if we can figure it out."""
+ if api.api_key:
+ if api.settings("entity") is None:
+ viewer = api.viewer()
+ if viewer.get("entity"):
+ api.set_setting("entity", viewer["entity"])
+ project = api.settings("project")
+ if not project:
+ return
+ if api.settings("entity"):
+ return "{base}/{entity}/{project}/sweeps/{sweepid}".format(
+ base=api.app_url,
+ entity=urllib.parse.quote(api.settings("entity")),
+ project=urllib.parse.quote(project),
+ sweepid=urllib.parse.quote(sweep_id),
+ )
+
+
+def sweep(
+ sweep: Union[dict, Callable],
+ entity: Optional[str] = None,
+ project: Optional[str] = None,
+ prior_runs: Optional[List[str]] = None,
+) -> str:
+ """Initialize a hyperparameter sweep.
+
+ Search for hyperparameters that optimizes a cost function
+ of a machine learning model by testing various combinations.
+
+ Make note the unique identifier, `sweep_id`, that is returned.
+ At a later step provide the `sweep_id` to a sweep agent.
+
+ See [Sweep configuration structure](https://docs.wandb.ai/guides/sweeps/define-sweep-configuration)
+ for information on how to define your sweep.
+
+ Args:
+ sweep: The configuration of a hyperparameter search.
+ (or configuration generator).
+ If you provide a callable, ensure that the callable does
+ not take arguments and that it returns a dictionary that
+ conforms to the W&B sweep config spec.
+ entity: The username or team name where you want to send W&B
+ runs created by the sweep to. Ensure that the entity you
+ specify already exists. If you don't specify an entity,
+ the run will be sent to your default entity,
+ which is usually your username.
+ project: The name of the project where W&B runs created from
+ the sweep are sent to. If the project is not specified, the
+ run is sent to a project labeled 'Uncategorized'.
+ prior_runs: The run IDs of existing runs to add to this sweep.
+
+ Returns:
+ str: A unique identifier for the sweep.
+ """
+ if callable(sweep):
+ sweep = sweep()
+ """Sweep create for controller api and jupyter (eventually for cli)."""
+
+ # Project may be only found in the sweep config.
+ if project is None and isinstance(sweep, dict):
+ project = sweep.get("project", None)
+
+ if entity:
+ env.set_entity(entity)
+ if project:
+ env.set_project(project)
+
+ # Make sure we are logged in
+ if wandb.run is None:
+ wandb_login._login(_silent=True)
+ api = InternalApi()
+ sweep_id, warnings = api.upsert_sweep(sweep, prior_runs=prior_runs)
+ handle_sweep_config_violations(warnings)
+ print("Create sweep with ID:", sweep_id) # noqa: T201
+ sweep_url = _get_sweep_url(api, sweep_id)
+ if sweep_url:
+ print("Sweep URL:", sweep_url) # noqa: T201
+ return sweep_id
+
+
+def controller(
+ sweep_id_or_config: Optional[Union[str, Dict]] = None,
+ entity: Optional[str] = None,
+ project: Optional[str] = None,
+) -> "_WandbController":
+ """Public sweep controller constructor.
+
+ Examples:
+ ```python
+ import wandb
+
+ tuner = wandb.controller(...)
+ print(tuner.sweep_config)
+ print(tuner.sweep_id)
+ tuner.configure_search(...)
+ tuner.configure_stopping(...)
+ ```
+
+ """
+ from ..wandb_controller import _WandbController
+
+ c = _WandbController(
+ sweep_id_or_config=sweep_id_or_config, entity=entity, project=project
+ )
+ return c
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_sync.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_sync.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c5a3fde47bdda06ba979f912eae0ffc31502548
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_sync.py
@@ -0,0 +1,71 @@
+import pathlib
+from typing import TYPE_CHECKING, Optional
+
+from wandb import util
+from wandb.errors.term import termerror, termlog
+
+from . import wandb_setup
+from .backend.backend import Backend
+from .lib.runid import generate_id
+
+if TYPE_CHECKING:
+ from wandb.proto import wandb_internal_pb2
+
+
+def _sync(
+ path: str,
+ run_id: Optional[str] = None,
+ project: Optional[str] = None,
+ entity: Optional[str] = None,
+ mark_synced: Optional[bool] = None,
+ append: Optional[bool] = None,
+ skip_console: Optional[bool] = None,
+) -> "wandb_internal_pb2.SyncResponse":
+ wl = wandb_setup.setup()
+ assert wl is not None
+
+ stream_id = generate_id()
+
+ settings = wl.settings.to_proto()
+ p = pathlib.Path(path)
+
+ # update sync_file setting to point to the passed path
+ settings.sync_file.value = str(p.absolute())
+ settings.sync_dir.value = str(p.parent.absolute())
+ settings.files_dir.value = str(p.parent.absolute() / "files")
+ settings.x_sync.value = True
+ if run_id:
+ settings.run_id.value = run_id
+ if entity:
+ settings.entity.value = entity
+ if project:
+ settings.project.value = project
+ if skip_console:
+ settings.console.value = "off"
+ if append:
+ settings.resume.value = "allow"
+
+ service = wl.ensure_service()
+ service.inform_init(settings=settings, run_id=stream_id)
+
+ backend = Backend(settings=wl.settings, service=service)
+ backend.ensure_launched()
+
+ assert backend.interface
+ backend.interface._stream_id = stream_id # type: ignore
+
+ handle = backend.interface.deliver_finish_sync()
+ result = handle.wait_or(timeout=None)
+ response = result.response.sync_response
+ if response.url:
+ termlog(f"Synced {p} to {util.app_url(response.url)}")
+ # create a .synced file in the directory if mark_synced is true
+ if mark_synced:
+ with open(f"{p}.synced", "w"):
+ pass
+ else:
+ termerror(f"Failed to sync {p}")
+ if response.error and response.error.message:
+ termerror(response.error.message)
+
+ return response
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_watch.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_watch.py
new file mode 100644
index 0000000000000000000000000000000000000000..170a5c55ffec85d2c6cb052028183104a2cbb132
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sdk/wandb_watch.py
@@ -0,0 +1,146 @@
+"""watch."""
+
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING, Sequence
+
+try:
+ from typing import Literal
+except ImportError:
+ from typing_extensions import Literal # type: ignore
+
+import wandb
+
+from .lib import telemetry
+
+if TYPE_CHECKING:
+ import torch # type: ignore [import-not-found]
+
+logger = logging.getLogger("wandb")
+
+_global_watch_idx = 0
+
+
+def _watch(
+ run: wandb.Run,
+ models: torch.nn.Module | Sequence[torch.nn.Module],
+ criterion: torch.F | None = None,
+ log: Literal["gradients", "parameters", "all"] | None = "gradients",
+ log_freq: int = 1000,
+ idx: int | None = None,
+ log_graph: bool = False,
+):
+ """Hooks into the given PyTorch model(s) to monitor gradients and the model's computational graph.
+
+ This function can track parameters, gradients, or both during training. It should be
+ extended to support arbitrary machine learning models in the future.
+
+ Args:
+ run (wandb.Run): The run object to log to.
+ models (Union[torch.nn.Module, Sequence[torch.nn.Module]]):
+ A single model or a sequence of models to be monitored.
+ criterion (Optional[torch.F]):
+ The loss function being optimized (optional).
+ log (Optional[Literal["gradients", "parameters", "all"]]):
+ Specifies whether to log "gradients", "parameters", or "all".
+ Set to None to disable logging. (default="gradients")
+ log_freq (int):
+ Frequency (in batches) to log gradients and parameters. (default=1000)
+ idx (Optional[int]):
+ Index used when tracking multiple models with `wandb.watch`. (default=None)
+ log_graph (bool):
+ Whether to log the model's computational graph. (default=False)
+
+ Returns:
+ wandb.Graph:
+ The graph object, which will be populated after the first backward pass.
+
+ Raises:
+ ValueError: If `wandb.init` has not been called.
+ TypeError: If any of the models are not instances of `torch.nn.Module`.
+ """
+ global _global_watch_idx
+
+ with telemetry.context() as tel:
+ tel.feature.watch = True
+
+ logger.info("Watching")
+
+ if log not in {"gradients", "parameters", "all", None}:
+ raise ValueError("log must be one of 'gradients', 'parameters', 'all', or None")
+
+ log_parameters = log in {"parameters", "all"}
+ log_gradients = log in {"gradients", "all"}
+
+ if not isinstance(models, (tuple, list)):
+ models = (models,)
+
+ torch = wandb.util.get_module(
+ "torch", required="wandb.watch only works with pytorch, couldn't import torch."
+ )
+
+ for model in models:
+ if not isinstance(model, torch.nn.Module):
+ raise TypeError(
+ f"Expected a pytorch model (torch.nn.Module). Received {type(model)}"
+ )
+
+ graphs = []
+ prefix = ""
+
+ if idx is None:
+ idx = _global_watch_idx
+ for local_idx, model in enumerate(models):
+ global_idx = idx + local_idx
+ _global_watch_idx += 1
+ if global_idx > 0:
+ # TODO: this makes ugly chart names like gradients/graph_1conv1d.bias
+ prefix = f"graph_{global_idx}"
+
+ if log_parameters:
+ run._torch.add_log_parameters_hook(
+ model,
+ prefix=prefix,
+ log_freq=log_freq,
+ )
+
+ if log_gradients:
+ run._torch.add_log_gradients_hook(
+ model,
+ prefix=prefix,
+ log_freq=log_freq,
+ )
+
+ if log_graph:
+ graph = run._torch.hook_torch(model, criterion, graph_idx=global_idx)
+ graphs.append(graph)
+ # NOTE: the graph is set in run.summary by hook_torch on the backward pass
+ return graphs
+
+
+def _unwatch(
+ run: wandb.Run, models: torch.nn.Module | Sequence[torch.nn.Module] | None = None
+) -> None:
+ """Remove pytorch model topology, gradient and parameter hooks.
+
+ Args:
+ run (wandb.Run):
+ The run object to log to.
+ models (torch.nn.Module | Sequence[torch.nn.Module]):
+ Optional list of pytorch models that have had watch called on them
+ """
+ if models:
+ if not isinstance(models, (tuple, list)):
+ models = (models,)
+ for model in models:
+ if not hasattr(model, "_wandb_hook_names"):
+ wandb.termwarn(f"{model} model has not been watched")
+ else:
+ for name in model._wandb_hook_names:
+ run._torch.unhook(name)
+ delattr(model, "_wandb_hook_names")
+ # TODO: we should also remove recursively model._wandb_watch_called
+
+ else:
+ run._torch.unhook_all()
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sklearn.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sklearn.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c72b8228b5cb342ba2a217104ee5ce9267a2d2f
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/sklearn.py
@@ -0,0 +1,35 @@
+from wandb.integration.sklearn import (
+ plot_calibration_curve,
+ plot_class_proportions,
+ plot_classifier,
+ plot_clusterer,
+ plot_confusion_matrix,
+ plot_elbow_curve,
+ plot_feature_importances,
+ plot_learning_curve,
+ plot_outlier_candidates,
+ plot_precision_recall,
+ plot_regressor,
+ plot_residuals,
+ plot_roc,
+ plot_silhouette,
+ plot_summary_metrics,
+)
+
+__all__ = (
+ "plot_classifier",
+ "plot_clusterer",
+ "plot_regressor",
+ "plot_summary_metrics",
+ "plot_learning_curve",
+ "plot_feature_importances",
+ "plot_class_proportions",
+ "plot_calibration_curve",
+ "plot_roc",
+ "plot_precision_recall",
+ "plot_confusion_matrix",
+ "plot_elbow_curve",
+ "plot_silhouette",
+ "plot_residuals",
+ "plot_outlier_candidates",
+)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/trigger.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/trigger.py
new file mode 100644
index 0000000000000000000000000000000000000000..15b52eec9e121a430ae64f1a5b8265f2cb2b8786
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/trigger.py
@@ -0,0 +1,29 @@
+"""Module to facilitate adding hooks to wandb actions.
+
+Usage:
+ import trigger
+ trigger.register('on_something', func)
+ trigger.call('on_something', *args, **kwargs)
+ trigger.unregister('on_something', func)
+"""
+
+from typing import Any, Callable
+
+_triggers = {}
+
+
+def reset():
+ _triggers.clear()
+
+
+def register(event: str, func: Callable):
+ _triggers.setdefault(event, []).append(func)
+
+
+def call(event_str: str, *args: Any, **kwargs: Any):
+ for func in _triggers.get(event_str, []):
+ func(*args, **kwargs)
+
+
+def unregister(event: str, func: Callable):
+ _triggers[event].remove(func)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/util.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..264e526ed0d4f02cbf866c196192dc4b2ca25581
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/util.py
@@ -0,0 +1,2040 @@
+import colorsys
+import contextlib
+import dataclasses
+import enum
+import functools
+import gzip
+import importlib
+import importlib.util
+import itertools
+import json
+import logging
+import math
+import numbers
+import os
+import pathlib
+import platform
+import queue
+import random
+import re
+import secrets
+import shlex
+import socket
+import string
+import sys
+import tarfile
+import tempfile
+import threading
+import time
+import types
+import urllib
+from dataclasses import asdict, is_dataclass
+from datetime import date, datetime, timedelta
+from importlib import import_module
+from sys import getsizeof
+from types import ModuleType
+from typing import (
+ IO,
+ TYPE_CHECKING,
+ Callable,
+ Dict,
+ Iterable,
+ List,
+ Mapping,
+ Optional,
+ Sequence,
+ TextIO,
+ Tuple,
+ Union,
+)
+
+import requests
+import yaml
+from typing_extensions import Any, Generator, TypeGuard, TypeVar
+
+import wandb
+import wandb.env
+from wandb.errors import (
+ AuthenticationError,
+ CommError,
+ UsageError,
+ WandbCoreNotAvailableError,
+ term,
+)
+from wandb.sdk.internal.thread_local_settings import _thread_local_api_settings
+from wandb.sdk.lib import filesystem, runid
+from wandb.sdk.lib.json_util import dump, dumps
+from wandb.sdk.lib.paths import FilePathStr, StrPath
+
+if TYPE_CHECKING:
+ import wandb.sdk.internal.settings_static
+ import wandb.sdk.wandb_settings
+ from wandb.sdk.artifacts.artifact import Artifact
+
+CheckRetryFnType = Callable[[Exception], Union[bool, timedelta]]
+T = TypeVar("T")
+
+
+logger = logging.getLogger(__name__)
+_not_importable = set()
+
+LAUNCH_JOB_ARTIFACT_SLOT_NAME = "_wandb_job"
+
+MAX_LINE_BYTES = (10 << 20) - (100 << 10) # imposed by back end
+IS_GIT = os.path.exists(os.path.join(os.path.dirname(__file__), "..", ".git"))
+
+# From https://docs.docker.com/engine/reference/commandline/tag/
+# "Name components may contain lowercase letters, digits and separators.
+# A separator is defined as a period, one or two underscores, or one or more dashes.
+# A name component may not start or end with a separator."
+DOCKER_IMAGE_NAME_SEPARATOR = "(?:__|[._]|[-]+)"
+RE_DOCKER_IMAGE_NAME_SEPARATOR_START = re.compile("^" + DOCKER_IMAGE_NAME_SEPARATOR)
+RE_DOCKER_IMAGE_NAME_SEPARATOR_END = re.compile(DOCKER_IMAGE_NAME_SEPARATOR + "$")
+RE_DOCKER_IMAGE_NAME_SEPARATOR_REPEAT = re.compile(DOCKER_IMAGE_NAME_SEPARATOR + "{2,}")
+RE_DOCKER_IMAGE_NAME_CHARS = re.compile(r"[^a-z0-9._\-]")
+
+# these match the environments for gorilla
+if IS_GIT:
+ SENTRY_ENV = "development"
+else:
+ SENTRY_ENV = "production"
+
+
+POW_10_BYTES = [
+ ("B", 10**0),
+ ("KB", 10**3),
+ ("MB", 10**6),
+ ("GB", 10**9),
+ ("TB", 10**12),
+ ("PB", 10**15),
+ ("EB", 10**18),
+]
+
+POW_2_BYTES = [
+ ("B", 2**0),
+ ("KiB", 2**10),
+ ("MiB", 2**20),
+ ("GiB", 2**30),
+ ("TiB", 2**40),
+ ("PiB", 2**50),
+ ("EiB", 2**60),
+]
+
+
+def vendor_setup() -> Callable:
+ """Create a function that restores user paths after vendor imports.
+
+ This enables us to use the vendor directory for packages we don't depend on. Call
+ the returned function after imports are complete. If you don't you may modify the
+ user's path which is never good.
+
+ Usage:
+
+ ```python
+ reset_path = vendor_setup()
+ # do any vendor imports...
+ reset_path()
+ ```
+ """
+ original_path = [directory for directory in sys.path]
+
+ def reset_import_path() -> None:
+ sys.path = original_path
+
+ parent_dir = os.path.abspath(os.path.dirname(__file__))
+ vendor_dir = os.path.join(parent_dir, "vendor")
+ vendor_packages = (
+ "gql-0.2.0",
+ "graphql-core-1.1",
+ "watchdog_0_9_0",
+ "promise-2.3.0",
+ )
+ package_dirs = [os.path.join(vendor_dir, p) for p in vendor_packages]
+ for p in [vendor_dir] + package_dirs:
+ if p not in sys.path:
+ sys.path.insert(1, p)
+
+ return reset_import_path
+
+
+def vendor_import(name: str) -> Any:
+ reset_path = vendor_setup()
+ module = import_module(name)
+ reset_path()
+ return module
+
+
+class LazyModuleState:
+ def __init__(self, module: types.ModuleType) -> None:
+ self.module = module
+ self.load_started = False
+ self.lock = threading.RLock()
+
+ def load(self) -> None:
+ with self.lock:
+ if self.load_started:
+ return
+ self.load_started = True
+ assert self.module.__spec__ is not None
+ assert self.module.__spec__.loader is not None
+ self.module.__spec__.loader.exec_module(self.module)
+ self.module.__class__ = types.ModuleType
+
+ # Set the submodule as an attribute on the parent module
+ # This enables access to the submodule via normal attribute access.
+ parent, _, child = self.module.__name__.rpartition(".")
+ if parent:
+ parent_module = sys.modules[parent]
+ setattr(parent_module, child, self.module)
+
+
+class LazyModule(types.ModuleType):
+ def __getattribute__(self, name: str) -> Any:
+ state = object.__getattribute__(self, "__lazy_module_state__")
+ state.load()
+ return object.__getattribute__(self, name)
+
+ def __setattr__(self, name: str, value: Any) -> None:
+ state = object.__getattribute__(self, "__lazy_module_state__")
+ state.load()
+ object.__setattr__(self, name, value)
+
+ def __delattr__(self, name: str) -> None:
+ state = object.__getattribute__(self, "__lazy_module_state__")
+ state.load()
+ object.__delattr__(self, name)
+
+
+def import_module_lazy(name: str) -> types.ModuleType:
+ """Import a module lazily, only when it is used.
+
+ Inspired by importlib.util.LazyLoader, but improved so that the module loading is
+ thread-safe. Circular dependency between modules can lead to a deadlock if the two
+ modules are loaded from different threads.
+
+ :param (str) name: Dot-separated module path. E.g., 'scipy.stats'.
+ """
+ try:
+ return sys.modules[name]
+ except KeyError:
+ spec = importlib.util.find_spec(name)
+ if spec is None:
+ raise ModuleNotFoundError
+ module = importlib.util.module_from_spec(spec)
+ module.__lazy_module_state__ = LazyModuleState(module) # type: ignore
+ module.__class__ = LazyModule
+ sys.modules[name] = module
+ return module
+
+
+def get_module(
+ name: str,
+ required: Optional[str] = None,
+ lazy: bool = True,
+) -> Any:
+ """Return module or None. Absolute import is required.
+
+ :param (str) name: Dot-separated module path. E.g., 'scipy.stats'.
+ :param (str) required: A string to raise a ValueError if missing
+ :param (bool) lazy: If True, return a lazy loader for the module.
+ :return: (module|None) If import succeeds, the module will be returned.
+ """
+ if name not in _not_importable:
+ try:
+ if not lazy:
+ return import_module(name)
+ else:
+ return import_module_lazy(name)
+ except Exception:
+ _not_importable.add(name)
+ msg = f"Error importing optional module {name}"
+ if required:
+ logger.exception(msg)
+ if required and name in _not_importable:
+ raise wandb.Error(required)
+
+
+def get_optional_module(name) -> Optional["importlib.ModuleInterface"]: # type: ignore
+ return get_module(name)
+
+
+np = get_module("numpy")
+
+pd_available = False
+pandas_spec = importlib.util.find_spec("pandas")
+if pandas_spec is not None:
+ pd_available = True
+
+# TODO: Revisit these limits
+VALUE_BYTES_LIMIT = 100000
+
+
+def app_url(api_url: str) -> str:
+ """Return the frontend app url without a trailing slash."""
+ # TODO: move me to settings
+ app_url = wandb.env.get_app_url()
+ if app_url is not None:
+ return str(app_url.strip("/"))
+ if "://api.wandb.test" in api_url:
+ # dev mode
+ return api_url.replace("://api.", "://app.").strip("/")
+ elif "://api.wandb." in api_url:
+ # cloud
+ return api_url.replace("://api.", "://").strip("/")
+ elif "://api." in api_url:
+ # onprem cloud
+ return api_url.replace("://api.", "://app.").strip("/")
+ # wandb/local
+ return api_url
+
+
+def get_full_typename(o: Any) -> Any:
+ """Determine types based on type names.
+
+ Avoids needing to to import (and therefore depend on) PyTorch, TensorFlow, etc.
+ """
+ instance_name = o.__class__.__module__ + "." + o.__class__.__name__
+ if instance_name in ["builtins.module", "__builtin__.module"]:
+ return o.__name__
+ else:
+ return instance_name
+
+
+def get_h5_typename(o: Any) -> Any:
+ typename = get_full_typename(o)
+ if is_tf_tensor_typename(typename):
+ return "tensorflow.Tensor"
+ elif is_pytorch_tensor_typename(typename):
+ return "torch.Tensor"
+ else:
+ return o.__class__.__module__.split(".")[0] + "." + o.__class__.__name__
+
+
+def is_uri(string: str) -> bool:
+ parsed_uri = urllib.parse.urlparse(string)
+ return len(parsed_uri.scheme) > 0
+
+
+def local_file_uri_to_path(uri: str) -> str:
+ """Convert URI to local filesystem path.
+
+ No-op if the uri does not have the expected scheme.
+ """
+ path = urllib.parse.urlparse(uri).path if uri.startswith("file:") else uri
+ return urllib.request.url2pathname(path)
+
+
+def get_local_path_or_none(path_or_uri: str) -> Optional[str]:
+ """Return path if local, None otherwise.
+
+ Return None if the argument is a local path (not a scheme or file:///). Otherwise
+ return `path_or_uri`.
+ """
+ parsed_uri = urllib.parse.urlparse(path_or_uri)
+ if (
+ len(parsed_uri.scheme) == 0
+ or parsed_uri.scheme == "file"
+ and len(parsed_uri.netloc) == 0
+ ):
+ return local_file_uri_to_path(path_or_uri)
+ else:
+ return None
+
+
+def check_windows_valid_filename(path: Union[int, str]) -> bool:
+ r"""Verify that the given path does not contain any invalid characters for a Windows filename.
+
+ Windows filenames cannot contain the following characters:
+ < > : " \ / | ? *
+
+ For more details, refer to the official documentation:
+ https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions
+
+ Args:
+ path: The file path to check, which can be either an integer or a string.
+
+ Returns:
+ bool: True if the path does not contain any invalid characters, False otherwise.
+ """
+ return not bool(re.search(r'[<>:"\\?*]', path)) # type: ignore
+
+
+def make_file_path_upload_safe(path: str) -> str:
+ r"""Makes the provide path safe for file upload.
+
+ The filename is made safe by:
+ 1. Removing any leading slashes to prevent writing to absolute paths
+ 2. Replacing '.' and '..' with underscores to prevent directory traversal attacks
+
+ Raises:
+ ValueError: If running on Windows and the key contains invalid filename characters
+ (\, :, *, ?, ", <, >, |)
+ """
+ sys_platform = platform.system()
+ if sys_platform == "Windows" and not check_windows_valid_filename(path):
+ raise ValueError(
+ f"Path {path} is invalid. Please remove invalid filename characters"
+ r' (\, :, *, ?, ", <, >, |)'
+ )
+
+ # On Windows, convert forward slashes to backslashes.
+ # This ensures that the key is a valid filename on Windows.
+ if sys_platform == "Windows":
+ path = str(path).replace("/", os.sep)
+
+ # Avoid writing to absolute paths by striping any leading slashes.
+ # The key has already been validated for windows operating systems in util.check_windows_valid_filename
+ # This ensures the key does not contain invalid characters for windows, such as '\' or ':'.
+ # So we can check only for '/' in the key.
+ path = path.lstrip(os.sep)
+
+ # Avoid directory traversal by replacing dots with underscores.
+ paths = path.split(os.sep)
+ safe_paths = [
+ p.replace(".", "_") if p in (os.curdir, os.pardir) else p for p in paths
+ ]
+
+ # Recombine the key into a relative path.
+ return os.sep.join(safe_paths)
+
+
+def make_tarfile(
+ output_filename: str,
+ source_dir: str,
+ archive_name: str,
+ custom_filter: Optional[Callable] = None,
+) -> None:
+ # Helper for filtering out modification timestamps
+ def _filter_timestamps(tar_info: "tarfile.TarInfo") -> Optional["tarfile.TarInfo"]:
+ tar_info.mtime = 0
+ return tar_info if custom_filter is None else custom_filter(tar_info)
+
+ descriptor, unzipped_filename = tempfile.mkstemp()
+ try:
+ with tarfile.open(unzipped_filename, "w") as tar:
+ tar.add(source_dir, arcname=archive_name, filter=_filter_timestamps)
+ # When gzipping the tar, don't include the tar's filename or modification time in the
+ # zipped archive (see https://docs.python.org/3/library/gzip.html#gzip.GzipFile)
+ with gzip.GzipFile(
+ filename="", fileobj=open(output_filename, "wb"), mode="wb", mtime=0
+ ) as gzipped_tar, open(unzipped_filename, "rb") as tar_file:
+ gzipped_tar.write(tar_file.read())
+ finally:
+ os.close(descriptor)
+ os.remove(unzipped_filename)
+
+
+def is_tf_tensor(obj: Any) -> bool:
+ import tensorflow # type: ignore
+
+ return isinstance(obj, tensorflow.Tensor)
+
+
+def is_tf_tensor_typename(typename: str) -> bool:
+ return typename.startswith("tensorflow.") and (
+ "Tensor" in typename or "Variable" in typename
+ )
+
+
+def is_tf_eager_tensor_typename(typename: str) -> bool:
+ return typename.startswith("tensorflow.") and ("EagerTensor" in typename)
+
+
+def is_pytorch_tensor(obj: Any) -> bool:
+ import torch # type: ignore
+
+ return isinstance(obj, torch.Tensor)
+
+
+def is_pytorch_tensor_typename(typename: str) -> bool:
+ return typename.startswith("torch.") and (
+ "Tensor" in typename or "Variable" in typename
+ )
+
+
+def is_jax_tensor_typename(typename: str) -> bool:
+ return typename.startswith("jaxlib.") and "Array" in typename
+
+
+def get_jax_tensor(obj: Any) -> Optional[Any]:
+ import jax # type: ignore
+
+ return jax.device_get(obj)
+
+
+def is_fastai_tensor_typename(typename: str) -> bool:
+ return typename.startswith("fastai.") and ("Tensor" in typename)
+
+
+def is_pandas_data_frame_typename(typename: str) -> bool:
+ return typename.startswith("pandas.") and "DataFrame" in typename
+
+
+def is_matplotlib_typename(typename: str) -> bool:
+ return typename.startswith("matplotlib.")
+
+
+def is_plotly_typename(typename: str) -> bool:
+ return typename.startswith("plotly.")
+
+
+def is_plotly_figure_typename(typename: str) -> bool:
+ return typename.startswith("plotly.") and typename.endswith(".Figure")
+
+
+def is_numpy_array(obj: Any) -> bool:
+ return np and isinstance(obj, np.ndarray)
+
+
+def is_pandas_data_frame(obj: Any) -> bool:
+ if pd_available:
+ import pandas as pd
+
+ return isinstance(obj, pd.DataFrame)
+ else:
+ return is_pandas_data_frame_typename(get_full_typename(obj))
+
+
+def ensure_matplotlib_figure(obj: Any) -> Any:
+ """Extract the current figure from a matplotlib object.
+
+ Return the object itself if it's a figure.
+ Raises ValueError if the object can't be converted.
+ """
+ import matplotlib # type: ignore
+ from matplotlib.figure import Figure # type: ignore
+
+ # there are combinations of plotly and matplotlib versions that don't work well together,
+ # this patches matplotlib to add a removed method that plotly assumes exists
+ from matplotlib.spines import Spine # type: ignore
+
+ def is_frame_like(self: Any) -> bool:
+ """Return True if directly on axes frame.
+
+ This is useful for determining if a spine is the edge of an
+ old style MPL plot. If so, this function will return True.
+ """
+ position = self._position or ("outward", 0.0)
+ if isinstance(position, str):
+ if position == "center":
+ position = ("axes", 0.5)
+ elif position == "zero":
+ position = ("data", 0)
+ if len(position) != 2:
+ raise ValueError("position should be 2-tuple")
+ position_type, amount = position # type: ignore
+ if position_type == "outward" and amount == 0:
+ return True
+ else:
+ return False
+
+ Spine.is_frame_like = is_frame_like
+
+ if obj == matplotlib.pyplot:
+ obj = obj.gcf()
+ elif not isinstance(obj, Figure):
+ if hasattr(obj, "figure"):
+ obj = obj.figure
+ # Some matplotlib objects have a figure function
+ if not isinstance(obj, Figure):
+ raise ValueError(
+ "Only matplotlib.pyplot or matplotlib.pyplot.Figure objects are accepted."
+ )
+ return obj
+
+
+def matplotlib_to_plotly(obj: Any) -> Any:
+ obj = ensure_matplotlib_figure(obj)
+ tools = get_module(
+ "plotly.tools",
+ required=(
+ "plotly is required to log interactive plots, install with: "
+ "`pip install plotly` or convert the plot to an image with `wandb.Image(plt)`"
+ ),
+ )
+ return tools.mpl_to_plotly(obj)
+
+
+def matplotlib_contains_images(obj: Any) -> bool:
+ obj = ensure_matplotlib_figure(obj)
+ return any(len(ax.images) > 0 for ax in obj.axes)
+
+
+def _numpy_generic_convert(obj: Any) -> Any:
+ obj = obj.item()
+ if isinstance(obj, float) and math.isnan(obj):
+ obj = None
+ elif isinstance(obj, np.generic) and (
+ obj.dtype.kind == "f" or obj.dtype == "bfloat16"
+ ):
+ # obj is a numpy float with precision greater than that of native python float
+ # (i.e., float96 or float128) or it is of custom type such as bfloat16.
+ # in these cases, obj.item() does not return a native
+ # python float (in the first case - to avoid loss of precision,
+ # so we need to explicitly cast this down to a 64bit float)
+ obj = float(obj)
+ return obj
+
+
+def _sanitize_numpy_keys(
+ d: Dict,
+ visited: Optional[Dict[int, Dict]] = None,
+) -> Tuple[Dict, bool]:
+ """Returns a dictionary where all NumPy keys are converted.
+
+ Args:
+ d: The dictionary to sanitize.
+
+ Returns:
+ A sanitized dictionary, and a boolean indicating whether anything was
+ changed.
+ """
+ out: Dict[Any, Any] = dict()
+ converted = False
+
+ # Work with recursive dictionaries: if a dictionary has already been
+ # converted, reuse its converted value to retain the recursive structure
+ # of the input.
+ if visited is None:
+ visited = {id(d): out}
+ elif id(d) in visited:
+ return visited[id(d)], False
+ visited[id(d)] = out
+
+ for key, value in d.items():
+ if isinstance(value, dict):
+ value, converted_value = _sanitize_numpy_keys(value, visited)
+ converted |= converted_value
+ if isinstance(key, np.generic):
+ key = _numpy_generic_convert(key)
+ converted = True
+ out[key] = value
+
+ return out, converted
+
+
+def json_friendly( # noqa: C901
+ obj: Any,
+) -> Union[Tuple[Any, bool], Tuple[Union[None, str, float], bool]]:
+ """Convert an object into something that's more becoming of JSON."""
+ converted = True
+ typename = get_full_typename(obj)
+
+ if is_tf_eager_tensor_typename(typename):
+ obj = obj.numpy()
+ elif is_tf_tensor_typename(typename):
+ try:
+ obj = obj.eval()
+ except RuntimeError:
+ obj = obj.numpy()
+ elif is_pytorch_tensor_typename(typename) or is_fastai_tensor_typename(typename):
+ try:
+ if obj.requires_grad:
+ obj = obj.detach()
+ except AttributeError:
+ pass # before 0.4 is only present on variables
+
+ try:
+ obj = obj.data
+ except RuntimeError:
+ pass # happens for Tensors before 0.4
+
+ if obj.size():
+ obj = obj.cpu().detach().numpy()
+ else:
+ return obj.item(), True
+ elif is_jax_tensor_typename(typename):
+ obj = get_jax_tensor(obj)
+
+ if is_numpy_array(obj):
+ if obj.size == 1:
+ obj = obj.flatten()[0]
+ elif obj.size <= 32:
+ obj = obj.tolist()
+ elif np and isinstance(obj, np.generic):
+ obj = _numpy_generic_convert(obj)
+ elif isinstance(obj, bytes):
+ obj = obj.decode("utf-8")
+ elif isinstance(obj, (datetime, date)):
+ obj = obj.isoformat()
+ elif callable(obj):
+ obj = (
+ f"{obj.__module__}.{obj.__qualname__}"
+ if hasattr(obj, "__qualname__") and hasattr(obj, "__module__")
+ else str(obj)
+ )
+ elif isinstance(obj, float) and math.isnan(obj):
+ obj = None
+ elif isinstance(obj, dict) and np:
+ obj, converted = _sanitize_numpy_keys(obj)
+ elif isinstance(obj, set):
+ # set is not json serializable, so we convert it to tuple
+ obj = tuple(obj)
+ elif isinstance(obj, enum.Enum):
+ obj = obj.name
+ else:
+ converted = False
+ if getsizeof(obj) > VALUE_BYTES_LIMIT:
+ wandb.termwarn(
+ f"Serializing object of type {type(obj).__name__} that is {getsizeof(obj)} bytes"
+ )
+ return obj, converted
+
+
+def json_friendly_val(val: Any) -> Any:
+ """Make any value (including dict, slice, sequence, dataclass) JSON friendly."""
+ converted: Union[dict, list]
+ if isinstance(val, dict):
+ converted = {}
+ for key, value in val.items():
+ converted[key] = json_friendly_val(value)
+ return converted
+ if isinstance(val, slice):
+ converted = dict(
+ slice_start=val.start, slice_step=val.step, slice_stop=val.stop
+ )
+ return converted
+ val, _ = json_friendly(val)
+ if isinstance(val, Sequence) and not isinstance(val, str):
+ converted = []
+ for value in val:
+ converted.append(json_friendly_val(value))
+ return converted
+ if is_dataclass(val) and not isinstance(val, type):
+ converted = asdict(val)
+ return json_friendly_val(converted)
+ else:
+ if val.__class__.__module__ not in ("builtins", "__builtin__"):
+ val = str(val)
+ return val
+
+
+def alias_is_version_index(alias: str) -> bool:
+ return len(alias) >= 2 and alias[0] == "v" and alias[1:].isnumeric()
+
+
+def convert_plots(obj: Any) -> Any:
+ if is_matplotlib_typename(get_full_typename(obj)):
+ tools = get_module(
+ "plotly.tools",
+ required=(
+ "plotly is required to log interactive plots, install with: "
+ "`pip install plotly` or convert the plot to an image with `wandb.Image(plt)`"
+ ),
+ )
+ obj = tools.mpl_to_plotly(obj)
+
+ if is_plotly_typename(get_full_typename(obj)):
+ return {"_type": "plotly", "plot": obj.to_plotly_json()}
+ else:
+ return obj
+
+
+def maybe_compress_history(obj: Any) -> Tuple[Any, bool]:
+ if np and isinstance(obj, np.ndarray) and obj.size > 32:
+ return wandb.Histogram(obj, num_bins=32).to_json(), True
+ else:
+ return obj, False
+
+
+def maybe_compress_summary(obj: Any, h5_typename: str) -> Tuple[Any, bool]:
+ if np and isinstance(obj, np.ndarray) and obj.size > 32:
+ return (
+ {
+ "_type": h5_typename, # may not be ndarray
+ "var": np.var(obj).item(),
+ "mean": np.mean(obj).item(),
+ "min": np.amin(obj).item(),
+ "max": np.amax(obj).item(),
+ "10%": np.percentile(obj, 10),
+ "25%": np.percentile(obj, 25),
+ "75%": np.percentile(obj, 75),
+ "90%": np.percentile(obj, 90),
+ "size": obj.size,
+ },
+ True,
+ )
+ else:
+ return obj, False
+
+
+def launch_browser(attempt_launch_browser: bool = True) -> bool:
+ """Decide if we should launch a browser."""
+ _display_variables = ["DISPLAY", "WAYLAND_DISPLAY", "MIR_SOCKET"]
+ _webbrowser_names_blocklist = ["www-browser", "lynx", "links", "elinks", "w3m"]
+
+ import webbrowser
+
+ launch_browser = attempt_launch_browser
+ if launch_browser:
+ if "linux" in sys.platform and not any(
+ os.getenv(var) for var in _display_variables
+ ):
+ launch_browser = False
+ try:
+ browser = webbrowser.get()
+ if hasattr(browser, "name") and browser.name in _webbrowser_names_blocklist:
+ launch_browser = False
+ except webbrowser.Error:
+ launch_browser = False
+
+ return launch_browser
+
+
+def generate_id(length: int = 8) -> str:
+ # Do not use this; use wandb.sdk.lib.runid.generate_id instead.
+ # This is kept only for legacy code.
+ return runid.generate_id(length)
+
+
+def parse_tfjob_config() -> Any:
+ """Attempt to parse TFJob config, returning False if it can't find it."""
+ if os.getenv("TF_CONFIG"):
+ try:
+ return json.loads(os.environ["TF_CONFIG"])
+ except ValueError:
+ return False
+ else:
+ return False
+
+
+class WandBJSONEncoder(json.JSONEncoder):
+ """A JSON Encoder that handles some extra types."""
+
+ def default(self, obj: Any) -> Any:
+ if hasattr(obj, "json_encode"):
+ return obj.json_encode()
+ # if hasattr(obj, 'to_json'):
+ # return obj.to_json()
+ tmp_obj, converted = json_friendly(obj)
+ if converted:
+ return tmp_obj
+ return json.JSONEncoder.default(self, obj)
+
+
+class WandBJSONEncoderOld(json.JSONEncoder):
+ """A JSON Encoder that handles some extra types."""
+
+ def default(self, obj: Any) -> Any:
+ tmp_obj, converted = json_friendly(obj)
+ tmp_obj, compressed = maybe_compress_summary(tmp_obj, get_h5_typename(obj))
+ if converted:
+ return tmp_obj
+ return json.JSONEncoder.default(self, tmp_obj)
+
+
+class WandBHistoryJSONEncoder(json.JSONEncoder):
+ """A JSON Encoder that handles some extra types.
+
+ This encoder turns numpy like objects with a size > 32 into histograms.
+ """
+
+ def default(self, obj: Any) -> Any:
+ obj, converted = json_friendly(obj)
+ obj, compressed = maybe_compress_history(obj)
+ if converted:
+ return obj
+ return json.JSONEncoder.default(self, obj)
+
+
+class JSONEncoderUncompressed(json.JSONEncoder):
+ """A JSON Encoder that handles some extra types.
+
+ This encoder turns numpy like objects with a size > 32 into histograms.
+ """
+
+ def default(self, obj: Any) -> Any:
+ if is_numpy_array(obj):
+ return obj.tolist()
+ elif np and isinstance(obj, np.number):
+ return obj.item()
+ elif np and isinstance(obj, np.generic):
+ obj = obj.item()
+ return json.JSONEncoder.default(self, obj)
+
+
+def json_dump_safer(obj: Any, fp: IO[str], **kwargs: Any) -> None:
+ """Convert obj to json, with some extra encodable types."""
+ return dump(obj, fp, cls=WandBJSONEncoder, **kwargs)
+
+
+def json_dumps_safer(obj: Any, **kwargs: Any) -> str:
+ """Convert obj to json, with some extra encodable types."""
+ return dumps(obj, cls=WandBJSONEncoder, **kwargs)
+
+
+# This is used for dumping raw json into files
+def json_dump_uncompressed(obj: Any, fp: IO[str], **kwargs: Any) -> None:
+ """Convert obj to json, with some extra encodable types."""
+ return dump(obj, fp, cls=JSONEncoderUncompressed, **kwargs)
+
+
+def json_dumps_safer_history(obj: Any, **kwargs: Any) -> str:
+ """Convert obj to json, with some extra encodable types, including histograms."""
+ return dumps(obj, cls=WandBHistoryJSONEncoder, **kwargs)
+
+
+def make_json_if_not_number(
+ v: Union[int, float, str, Mapping, Sequence],
+) -> Union[int, float, str]:
+ """If v is not a basic type convert it to json."""
+ if isinstance(v, (float, int)):
+ return v
+ return json_dumps_safer(v)
+
+
+def make_safe_for_json(obj: Any) -> Any:
+ """Replace invalid json floats with strings. Also converts to lists and dicts."""
+ if isinstance(obj, Mapping):
+ return {k: make_safe_for_json(v) for k, v in obj.items()}
+ elif isinstance(obj, str):
+ # str's are Sequence, so we need to short-circuit
+ return obj
+ elif isinstance(obj, Sequence):
+ return [make_safe_for_json(v) for v in obj]
+ elif isinstance(obj, float):
+ # W&B backend and UI handle these strings
+ if obj != obj: # standard way to check for NaN
+ return "NaN"
+ elif obj == float("+inf"):
+ return "Infinity"
+ elif obj == float("-inf"):
+ return "-Infinity"
+ return obj
+
+
+def no_retry_4xx(e: Exception) -> bool:
+ if not isinstance(e, requests.HTTPError):
+ return True
+ assert e.response is not None
+ if not (400 <= e.response.status_code < 500) or e.response.status_code == 429:
+ return True
+ body = json.loads(e.response.content)
+ raise UsageError(body["errors"][0]["message"])
+
+
+def parse_backend_error_messages(response: requests.Response) -> List[str]:
+ """Returns error messages stored in a backend response.
+
+ If the response is not in an expected format, an empty list is returned.
+
+ Args:
+ response: A response to an HTTP request to the W&B server.
+ """
+ try:
+ data = response.json()
+ except requests.JSONDecodeError:
+ return []
+
+ if not isinstance(data, dict):
+ return []
+
+ # Backend error values are returned in one of two ways:
+ # - A string containing the error message
+ # - A JSON object with a "message" field that is a string
+ def get_message(error: Any) -> Optional[str]:
+ if isinstance(error, str):
+ return error
+ elif (
+ isinstance(error, dict)
+ and (message := error.get("message"))
+ and isinstance(message, str)
+ ):
+ return message
+ else:
+ return None
+
+ # The response can contain an "error" field with a single error
+ # or an "errors" field with a list of errors.
+ if error := data.get("error"):
+ message = get_message(error)
+ return [message] if message else []
+
+ elif (errors := data.get("errors")) and isinstance(errors, list):
+ messages: List[str] = []
+ for error in errors:
+ message = get_message(error)
+ if message:
+ messages.append(message)
+ return messages
+
+ else:
+ return []
+
+
+def no_retry_auth(e: Any) -> bool:
+ if hasattr(e, "exception"):
+ e = e.exception
+ if not isinstance(e, requests.HTTPError):
+ return True
+ if e.response is None:
+ return True
+ # Don't retry bad request errors; raise immediately
+ if e.response.status_code in (400, 409):
+ return False
+ # Retry all non-forbidden/unauthorized/not-found errors.
+ if e.response.status_code not in (401, 403, 404):
+ return True
+
+ # Crash with more informational message on forbidden/unauthorized errors.
+ # UnauthorizedError
+ if e.response.status_code == 401:
+ raise AuthenticationError(
+ "The API key you provided is either invalid or missing. "
+ f"If the `{wandb.env.API_KEY}` environment variable is set, make sure it is correct. "
+ "Otherwise, to resolve this issue, you may try running the 'wandb login --relogin' command. "
+ "If you are using a local server, make sure that you're using the correct hostname. "
+ "If you're not sure, you can try logging in again using the 'wandb login --relogin --host [hostname]' command."
+ f"(Error {e.response.status_code}: {e.response.reason})"
+ )
+ # ForbiddenError
+ if e.response.status_code == 403:
+ if wandb.run:
+ raise CommError(f"Permission denied to access {wandb.run.path}")
+ else:
+ raise CommError(
+ "It appears that you do not have permission to access the requested resource. "
+ "Please reach out to the project owner to grant you access. "
+ "If you have the correct permissions, verify that there are no issues with your networking setup."
+ f"(Error {e.response.status_code}: {e.response.reason})"
+ )
+
+ # NotFoundError
+ if e.response.status_code == 404:
+ # If error message is empty, raise a more generic NotFoundError message.
+ if parse_backend_error_messages(e.response):
+ return False
+ else:
+ raise LookupError(
+ f"Failed to find resource. Please make sure you have the correct resource path. "
+ f"(Error {e.response.status_code}: {e.response.reason})"
+ )
+ return False
+
+
+def check_retry_conflict(e: Any) -> Optional[bool]:
+ """Check if the exception is a conflict type so it can be retried.
+
+ Returns:
+ True - Should retry this operation
+ False - Should not retry this operation
+ None - No decision, let someone else decide
+ """
+ if hasattr(e, "exception"):
+ e = e.exception
+ if isinstance(e, requests.HTTPError) and e.response is not None:
+ if e.response.status_code == 409:
+ return True
+ return None
+
+
+def check_retry_conflict_or_gone(e: Any) -> Optional[bool]:
+ """Check if the exception is a conflict or gone type, so it can be retried or not.
+
+ Returns:
+ True - Should retry this operation
+ False - Should not retry this operation
+ None - No decision, let someone else decide
+ """
+ if hasattr(e, "exception"):
+ e = e.exception
+ if isinstance(e, requests.HTTPError) and e.response is not None:
+ if e.response.status_code == 409:
+ return True
+ if e.response.status_code == 410:
+ return False
+ return None
+
+
+def make_check_retry_fn(
+ fallback_retry_fn: CheckRetryFnType,
+ check_fn: Callable[[Exception], Optional[bool]],
+ check_timedelta: Optional[timedelta] = None,
+) -> CheckRetryFnType:
+ """Return a check_retry_fn which can be used by lib.Retry().
+
+ Args:
+ fallback_fn: Use this function if check_fn didn't decide if a retry should happen.
+ check_fn: Function which returns bool if retry should happen or None if unsure.
+ check_timedelta: Optional retry timeout if we check_fn matches the exception
+ """
+
+ def check_retry_fn(e: Exception) -> Union[bool, timedelta]:
+ check = check_fn(e)
+ if check is None:
+ return fallback_retry_fn(e)
+ if check is False:
+ return False
+ if check_timedelta:
+ return check_timedelta
+ return True
+
+ return check_retry_fn
+
+
+def find_runner(program: str) -> Union[None, list, List[str]]:
+ """Return a command that will run program.
+
+ Args:
+ program: The string name of the program to try to run.
+
+ Returns:
+ commandline list of strings to run the program (eg. with subprocess.call()) or None
+ """
+ if os.path.isfile(program) and not os.access(program, os.X_OK):
+ # program is a path to a non-executable file
+ try:
+ opened = open(program)
+ except OSError: # PermissionError doesn't exist in 2.7
+ return None
+ first_line = opened.readline().strip()
+ if first_line.startswith("#!"):
+ return shlex.split(first_line[2:])
+ if program.endswith(".py"):
+ return [sys.executable]
+ return None
+
+
+def downsample(values: Sequence, target_length: int) -> list:
+ """Downsample 1d values to target_length, including start and end.
+
+ Algorithm just rounds index down.
+
+ Values can be any sequence, including a generator.
+ """
+ if not target_length > 1:
+ raise UsageError("target_length must be > 1")
+ values = list(values)
+ if len(values) < target_length:
+ return values
+ ratio = float(len(values) - 1) / (target_length - 1)
+ result = []
+ for i in range(target_length):
+ result.append(values[int(i * ratio)])
+ return result
+
+
+def has_num(dictionary: Mapping, key: Any) -> bool:
+ return key in dictionary and isinstance(dictionary[key], numbers.Number)
+
+
+def docker_image_regex(image: str) -> Any:
+ """Regex match for valid docker image names."""
+ if image:
+ return re.match(
+ r"^(?:(?=[^:\/]{1,253})(?!-)[a-zA-Z0-9-]{1,63}(? Optional[str]:
+ """Scan docker run args and attempt to find the most likely docker image argument.
+
+ It excludes any arguments that start with a dash, and the argument after it if it
+ isn't a boolean switch. This can be improved, we currently fallback gracefully when
+ this fails.
+ """
+ bool_args = [
+ "-t",
+ "--tty",
+ "--rm",
+ "--privileged",
+ "--oom-kill-disable",
+ "--no-healthcheck",
+ "-i",
+ "--interactive",
+ "--init",
+ "--help",
+ "--detach",
+ "-d",
+ "--sig-proxy",
+ "-it",
+ "-itd",
+ ]
+ last_flag = -2
+ last_arg = ""
+ possible_images = []
+ if len(args) > 0 and args[0] == "run":
+ args.pop(0)
+ for i, arg in enumerate(args):
+ if arg.startswith("-"):
+ last_flag = i
+ last_arg = arg
+ elif "@sha256:" in arg:
+ # Because our regex doesn't match digests
+ possible_images.append(arg)
+ elif docker_image_regex(arg):
+ if last_flag == i - 2:
+ possible_images.append(arg)
+ elif "=" in last_arg:
+ possible_images.append(arg)
+ elif last_arg in bool_args and last_flag == i - 1:
+ possible_images.append(arg)
+ most_likely = None
+ for img in possible_images:
+ if ":" in img or "@" in img or "/" in img:
+ most_likely = img
+ break
+ if most_likely is None and len(possible_images) > 0:
+ most_likely = possible_images[0]
+ return most_likely
+
+
+def load_yaml(file: Any) -> Any:
+ return yaml.safe_load(file)
+
+
+def image_id_from_k8s() -> Optional[str]:
+ """Ping the k8s metadata service for the image id.
+
+ Specify the KUBERNETES_NAMESPACE environment variable if your pods are not in the
+ default namespace:
+
+ - name: KUBERNETES_NAMESPACE valueFrom:
+ fieldRef:
+ fieldPath: metadata.namespace
+ """
+ token_path = "/var/run/secrets/kubernetes.io/serviceaccount/token"
+
+ if not os.path.exists(token_path):
+ return None
+
+ try:
+ with open(token_path) as token_file:
+ token = token_file.read()
+ except FileNotFoundError:
+ logger.warning(f"Token file not found at {token_path}.")
+ return None
+ except PermissionError as e:
+ current_uid = os.getuid()
+ warning = (
+ f"Unable to read the token file at {token_path} due to permission error ({e})."
+ f"The current user id is {current_uid}. "
+ "Consider changing the securityContext to run the container as the current user."
+ )
+ logger.warning(warning)
+ wandb.termwarn(warning)
+ return None
+
+ if not token:
+ return None
+
+ k8s_server = "https://{}:{}/api/v1/namespaces/{}/pods/{}".format(
+ os.getenv("KUBERNETES_SERVICE_HOST"),
+ os.getenv("KUBERNETES_PORT_443_TCP_PORT"),
+ os.getenv("KUBERNETES_NAMESPACE", "default"),
+ os.getenv("HOSTNAME"),
+ )
+ try:
+ res = requests.get(
+ k8s_server,
+ verify="/var/run/secrets/kubernetes.io/serviceaccount/ca.crt",
+ timeout=3,
+ headers={"Authorization": f"Bearer {token}"},
+ )
+ res.raise_for_status()
+ except requests.RequestException:
+ return None
+ try:
+ return str( # noqa: B005
+ res.json()["status"]["containerStatuses"][0]["imageID"]
+ ).strip("docker-pullable://")
+ except (ValueError, KeyError, IndexError):
+ logger.exception("Error checking kubernetes for image id")
+ return None
+
+
+def async_call(
+ target: Callable, timeout: Optional[Union[int, float]] = None
+) -> Callable:
+ """Wrap a method to run in the background with an optional timeout.
+
+ Returns a new method that will call the original with any args, waiting for upto
+ timeout seconds. This new method blocks on the original and returns the result or
+ None if timeout was reached, along with the thread. You can check thread.is_alive()
+ to determine if a timeout was reached. If an exception is thrown in the thread, we
+ reraise it.
+ """
+ q: queue.Queue = queue.Queue()
+
+ def wrapped_target(q: "queue.Queue", *args: Any, **kwargs: Any) -> Any:
+ try:
+ q.put(target(*args, **kwargs))
+ except Exception as e:
+ q.put(e)
+
+ def wrapper(
+ *args: Any, **kwargs: Any
+ ) -> Union[Tuple[Exception, "threading.Thread"], Tuple[None, "threading.Thread"]]:
+ thread = threading.Thread(
+ target=wrapped_target, args=(q,) + args, kwargs=kwargs
+ )
+ thread.daemon = True
+ thread.start()
+
+ try:
+ result = q.get(True, timeout)
+ except queue.Empty:
+ return None, thread
+
+ if isinstance(result, Exception):
+ raise result.with_traceback(sys.exc_info()[2])
+ return result, thread
+
+ return wrapper
+
+
+def read_many_from_queue(
+ q: "queue.Queue", max_items: int, queue_timeout: Union[int, float]
+) -> list:
+ try:
+ item = q.get(True, queue_timeout)
+ except queue.Empty:
+ return []
+ items = [item]
+ for _ in range(max_items):
+ try:
+ item = q.get_nowait()
+ except queue.Empty:
+ return items
+ items.append(item)
+ return items
+
+
+def stopwatch_now() -> float:
+ """Get a time value for interval comparisons.
+
+ When possible it is a monotonic clock to prevent backwards time issues.
+ """
+ return time.monotonic()
+
+
+def class_colors(class_count: int) -> List[List[int]]:
+ # make class 0 black, and the rest equally spaced fully saturated hues
+ return [[0, 0, 0]] + [
+ colorsys.hsv_to_rgb(i / (class_count - 1.0), 1.0, 1.0) # type: ignore
+ for i in range(class_count - 1)
+ ]
+
+
+def _prompt_choice(
+ input_timeout: Union[int, float, None] = None,
+ jupyter: bool = False,
+) -> str:
+ input_fn: Callable = input
+ prompt = term.LOG_STRING
+ if input_timeout is not None:
+ # delayed import to mitigate risk of timed_input complexity
+ from wandb.sdk.lib import timed_input
+
+ input_fn = functools.partial(timed_input.timed_input, timeout=input_timeout)
+ # timed_input doesn't handle enhanced prompts
+ if platform.system() == "Windows":
+ prompt = "wandb"
+
+ text = f"{prompt}: Enter your choice: "
+ if input_fn == input:
+ choice = input_fn(text)
+ else:
+ choice = input_fn(text, jupyter=jupyter)
+ return choice # type: ignore
+
+
+def prompt_choices(
+ choices: Sequence[str],
+ input_timeout: Union[int, float, None] = None,
+ jupyter: bool = False,
+) -> str:
+ """Allow a user to choose from a list of options."""
+ for i, choice in enumerate(choices):
+ wandb.termlog(f"({i + 1}) {choice}")
+
+ idx = -1
+ while idx < 0 or idx > len(choices) - 1:
+ choice = _prompt_choice(input_timeout=input_timeout, jupyter=jupyter)
+ if not choice:
+ continue
+ idx = -1
+ try:
+ idx = int(choice) - 1
+ except ValueError:
+ pass
+ if idx < 0 or idx > len(choices) - 1:
+ wandb.termwarn("Invalid choice")
+ result = choices[idx]
+ wandb.termlog(f"You chose {result!r}")
+ return result
+
+
+def guess_data_type(shape: Sequence[int], risky: bool = False) -> Optional[str]:
+ """Infer the type of data based on the shape of the tensors.
+
+ Args:
+ shape (Sequence[int]): The shape of the data
+ risky(bool): some guesses are more likely to be wrong.
+ """
+ # (samples,) or (samples,logits)
+ if len(shape) in (1, 2):
+ return "label"
+ # Assume image mask like fashion mnist: (no color channel)
+ # This is risky because RNNs often have 3 dim tensors: batch, time, channels
+ if risky and len(shape) == 3:
+ return "image"
+ if len(shape) == 4:
+ if shape[-1] in (1, 3, 4):
+ # (samples, height, width, Y \ RGB \ RGBA)
+ return "image"
+ else:
+ # (samples, height, width, logits)
+ return "segmentation_mask"
+ return None
+
+
+def download_file_from_url(
+ dest_path: str, source_url: str, api_key: Optional[str] = None
+) -> None:
+ auth = None
+ if not _thread_local_api_settings.cookies:
+ auth = ("api", api_key or "")
+ response = requests.get(
+ source_url,
+ auth=auth,
+ headers=_thread_local_api_settings.headers,
+ cookies=_thread_local_api_settings.cookies,
+ stream=True,
+ timeout=5,
+ )
+ response.raise_for_status()
+
+ if os.sep in dest_path:
+ filesystem.mkdir_exists_ok(os.path.dirname(dest_path))
+ with fsync_open(dest_path, "wb") as file:
+ for data in response.iter_content(chunk_size=1024):
+ file.write(data)
+
+
+def download_file_into_memory(source_url: str, api_key: Optional[str] = None) -> bytes:
+ auth = None
+ if not _thread_local_api_settings.cookies:
+ auth = ("api", api_key or "")
+ response = requests.get(
+ source_url,
+ auth=auth,
+ headers=_thread_local_api_settings.headers,
+ cookies=_thread_local_api_settings.cookies,
+ stream=True,
+ timeout=5,
+ )
+ response.raise_for_status()
+ return response.content
+
+
+def isatty(ob: IO) -> bool:
+ return hasattr(ob, "isatty") and ob.isatty()
+
+
+def to_human_size(size: int, units: Optional[List[Tuple[str, Any]]] = None) -> str:
+ units = units or POW_10_BYTES
+ unit, value = units[0]
+ factor = round(float(size) / value, 1)
+ return (
+ f"{factor}{unit}"
+ if factor < 1024 or len(units) == 1
+ else to_human_size(size, units[1:])
+ )
+
+
+def from_human_size(size: str, units: Optional[List[Tuple[str, Any]]] = None) -> int:
+ units = units or POW_10_BYTES
+ units_dict = {unit.upper(): value for (unit, value) in units}
+ regex = re.compile(
+ r"(\d+\.?\d*)\s*({})?".format("|".join(units_dict.keys())), re.IGNORECASE
+ )
+ match = re.match(regex, size)
+ if not match:
+ raise ValueError("size must be of the form `10`, `10B` or `10 B`.")
+ factor, unit = (
+ float(match.group(1)),
+ units_dict[match.group(2).upper()] if match.group(2) else 1,
+ )
+ return int(factor * unit)
+
+
+def auto_project_name(program: Optional[str]) -> str:
+ # if we're in git, set project name to git repo name + relative path within repo
+ from wandb.sdk.lib.gitlib import GitRepo
+
+ root_dir = GitRepo().root_dir
+ if root_dir is None:
+ return "uncategorized"
+ # On windows, GitRepo returns paths in unix style, but os.path is windows
+ # style. Coerce here.
+ root_dir = to_native_slash_path(root_dir)
+ repo_name = os.path.basename(root_dir)
+ if program is None:
+ return str(repo_name)
+ if not os.path.isabs(program):
+ program = os.path.join(os.curdir, program)
+ prog_dir = os.path.dirname(os.path.abspath(program))
+ if not prog_dir.startswith(root_dir):
+ return str(repo_name)
+ project = repo_name
+ sub_path = os.path.relpath(prog_dir, root_dir)
+ if sub_path != ".":
+ project += "-" + sub_path
+ return str(project.replace(os.sep, "_"))
+
+
+def are_paths_on_same_drive(path1: str, path2: str) -> bool:
+ """Check if two paths are on the same drive.
+
+ This check is only relevant on Windows,
+ since the concept of drives only exists on Windows.
+ """
+ if platform.system() != "Windows":
+ return True
+
+ try:
+ path1_drive = pathlib.Path(path1).resolve().drive
+ path2_drive = pathlib.Path(path2).resolve().drive
+ except OSError:
+ # If either path is not a valid Windows path, an OSError is raised.
+ return False
+
+ return path1_drive == path2_drive
+
+
+# TODO(hugh): Deprecate version here and use wandb/sdk/lib/paths.py
+def to_forward_slash_path(path: str) -> str:
+ if platform.system() == "Windows":
+ path = path.replace("\\", "/")
+ return path
+
+
+# TODO(hugh): Deprecate version here and use wandb/sdk/lib/paths.py
+def to_native_slash_path(path: str) -> FilePathStr:
+ return FilePathStr(path.replace("/", os.sep))
+
+
+def check_and_warn_old(files: List[str]) -> bool:
+ if "wandb-metadata.json" in files:
+ wandb.termwarn("These runs were logged with a previous version of wandb.")
+ wandb.termwarn(
+ "Run pip install wandb<0.10.0 to get the old library and sync your runs."
+ )
+ return True
+ return False
+
+
+class ImportMetaHook:
+ def __init__(self) -> None:
+ self.modules: Dict[str, ModuleType] = dict()
+ self.on_import: Dict[str, list] = dict()
+
+ def add(self, fullname: str, on_import: Callable) -> None:
+ self.on_import.setdefault(fullname, []).append(on_import)
+
+ def install(self) -> None:
+ sys.meta_path.insert(0, self) # type: ignore
+
+ def uninstall(self) -> None:
+ sys.meta_path.remove(self) # type: ignore
+
+ def find_module(
+ self, fullname: str, path: Optional[str] = None
+ ) -> Optional["ImportMetaHook"]:
+ if fullname in self.on_import:
+ return self
+ return None
+
+ def load_module(self, fullname: str) -> ModuleType:
+ self.uninstall()
+ mod = importlib.import_module(fullname)
+ self.install()
+ self.modules[fullname] = mod
+ on_imports = self.on_import.get(fullname)
+ if on_imports:
+ for f in on_imports:
+ f()
+ return mod
+
+ def get_modules(self) -> Tuple[str, ...]:
+ return tuple(self.modules)
+
+ def get_module(self, module: str) -> ModuleType:
+ return self.modules[module]
+
+
+_import_hook: Optional[ImportMetaHook] = None
+
+
+def add_import_hook(fullname: str, on_import: Callable) -> None:
+ global _import_hook
+ if _import_hook is None:
+ _import_hook = ImportMetaHook()
+ _import_hook.install()
+ _import_hook.add(fullname, on_import)
+
+
+def host_from_path(path: Optional[str]) -> str:
+ """Return the host of the path."""
+ url = urllib.parse.urlparse(path)
+ return str(url.netloc)
+
+
+def uri_from_path(path: Optional[str]) -> str:
+ """Return the URI of the path."""
+ url = urllib.parse.urlparse(path)
+ uri = url.path if url.path[0] != "/" else url.path[1:]
+ return str(uri)
+
+
+def is_unicode_safe(stream: TextIO) -> bool:
+ """Return True if the stream supports UTF-8."""
+ encoding = getattr(stream, "encoding", None)
+ return encoding.lower() in {"utf-8", "utf_8"} if encoding else False
+
+
+def _has_internet() -> bool:
+ """Returns whether we have internet access.
+
+ Checks for internet access by attempting to open a DNS connection to
+ Google's root servers.
+ """
+ try:
+ s = socket.create_connection(("8.8.8.8", 53), 0.5)
+ s.close()
+ except OSError:
+ return False
+
+ return True
+
+
+def rand_alphanumeric(
+ length: int = 8, rand: Optional[Union[ModuleType, random.Random]] = None
+) -> str:
+ wandb.termerror("rand_alphanumeric is deprecated, use 'secrets.token_hex'")
+ rand = rand or random
+ return "".join(rand.choice("0123456789ABCDEF") for _ in range(length))
+
+
+@contextlib.contextmanager
+def fsync_open(
+ path: StrPath, mode: str = "w", encoding: Optional[str] = None
+) -> Generator[IO[Any], None, None]:
+ """Open a path for I/O and guarantee that the file is flushed and synced."""
+ with open(path, mode, encoding=encoding) as f:
+ yield f
+
+ f.flush()
+ os.fsync(f.fileno())
+
+
+def _is_kaggle() -> bool:
+ return (
+ os.getenv("KAGGLE_KERNEL_RUN_TYPE") is not None
+ or "kaggle_environments" in sys.modules
+ )
+
+
+def _is_likely_kaggle() -> bool:
+ # Telemetry to mark first runs from Kagglers.
+ return (
+ _is_kaggle()
+ or os.path.exists(
+ os.path.expanduser(os.path.join("~", ".kaggle", "kaggle.json"))
+ )
+ or "kaggle" in sys.modules
+ )
+
+
+def _is_databricks() -> bool:
+ # check if we are running inside a databricks notebook by
+ # inspecting sys.modules, searching for dbutils and verifying that
+ # it has the appropriate structure
+
+ if "dbutils" in sys.modules:
+ dbutils = sys.modules["dbutils"]
+ if hasattr(dbutils, "shell"):
+ shell = dbutils.shell
+ if hasattr(shell, "sc"):
+ sc = shell.sc
+ if hasattr(sc, "appName"):
+ return bool(sc.appName == "Databricks Shell")
+ return False
+
+
+def _is_py_requirements_or_dockerfile(path: str) -> bool:
+ file = os.path.basename(path)
+ return (
+ file.endswith(".py")
+ or file.startswith("Dockerfile")
+ or file == "requirements.txt"
+ )
+
+
+def artifact_to_json(artifact: "Artifact") -> Dict[str, Any]:
+ return {
+ "_type": "artifactVersion",
+ "_version": "v0",
+ "id": artifact.id,
+ "version": artifact.source_version,
+ "sequenceName": artifact.source_name.split(":")[0],
+ "usedAs": artifact.use_as,
+ }
+
+
+def check_dict_contains_nested_artifact(d: dict, nested: bool = False) -> bool:
+ for item in d.values():
+ if isinstance(item, dict):
+ contains_artifacts = check_dict_contains_nested_artifact(item, True)
+ if contains_artifacts:
+ return True
+ elif (isinstance(item, wandb.Artifact) or _is_artifact_string(item)) and nested:
+ return True
+ return False
+
+
+def load_json_yaml_dict(config: str) -> Any:
+ ext = os.path.splitext(config)[-1]
+ if ext == ".json":
+ with open(config) as f:
+ return json.load(f)
+ elif ext == ".yaml":
+ with open(config) as f:
+ return yaml.safe_load(f)
+ else:
+ try:
+ return json.loads(config)
+ except ValueError:
+ return None
+
+
+def _parse_entity_project_item(path: str) -> tuple:
+ """Parse paths with the following formats: {item}, {project}/{item}, & {entity}/{project}/{item}.
+
+ Args:
+ path: `str`, input path; must be between 0 and 3 in length.
+
+ Returns:
+ tuple of length 3 - (item, project, entity)
+
+ Example:
+ alias, project, entity = _parse_entity_project_item("myproj/mymodel:best")
+
+ assert entity == ""
+ assert project == "myproj"
+ assert alias == "mymodel:best"
+
+ """
+ words = path.split("/")
+ if len(words) > 3:
+ raise ValueError(
+ "Invalid path: must be str the form {item}, {project}/{item}, or {entity}/{project}/{item}"
+ )
+ padded_words = [""] * (3 - len(words)) + words
+ return tuple(reversed(padded_words))
+
+
+def _resolve_aliases(aliases: Optional[Union[str, Iterable[str]]]) -> List[str]:
+ """Add the 'latest' alias and ensure that all aliases are unique.
+
+ Takes in `aliases` which can be None, str, or List[str] and returns List[str].
+ Ensures that "latest" is always present in the returned list.
+
+ Args:
+ aliases: `Optional[Union[str, List[str]]]`
+
+ Returns:
+ List[str], with "latest" always present.
+
+ Usage:
+
+ ```python
+ aliases = _resolve_aliases(["best", "dev"])
+ assert aliases == ["best", "dev", "latest"]
+
+ aliases = _resolve_aliases("boom")
+ assert aliases == ["boom", "latest"]
+ ```
+ """
+ aliases = aliases or ["latest"]
+
+ if isinstance(aliases, str):
+ aliases = [aliases]
+
+ try:
+ return list(set(aliases) | {"latest"})
+ except TypeError as exc:
+ raise ValueError("`aliases` must be Iterable or None") from exc
+
+
+def _is_artifact_object(v: Any) -> "TypeGuard[wandb.Artifact]":
+ return isinstance(v, wandb.Artifact)
+
+
+def _is_artifact_string(v: Any) -> "TypeGuard[str]":
+ return isinstance(v, str) and v.startswith("wandb-artifact://")
+
+
+def _is_artifact_version_weave_dict(v: Any) -> "TypeGuard[dict]":
+ return isinstance(v, dict) and v.get("_type") == "artifactVersion"
+
+
+def _is_artifact_representation(v: Any) -> bool:
+ return (
+ _is_artifact_object(v)
+ or _is_artifact_string(v)
+ or _is_artifact_version_weave_dict(v)
+ )
+
+
+def parse_artifact_string(v: str) -> Tuple[str, Optional[str], bool]:
+ if not v.startswith("wandb-artifact://"):
+ raise ValueError(f"Invalid artifact string: {v}")
+ parsed_v = v[len("wandb-artifact://") :]
+ base_uri = None
+ url_info = urllib.parse.urlparse(parsed_v)
+ if url_info.scheme != "":
+ base_uri = f"{url_info.scheme}://{url_info.netloc}"
+ parts = url_info.path.split("/")[1:]
+ else:
+ parts = parsed_v.split("/")
+ if parts[0] == "_id":
+ # for now can't fetch paths but this will be supported in the future
+ # when we allow passing typed media objects, this can be extended
+ # to include paths
+ return parts[1], base_uri, True
+
+ if len(parts) < 3:
+ raise ValueError(f"Invalid artifact string: {v}")
+
+ # for now can't fetch paths but this will be supported in the future
+ # when we allow passing typed media objects, this can be extended
+ # to include paths
+ entity, project, name_and_alias_or_version = parts[:3]
+ return f"{entity}/{project}/{name_and_alias_or_version}", base_uri, False
+
+
+def _get_max_cli_version() -> Union[str, None]:
+ max_cli_version = wandb.api.max_cli_version()
+ return str(max_cli_version) if max_cli_version is not None else None
+
+
+def ensure_text(
+ string: Union[str, bytes], encoding: str = "utf-8", errors: str = "strict"
+) -> str:
+ """Coerce s to str."""
+ if isinstance(string, bytes):
+ return string.decode(encoding, errors)
+ elif isinstance(string, str):
+ return string
+ else:
+ raise TypeError(f"not expecting type {type(string)!r}")
+
+
+def make_artifact_name_safe(name: str) -> str:
+ """Make an artifact name safe for use in artifacts."""
+ # artifact names may only contain alphanumeric characters, dashes, underscores, and dots.
+ cleaned = re.sub(r"[^a-zA-Z0-9_\-.]", "_", name)
+ if len(cleaned) <= 128:
+ return cleaned
+ # truncate with dots in the middle using regex
+ return re.sub(r"(^.{63}).*(.{63}$)", r"\g<1>..\g<2>", cleaned)
+
+
+def make_docker_image_name_safe(name: str) -> str:
+ """Make a docker image name safe for use in artifacts."""
+ safe_chars = RE_DOCKER_IMAGE_NAME_CHARS.sub("__", name.lower())
+ deduped = RE_DOCKER_IMAGE_NAME_SEPARATOR_REPEAT.sub("__", safe_chars)
+ trimmed_start = RE_DOCKER_IMAGE_NAME_SEPARATOR_START.sub("", deduped)
+ trimmed = RE_DOCKER_IMAGE_NAME_SEPARATOR_END.sub("", trimmed_start)
+ return trimmed if trimmed else "image"
+
+
+def merge_dicts(
+ source: Dict[str, Any],
+ destination: Dict[str, Any],
+) -> Dict[str, Any]:
+ """Recursively merge two dictionaries.
+
+ This mutates the destination and its nested dictionaries and lists.
+
+ Instances of `dict` are recursively merged and instances of `list`
+ are appended to the destination. If the destination type is not
+ `dict` or `list`, respectively, the key is overwritten with the
+ source value.
+
+ For all other types, the source value overwrites the destination value.
+ """
+ for key, value in source.items():
+ if isinstance(value, dict):
+ node = destination.get(key)
+ if isinstance(node, dict):
+ merge_dicts(value, node)
+ else:
+ destination[key] = value
+
+ elif isinstance(value, list):
+ dest_value = destination.get(key)
+ if isinstance(dest_value, list):
+ dest_value.extend(value)
+ else:
+ destination[key] = value
+
+ else:
+ destination[key] = value
+
+ return destination
+
+
+def coalesce(*arg: Any) -> Any:
+ """Return the first non-none value in the list of arguments.
+
+ Similar to ?? in C#.
+ """
+ return next((a for a in arg if a is not None), None)
+
+
+def recursive_cast_dictlike_to_dict(d: Dict[str, Any]) -> Dict[str, Any]:
+ for k, v in d.items():
+ if isinstance(v, dict):
+ recursive_cast_dictlike_to_dict(v)
+ elif hasattr(v, "keys"):
+ d[k] = dict(v)
+ recursive_cast_dictlike_to_dict(d[k])
+ return d
+
+
+def remove_keys_with_none_values(
+ d: Union[Dict[str, Any], Any],
+) -> Union[Dict[str, Any], Any]:
+ # otherwise iterrows will create a bunch of ugly charts
+ if not isinstance(d, dict):
+ return d
+
+ if isinstance(d, dict):
+ new_dict = {}
+ for k, v in d.items():
+ new_v = remove_keys_with_none_values(v)
+ if new_v is not None and not (isinstance(new_v, dict) and len(new_v) == 0):
+ new_dict[k] = new_v
+ return new_dict if new_dict else None
+
+
+def batched(n: int, iterable: Iterable[T]) -> Generator[List[T], None, None]:
+ i = iter(iterable)
+ batch = list(itertools.islice(i, n))
+ while batch:
+ yield batch
+ batch = list(itertools.islice(i, n))
+
+
+def random_string(length: int = 12) -> str:
+ """Generate a random string of a given length.
+
+ :param length: Length of the string to generate.
+ :return: Random string.
+ """
+ return "".join(
+ secrets.choice(string.ascii_lowercase + string.digits) for _ in range(length)
+ )
+
+
+def sample_with_exponential_decay_weights(
+ xs: Union[Iterable, Iterable[Iterable]],
+ ys: Iterable[Iterable],
+ keys: Optional[Iterable] = None,
+ sample_size: int = 1500,
+) -> Tuple[List, List, Optional[List]]:
+ """Sample from a list of lists with weights that decay exponentially.
+
+ May be used with the wandb.plot.line_series function.
+ """
+ xs_array = np.array(xs)
+ ys_array = np.array(ys)
+ keys_array = np.array(keys) if keys else None
+ weights = np.exp(-np.arange(len(xs_array)) / len(xs_array))
+ weights /= np.sum(weights)
+ sampled_indices = np.random.choice(len(xs_array), size=sample_size, p=weights)
+ sampled_xs = xs_array[sampled_indices].tolist()
+ sampled_ys = ys_array[sampled_indices].tolist()
+ sampled_keys = keys_array[sampled_indices].tolist() if keys_array else None
+
+ return sampled_xs, sampled_ys, sampled_keys
+
+
+@dataclasses.dataclass(frozen=True)
+class InstalledDistribution:
+ """An installed distribution.
+
+ Attributes:
+ key: The distribution name as it would be imported.
+ version: The distribution's version string.
+ """
+
+ key: str
+ version: str
+
+
+def working_set() -> Iterable[InstalledDistribution]:
+ """Return the working set of installed distributions."""
+ from importlib.metadata import distributions
+
+ for d in distributions():
+ try:
+ # In some distributions, the "Name" attribute may not be present,
+ # which can raise a KeyError. To handle this, we catch the exception
+ # and skip those distributions.
+ # For additional context, see: https://github.com/python/importlib_metadata/issues/371.
+
+ # From Sentry events we observed that UnicodeDecodeError can occur when
+ # trying to decode the metadata of a distribution. To handle this, we catch
+ # the exception and skip those distributions.
+ yield InstalledDistribution(key=d.metadata["Name"], version=d.version)
+ except (KeyError, UnicodeDecodeError):
+ pass
+
+
+def get_core_path() -> str:
+ """Returns the path to the wandb-core binary.
+
+ The path can be set explicitly via the _WANDB_CORE_PATH environment
+ variable. Otherwise, the path to the binary in the current package
+ is returned.
+
+ Returns:
+ str: The path to the wandb-core package.
+
+ Raises:
+ WandbCoreNotAvailableError: If wandb-core was not built for the current system.
+ """
+ # NOTE: Environment variable _WANDB_CORE_PATH is a temporary development feature
+ # to assist in running the core service from a live development directory.
+ path_from_env: str = os.environ.get("_WANDB_CORE_PATH", "")
+ if path_from_env:
+ wandb.termwarn(
+ f"Using wandb-core from path `_WANDB_CORE_PATH={path_from_env}`. "
+ "This is a development feature and may not work as expected."
+ )
+ return path_from_env
+
+ bin_path = pathlib.Path(__file__).parent / "bin" / "wandb-core"
+ if not bin_path.exists():
+ raise WandbCoreNotAvailableError(
+ f"File not found: {bin_path}."
+ " Please contact support at support@wandb.com."
+ f" Your platform is: {platform.platform()}."
+ )
+
+ return str(bin_path)
+
+
+class NonOctalStringDumper(yaml.Dumper):
+ """Prevents strings containing non-octal values like "008" and "009" from being converted to numbers in in the yaml string saved as the sweep config."""
+
+ def represent_scalar(self, tag, value, style=None):
+ if tag == "tag:yaml.org,2002:str" and value.startswith("0") and len(value) > 1:
+ return super().represent_scalar(tag, value, style="'")
+ return super().represent_scalar(tag, value, style)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/wandb_agent.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/wandb_agent.py
new file mode 100644
index 0000000000000000000000000000000000000000..30819c702f8e3b81165adb92b9db3ca3612aac39
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/wandb_agent.py
@@ -0,0 +1,611 @@
+import logging
+import multiprocessing
+import os
+import platform
+import queue
+import re
+import signal
+import socket
+import subprocess
+import sys
+import time
+import traceback
+from typing import Any, Callable, Dict, List, Optional
+
+import yaml
+
+import wandb
+from wandb import util, wandb_lib, wandb_sdk
+from wandb.agents.pyagent import pyagent
+from wandb.apis import InternalApi
+from wandb.sdk.launch.sweeps import utils as sweep_utils
+from wandb.sdk.lib import ipython
+
+logger = logging.getLogger(__name__)
+
+
+class AgentError(Exception):
+ pass
+
+
+class AgentProcess:
+ """Launch and manage a process."""
+
+ def __init__(
+ self, env=None, command=None, function=None, run_id=None, in_jupyter=None
+ ):
+ self._popen = None
+ self._proc = None
+ self._finished_q = multiprocessing.Queue()
+ self._proc_killed = False
+
+ if command:
+ if platform.system() == "Windows":
+ kwargs = dict(creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
+ env.pop(wandb.env.SERVICE, None)
+ # TODO: Determine if we need the same stdin workaround as POSIX case below.
+ self._popen = subprocess.Popen(command, env=env, **kwargs)
+ else:
+ if sys.version_info >= (3, 11):
+ # preexec_fn=os.setpgrp is not thread-safe; process_group was introduced in
+ # python 3.11 to replace it, so use that when possible
+ kwargs = dict(process_group=0)
+ else:
+ kwargs = dict(preexec_fn=os.setpgrp)
+ env.pop(wandb.env.SERVICE, None)
+ # Upon spawning the subprocess in a new process group, the child's process group is
+ # not connected to the controlling terminal's stdin. If it tries to access stdin,
+ # it gets a SIGTTIN and blocks until we give it the terminal, which we don't want
+ # to do.
+ #
+ # By using subprocess.PIPE, we give it an independent stdin. However, it will still
+ # block if it tries to read from stdin, because we're not writing anything to it.
+ # We immediately close the subprocess's stdin here so it can fail fast and get an
+ # EOF.
+ #
+ # (One situation that makes this relevant is that importing `readline` even
+ # indirectly can cause the child to attempt to access stdin, which can trigger the
+ # deadlock. In Python 3.13, `import torch` indirectly imports `readline` via `pdb`,
+ # meaning `import torch` in a run script can deadlock unless we override stdin.
+ # See https://github.com/wandb/wandb/pull/10489 description for more details.)
+ #
+ # Also, we avoid spawning a new session because that breaks preempted child process
+ # handling.
+ self._popen = subprocess.Popen(
+ command,
+ env=env,
+ stdin=subprocess.PIPE,
+ **kwargs,
+ )
+ self._popen.stdin.close()
+ elif function:
+ self._proc = multiprocessing.Process(
+ target=self._start,
+ args=(self._finished_q, env, function, run_id, in_jupyter),
+ )
+ self._proc.start()
+ else:
+ raise AgentError("Agent Process requires command or function")
+
+ def _start(self, finished_q, env, function, run_id, in_jupyter):
+ if env:
+ for k, v in env.items():
+ os.environ[k] = v
+
+ # call user function
+ wandb.termlog(f"Agent Started Run: {run_id}")
+ if function:
+ function()
+ wandb.termlog(f"Agent Finished Run: {run_id}\n")
+
+ # complete the run
+ run = wandb.run
+ if run:
+ wandb.join()
+
+ # signal that the process is finished
+ finished_q.put(True)
+
+ def poll(self):
+ if self._popen:
+ return self._popen.poll()
+ if self._proc_killed:
+ # we need to join process to prevent zombies
+ self._proc.join()
+ return True
+ try:
+ finished = self._finished_q.get(False, 0)
+ if finished:
+ return True
+ except queue.Empty:
+ pass
+ return
+
+ def wait(self):
+ if self._popen:
+ # if on windows, wait() will block and we won't be able to interrupt
+ if platform.system() == "Windows":
+ while True:
+ p = self._popen.poll()
+ if p is not None:
+ return p
+ time.sleep(1)
+ return self._popen.wait()
+ return self._proc.join()
+
+ def kill(self):
+ if self._popen:
+ return self._popen.kill()
+ pid = self._proc.pid
+ if pid:
+ ret = os.kill(pid, signal.SIGKILL)
+ self._proc_killed = True
+ return ret
+ return
+
+ def terminate(self):
+ if self._popen:
+ # windows terminate is too strong, send Ctrl-C instead
+ if platform.system() == "Windows":
+ return self._popen.send_signal(signal.CTRL_C_EVENT)
+ return self._popen.terminate()
+ return self._proc.terminate()
+
+
+class Agent:
+ POLL_INTERVAL = 5
+ REPORT_INTERVAL = 0
+ KILL_DELAY = 30
+ FLAPPING_MAX_SECONDS = 60
+ FLAPPING_MAX_FAILURES = 3
+ MAX_INITIAL_FAILURES = 5
+ DEFAULT_SWEEP_COMMAND: List[str] = [
+ "${env}",
+ "${interpreter}",
+ "${program}",
+ "${args}",
+ ]
+ SWEEP_COMMAND_ENV_VAR_REGEX = re.compile(r"\$\{envvar\:([A-Z0-9_]*)\}")
+
+ def __init__(
+ self, api, queue, sweep_id=None, function=None, in_jupyter=None, count=None
+ ):
+ self._api = api
+ self._queue = queue
+ self._run_processes = {} # keyed by run.id (GQL run name)
+ self._server_responses = []
+ self._sweep_id = sweep_id
+ self._in_jupyter = in_jupyter
+ self._log = []
+ self._running = True
+ self._last_report_time = None
+ self._function = function
+ self._report_interval = wandb.env.get_agent_report_interval(
+ self.REPORT_INTERVAL
+ )
+ self._kill_delay = wandb.env.get_agent_kill_delay(self.KILL_DELAY)
+ self._finished = 0
+ self._failed = 0
+ self._count = count
+ self._sweep_command = []
+ self._max_initial_failures = wandb.env.get_agent_max_initial_failures(
+ self.MAX_INITIAL_FAILURES
+ )
+ if self._report_interval is None:
+ raise AgentError("Invalid agent report interval")
+ if self._kill_delay is None:
+ raise AgentError("Invalid agent kill delay")
+ # if the directory to log to is not set, set it
+ if os.environ.get("WANDB_DIR") is None:
+ os.environ["WANDB_DIR"] = os.path.abspath(os.getcwd())
+
+ def is_flapping(self):
+ """Determine if the process is flapping.
+
+ Flapping occurs if the agents receives FLAPPING_MAX_FAILURES non-0 exit codes in
+ the first FLAPPING_MAX_SECONDS.
+ """
+ if os.getenv(wandb.env.AGENT_DISABLE_FLAPPING) == "true":
+ return False
+ if time.time() < wandb.START_TIME + self.FLAPPING_MAX_SECONDS:
+ return self._failed >= self.FLAPPING_MAX_FAILURES
+
+ def is_failing(self):
+ return (
+ self._failed >= self._finished
+ and self._max_initial_failures <= self._failed
+ )
+
+ def run(self): # noqa: C901
+ # TODO: catch exceptions, handle errors, show validation warnings, and make more generic
+ sweep_obj = self._api.sweep(self._sweep_id, "{}")
+ if sweep_obj:
+ sweep_yaml = sweep_obj.get("config")
+ if sweep_yaml:
+ sweep_config = yaml.safe_load(sweep_yaml)
+ if sweep_config:
+ sweep_command = sweep_config.get("command")
+ if sweep_command and isinstance(sweep_command, list):
+ self._sweep_command = sweep_command
+
+ # TODO: include sweep ID
+ agent = self._api.register_agent(socket.gethostname(), sweep_id=self._sweep_id)
+ agent_id = agent["id"]
+
+ try:
+ while self._running:
+ commands = util.read_many_from_queue(
+ self._queue, 100, self.POLL_INTERVAL
+ )
+ for command in commands:
+ command["resp_queue"].put(self._process_command(command))
+
+ now = util.stopwatch_now()
+ if self._last_report_time is None or (
+ self._report_interval != 0
+ and now > self._last_report_time + self._report_interval
+ ):
+ logger.info("Running runs: %s", list(self._run_processes.keys()))
+ self._last_report_time = now
+ run_status = {}
+ for run_id, run_process in list(self._run_processes.items()):
+ poll_result = run_process.poll()
+ if poll_result is None:
+ run_status[run_id] = True
+ continue
+ elif (
+ not isinstance(poll_result, bool)
+ and isinstance(poll_result, int)
+ and poll_result > 0
+ ):
+ self._failed += 1
+ if self.is_flapping():
+ logger.error(
+ "Detected %i failed runs in the first %i seconds, shutting down.",
+ self.FLAPPING_MAX_FAILURES,
+ self.FLAPPING_MAX_SECONDS,
+ )
+ logger.info(
+ "To disable this check set WANDB_AGENT_DISABLE_FLAPPING=true"
+ )
+ self._running = False
+ break
+ if self.is_failing():
+ logger.error(
+ "Detected %i failed runs in a row, shutting down.",
+ self._max_initial_failures,
+ )
+ logger.info(
+ "To change this value set WANDB_AGENT_MAX_INITIAL_FAILURES=val"
+ )
+ self._running = False
+ break
+ logger.info("Cleaning up finished run: %s", run_id)
+
+ # wandb.teardown() was added with wandb service and is a hammer to make
+ # sure that active runs are finished before moving on to another agent run
+ #
+ # In the future, a lighter weight way to implement this could be to keep a
+ # service process open for all the agent instances and inform_finish when
+ # the run should be marked complete. This however could require
+ # inform_finish on every run created by this process.
+ if hasattr(wandb, "teardown"):
+ exit_code = 0
+ if isinstance(poll_result, int):
+ exit_code = poll_result
+ elif isinstance(poll_result, bool):
+ exit_code = -1
+ wandb.teardown(exit_code)
+
+ del self._run_processes[run_id]
+ self._last_report_time = None
+ self._finished += 1
+
+ if self._count and self._finished >= self._count or not self._running:
+ self._running = False
+ continue
+
+ commands = self._api.agent_heartbeat(agent_id, {}, run_status)
+
+ # TODO: send _server_responses
+ self._server_responses = []
+ for command in commands:
+ self._server_responses.append(self._process_command(command))
+
+ except KeyboardInterrupt:
+ try:
+ wandb.termlog(
+ "Ctrl-c pressed. Waiting for runs to end. Press ctrl-c again to terminate them."
+ )
+ for _, run_process in self._run_processes.items():
+ run_process.wait()
+ except KeyboardInterrupt:
+ pass
+ finally:
+ try:
+ if not self._in_jupyter:
+ wandb.termlog("Terminating and syncing runs. Press ctrl-c to kill.")
+ for _, run_process in self._run_processes.items():
+ try:
+ run_process.terminate()
+ except OSError:
+ pass # if process is already dead
+ for _, run_process in self._run_processes.items():
+ run_process.wait()
+ except KeyboardInterrupt:
+ wandb.termlog("Killing runs and quitting.")
+ for _, run_process in self._run_processes.items():
+ try:
+ run_process.kill()
+ except OSError:
+ pass # if process is already dead
+
+ def _process_command(self, command):
+ logger.info(
+ "Agent received command: %s"
+ % (command["type"] if "type" in command else "Unknown")
+ )
+ response = {
+ "id": command.get("id"),
+ "result": None,
+ }
+ try:
+ command_type = command["type"]
+ if command_type == "run":
+ result = self._command_run(command)
+ elif command_type == "stop":
+ result = self._command_stop(command)
+ elif command_type == "exit":
+ result = self._command_exit(command)
+ elif command_type == "resume":
+ result = self._command_run(command)
+ else:
+ raise AgentError(f"No such command: {command_type}") # noqa: TRY301
+ response["result"] = result
+ except Exception:
+ logger.exception("Exception while processing command: %s", command)
+ ex_type, ex, tb = sys.exc_info()
+ response["exception"] = f"{ex_type.__name__}: {str(ex)}"
+ response["traceback"] = traceback.format_tb(tb)
+ del tb
+
+ self._log.append((command, response))
+
+ return response
+
+ def _command_run(self, command):
+ logger.info(
+ "Agent starting run with config:\n"
+ + "\n".join(
+ ["\t{}: {}".format(k, v["value"]) for k, v in command["args"].items()]
+ )
+ )
+ if self._in_jupyter:
+ wandb.termlog(
+ f"Agent Starting Run: {command.get('run_id')} with config:\n"
+ + "\n".join(
+ [f"\t{k}: {v['value']}" for k, v in command["args"].items()]
+ )
+ )
+
+ # Setup sweep command
+ sweep_command: List[str] = sweep_utils.create_sweep_command(self._sweep_command)
+
+ run_id = command.get("run_id")
+ sweep_id = os.environ.get(wandb.env.SWEEP_ID)
+ # TODO(jhr): move into settings
+ config_file = os.path.join(
+ "wandb", "sweep-" + sweep_id, "config-" + run_id + ".yaml"
+ )
+ json_file = os.path.join(
+ "wandb", "sweep-" + sweep_id, "config-" + run_id + ".json"
+ )
+
+ os.environ[wandb.env.RUN_ID] = run_id
+
+ base_dir = os.environ.get(wandb.env.DIR, "")
+ sweep_param_path = os.path.join(base_dir, config_file)
+ os.environ[wandb.env.SWEEP_PARAM_PATH] = sweep_param_path
+ wandb_lib.config_util.save_config_file_from_dict(
+ sweep_param_path, command["args"]
+ )
+
+ env = dict(os.environ)
+
+ sweep_vars: Dict[str, Any] = sweep_utils.create_sweep_command_args(command)
+
+ if "${args_json_file}" in sweep_command:
+ with open(json_file, "w") as fp:
+ fp.write(sweep_vars["args_json"][0])
+
+ if self._function:
+ # make sure that each run regenerates setup singleton
+ wandb.teardown()
+ proc = AgentProcess(
+ function=self._function,
+ env=env,
+ run_id=run_id,
+ in_jupyter=self._in_jupyter,
+ )
+ else:
+ sweep_vars["interpreter"] = ["python"]
+ sweep_vars["program"] = [command["program"]]
+ sweep_vars["args_json_file"] = [json_file]
+ if not platform.system() == "Windows":
+ sweep_vars["env"] = ["/usr/bin/env"]
+ command_list = []
+ for c in sweep_command:
+ c = str(c)
+ if c.startswith("${") and c.endswith("}"):
+ replace_list = sweep_vars.get(c[2:-1])
+ command_list += replace_list or []
+ else:
+ command_list += [c]
+ logger.info(
+ "About to run command: {}".format(
+ " ".join(f'"{c}"' if " " in c else c for c in command_list)
+ )
+ )
+ proc = AgentProcess(command=command_list, env=env)
+ self._run_processes[run_id] = proc
+
+ # we keep track of when we sent the sigterm to give processes a chance
+ # to handle the signal before sending sigkill every heartbeat
+ self._run_processes[run_id].last_sigterm_time = None
+ self._last_report_time = None
+
+ def _command_stop(self, command):
+ run_id = command["run_id"]
+ if run_id in self._run_processes:
+ proc = self._run_processes[run_id]
+ now = util.stopwatch_now()
+ if proc.last_sigterm_time is None:
+ proc.last_sigterm_time = now
+ logger.info("Stop: %s", run_id)
+ try:
+ proc.terminate()
+ except OSError: # if process is already dead
+ pass
+ elif now > proc.last_sigterm_time + self._kill_delay:
+ logger.info("Kill: %s", run_id)
+ try:
+ proc.kill()
+ except OSError: # if process is already dead
+ pass
+ else:
+ logger.error("Run %s not running", run_id)
+
+ def _command_exit(self, command):
+ logger.info("Received exit command. Killing runs and quitting.")
+ for _, proc in self._run_processes.items():
+ try:
+ proc.kill()
+ except OSError:
+ # process is already dead
+ pass
+ self._running = False
+
+
+class AgentApi:
+ def __init__(self, queue):
+ self._queue = queue
+ self._command_id = 0
+ self._multiproc_manager = multiprocessing.Manager()
+
+ def command(self, command):
+ command["origin"] = "local"
+ command["id"] = f"local-{self._command_id}"
+ self._command_id += 1
+ resp_queue = self._multiproc_manager.Queue()
+ command["resp_queue"] = resp_queue
+ self._queue.put(command)
+ result = resp_queue.get()
+ print("result:", result) # noqa: T201
+ if "exception" in result:
+ print("Exception occurred while running command") # noqa: T201
+ for line in result["traceback"]:
+ print(line.strip()) # noqa: T201
+ print(result["exception"]) # noqa: T201
+ return result
+
+
+def run_agent(
+ sweep_id, function=None, in_jupyter=None, entity=None, project=None, count=None
+):
+ parts = dict(entity=entity, project=project, name=sweep_id)
+ err = sweep_utils.parse_sweep_id(parts)
+ if err:
+ wandb.termerror(err)
+ return
+ entity = parts.get("entity") or entity
+ project = parts.get("project") or project
+ sweep_id = parts.get("name") or sweep_id
+
+ if entity:
+ wandb.env.set_entity(entity)
+ if project:
+ wandb.env.set_project(project)
+ if sweep_id:
+ # TODO(jhr): remove when jobspec is merged
+ os.environ[wandb.env.SWEEP_ID] = sweep_id
+ logger.setLevel(logging.DEBUG)
+ ch = logging.StreamHandler()
+ log_level = logging.DEBUG
+ if in_jupyter:
+ log_level = logging.ERROR
+ ch.setLevel(log_level)
+ formatter = logging.Formatter(
+ "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+ )
+ ch.setFormatter(formatter)
+ try:
+ logger.addHandler(ch)
+
+ api = InternalApi()
+ queue = multiprocessing.Queue()
+ agent = Agent(
+ api,
+ queue,
+ sweep_id=sweep_id,
+ function=function,
+ in_jupyter=in_jupyter,
+ count=count,
+ )
+ agent.run()
+ finally:
+ # make sure we remove the logging handler (important for jupyter notebooks)
+ logger.removeHandler(ch)
+
+
+def agent(
+ sweep_id: str,
+ function: Optional[Callable] = None,
+ entity: Optional[str] = None,
+ project: Optional[str] = None,
+ count: Optional[int] = None,
+) -> None:
+ """Start one or more sweep agents.
+
+ The sweep agent uses the `sweep_id` to know which sweep it
+ is a part of, what function to execute, and (optionally) how
+ many agents to run.
+
+ Args:
+ sweep_id: The unique identifier for a sweep. A sweep ID
+ is generated by W&B CLI or Python SDK.
+ function: A function to call instead of the "program"
+ specified in the sweep config.
+ entity: The username or team name where you want to send W&B
+ runs created by the sweep to. Ensure that the entity you
+ specify already exists. If you don't specify an entity,
+ the run will be sent to your default entity,
+ which is usually your username.
+ project: The name of the project where W&B runs created from
+ the sweep are sent to. If the project is not specified, the
+ run is sent to a project labeled "Uncategorized".
+ count: The number of sweep config trials to try.
+ """
+ global _INSTANCES
+ _INSTANCES += 1
+ try:
+ # make sure we are logged in
+ wandb_sdk.wandb_login._login(_silent=True)
+ if function:
+ return pyagent(sweep_id, function, entity, project, count)
+ return run_agent(
+ sweep_id,
+ function=function,
+ in_jupyter=ipython.in_jupyter(),
+ entity=entity,
+ project=project,
+ count=count,
+ )
+ finally:
+ _INSTANCES -= 1
+
+
+_INSTANCES = 0
+
+
+def _is_running():
+ return bool(_INSTANCES)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/wandb_controller.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/wandb_controller.py
new file mode 100644
index 0000000000000000000000000000000000000000..f819dc995e27192c7debdc87fa1042b3e77f1c98
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/wandb_controller.py
@@ -0,0 +1,719 @@
+"""Sweep controller.
+
+This module implements the sweep controller.
+
+On error an exception is raised:
+ ControllerError
+
+Example:
+ import wandb
+
+ #
+ # create a sweep controller
+ #
+ # There are three different ways sweeps can be created:
+ # (1) create with sweep id from `wandb sweep` command
+ sweep_id = 'xyzxyz2'
+ tuner = wandb.controller(sweep_id)
+ # (2) create with sweep config
+ sweep_config = {}
+ tuner = wandb.controller()
+ tuner.configure(sweep_config)
+ tuner.create()
+ # (3) create by constructing programmatic sweep configuration
+ tuner = wandb.controller()
+ tuner.configure_search('random')
+ tuner.configure_program('train-dummy.py')
+ tuner.configure_parameter('param1', values=[1,2,3])
+ tuner.configure_parameter('param2', values=[1,2,3])
+ tuner.configure_controller(type="local")
+ tuner.create()
+ #
+ # run the sweep controller
+ #
+ # There are three different ways sweeps can be executed:
+ # (1) run to completion
+ tuner.run()
+ # (2) run in a simple loop
+ while not tuner.done():
+ tuner.step()
+ tuner.print_status()
+ # (3) run in a more complex loop
+ while not tuner.done():
+ params = tuner.search()
+ tuner.schedule(params)
+ runs = tuner.stopping()
+ if runs:
+ tuner.stop_runs(runs)
+"""
+
+import json
+import os
+import random
+import string
+import time
+from typing import Callable, Dict, List, Optional, Tuple, Union
+
+import yaml
+
+from wandb import env
+from wandb.apis import InternalApi
+from wandb.sdk import wandb_sweep
+from wandb.sdk.launch.sweeps.utils import (
+ handle_sweep_config_violations,
+ sweep_config_err_text_from_jsonschema_violations,
+)
+from wandb.util import get_module
+
+# TODO(jhr): Add metric status
+# TODO(jhr): Add print_space
+# TODO(jhr): Add print_summary
+
+
+sweeps = get_module(
+ "sweeps",
+ required="wandb[sweeps] is required to use the local controller. "
+ "Please run `pip install wandb[sweeps]`.",
+)
+
+
+# This should be something like 'pending' (but we need to make sure everyone else is ok with that)
+SWEEP_INITIAL_RUN_STATE = sweeps.RunState.pending
+
+
+def _id_generator(size=10, chars=string.ascii_lowercase + string.digits):
+ return "".join(random.choice(chars) for _ in range(size))
+
+
+class ControllerError(Exception):
+ """Base class for sweep errors."""
+
+
+class _WandbController:
+ """Sweep controller class.
+
+ Internal datastructures on the sweep object to coordinate local controller with
+ cloud controller.
+
+ Data structures:
+ controller: {
+ schedule: [
+ { id: SCHEDULE_ID
+ data: {param1: val1, param2: val2}},
+ ]
+ earlystop: [RUN_ID, ...]
+ scheduler:
+ scheduled: [
+ { id: SCHEDULE_ID
+ runid: RUN_ID},
+ ]
+
+ `controller` is only updated by the client
+ `scheduler` is only updated by the cloud backend
+
+ Protocols:
+ Scheduling a run:
+ - client controller adds a schedule entry on the controller.schedule list
+ - cloud backend notices the new entry and creates a run with the parameters
+ - cloud backend adds a scheduled entry on the scheduler.scheduled list
+ - client controller notices that the run has been scheduled and removes it from
+ controller.schedule list
+
+ Current implementation details:
+ - Runs are only schedule if there are no other runs scheduled.
+
+ """
+
+ def __init__(self, sweep_id_or_config=None, entity=None, project=None):
+ # sweep id configured in constructor
+ self._sweep_id: Optional[str] = None
+
+ # configured parameters
+ # Configuration to be created
+ self._create: Dict = {}
+ # Custom search
+ self._custom_search: Optional[
+ Callable[
+ [Union[dict, sweeps.SweepConfig], List[sweeps.SweepRun]],
+ Optional[sweeps.SweepRun],
+ ]
+ ] = None
+ # Custom stopping
+ self._custom_stopping: Optional[
+ Callable[
+ [Union[dict, sweeps.SweepConfig], List[sweeps.SweepRun]],
+ List[sweeps.SweepRun],
+ ]
+ ] = None
+ # Program function (used for future jupyter support)
+ self._program_function = None
+
+ # The following are updated every sweep step
+ # raw sweep object (dict of strings)
+ self._sweep_obj = None
+ # parsed sweep config (dict)
+ self._sweep_config: Optional[Union[dict, sweeps.SweepConfig]] = None
+ # sweep metric used to optimize (str or None)
+ self._sweep_metric: Optional[str] = None
+ # list of _Run objects
+ self._sweep_runs: Optional[List[sweeps.SweepRun]] = None
+ # dictionary mapping name of run to run object
+ self._sweep_runs_map: Optional[Dict[str, sweeps.SweepRun]] = None
+ # scheduler dict (read only from controller) - used as feedback from the server
+ self._scheduler: Optional[Dict] = None
+ # controller dict (write only from controller) - used to send commands to server
+ self._controller: Optional[Dict] = None
+ # keep track of controller dict from previous step
+ self._controller_prev_step: Optional[Dict] = None
+
+ # Internal
+ # Keep track of whether the sweep has been started
+ self._started: bool = False
+ # indicate whether there is more to schedule
+ self._done_scheduling: bool = False
+ # indicate whether the sweep needs to be created
+ self._defer_sweep_creation: bool = False
+ # count of logged lines since last status
+ self._logged: int = 0
+ # last status line printed
+ self._laststatus: str = ""
+ # keep track of logged actions for print_actions()
+ self._log_actions: List[Tuple[str, str]] = []
+ # keep track of logged debug for print_debug()
+ self._log_debug: List[str] = []
+
+ # all backend commands use internal api
+ environ = os.environ
+ if entity:
+ env.set_entity(entity, env=environ)
+ if project:
+ env.set_project(project, env=environ)
+ self._api = InternalApi(environ=environ)
+
+ if isinstance(sweep_id_or_config, str):
+ self._sweep_id = sweep_id_or_config
+ elif isinstance(sweep_id_or_config, dict) or isinstance(
+ sweep_id_or_config, sweeps.SweepConfig
+ ):
+ self._create = sweeps.SweepConfig(sweep_id_or_config)
+
+ # check for custom search and or stopping functions
+ for config_key, controller_attr in zip(
+ ["method", "early_terminate"], ["_custom_search", "_custom_stopping"]
+ ):
+ if callable(config_key in self._create and self._create[config_key]):
+ setattr(self, controller_attr, self._create[config_key])
+ self._create[config_key] = "custom"
+
+ self._sweep_id = self.create(from_dict=True)
+ elif sweep_id_or_config is None:
+ self._defer_sweep_creation = True
+ return
+ else:
+ raise ControllerError("Unhandled sweep controller type")
+ sweep_obj = self._sweep_object_read_from_backend()
+ if sweep_obj is None:
+ raise ControllerError("Can not find sweep")
+ self._sweep_obj = sweep_obj
+
+ def configure_search(
+ self,
+ search: Union[
+ str,
+ Callable[
+ [Union[dict, sweeps.SweepConfig], List[sweeps.SweepRun]],
+ Optional[sweeps.SweepRun],
+ ],
+ ],
+ ):
+ self._configure_check()
+ if isinstance(search, str):
+ self._create["method"] = search
+ elif callable(search):
+ self._create["method"] = "custom"
+ self._custom_search = search
+ else:
+ raise ControllerError("Unhandled search type.")
+
+ def configure_stopping(
+ self,
+ stopping: Union[
+ str,
+ Callable[
+ [Union[dict, sweeps.SweepConfig], List[sweeps.SweepRun]],
+ List[sweeps.SweepRun],
+ ],
+ ],
+ **kwargs,
+ ):
+ self._configure_check()
+ if isinstance(stopping, str):
+ self._create.setdefault("early_terminate", {})
+ self._create["early_terminate"]["type"] = stopping
+ for k, v in kwargs.items():
+ self._create["early_terminate"][k] = v
+ elif callable(stopping):
+ self._custom_stopping = stopping(kwargs)
+ self._create.setdefault("early_terminate", {})
+ self._create["early_terminate"]["type"] = "custom"
+ else:
+ raise ControllerError("Unhandled stopping type.")
+
+ def configure_metric(self, metric, goal=None):
+ self._configure_check()
+ self._create.setdefault("metric", {})
+ self._create["metric"]["name"] = metric
+ if goal:
+ self._create["metric"]["goal"] = goal
+
+ def configure_program(self, program):
+ self._configure_check()
+ if isinstance(program, str):
+ self._create["program"] = program
+ elif callable(program):
+ self._create["program"] = "__callable__"
+ self._program_function = program
+ raise ControllerError("Program functions are not supported yet")
+ else:
+ raise ControllerError("Unhandled sweep program type")
+
+ def configure_name(self, name):
+ self._configure_check()
+ self._create["name"] = name
+
+ def configure_description(self, description):
+ self._configure_check()
+ self._create["description"] = description
+
+ def configure_parameter(
+ self,
+ name,
+ values=None,
+ value=None,
+ distribution=None,
+ min=None,
+ max=None,
+ mu=None,
+ sigma=None,
+ q=None,
+ a=None,
+ b=None,
+ ):
+ self._configure_check()
+ self._create.setdefault("parameters", {}).setdefault(name, {})
+ if value is not None or (
+ values is None and min is None and max is None and distribution is None
+ ):
+ self._create["parameters"][name]["value"] = value
+ if values is not None:
+ self._create["parameters"][name]["values"] = values
+ if distribution is not None:
+ self._create["parameters"][name]["distribution"] = distribution
+ if min is not None:
+ self._create["parameters"][name]["min"] = min
+ if max is not None:
+ self._create["parameters"][name]["max"] = max
+ if mu is not None:
+ self._create["parameters"][name]["mu"] = mu
+ if sigma is not None:
+ self._create["parameters"][name]["sigma"] = sigma
+ if q is not None:
+ self._create["parameters"][name]["q"] = q
+ if a is not None:
+ self._create["parameters"][name]["a"] = a
+ if b is not None:
+ self._create["parameters"][name]["b"] = b
+
+ def configure_controller(self, type):
+ """Configure controller to local if type == 'local'."""
+ self._configure_check()
+ self._create.setdefault("controller", {})
+ self._create["controller"].setdefault("type", type)
+
+ def configure(self, sweep_dict_or_config):
+ self._configure_check()
+ if self._create:
+ raise ControllerError("Already configured.")
+ if isinstance(sweep_dict_or_config, dict):
+ self._create = sweep_dict_or_config
+ elif isinstance(sweep_dict_or_config, str):
+ self._create = yaml.safe_load(sweep_dict_or_config)
+ else:
+ raise ControllerError("Unhandled sweep controller type")
+
+ @property
+ def sweep_config(self) -> Union[dict, sweeps.SweepConfig]:
+ return self._sweep_config
+
+ @property
+ def sweep_id(self) -> str:
+ return self._sweep_id
+
+ def _log(self) -> None:
+ self._logged += 1
+
+ def _error(self, s: str) -> None:
+ print("ERROR:", s) # noqa: T201
+ self._log()
+
+ def _warn(self, s: str) -> None:
+ print("WARN:", s) # noqa: T201
+ self._log()
+
+ def _info(self, s: str) -> None:
+ print("INFO:", s) # noqa: T201
+ self._log()
+
+ def _debug(self, s: str) -> None:
+ print("DEBUG:", s) # noqa: T201
+ self._log()
+
+ def _configure_check(self) -> None:
+ if self._started:
+ raise ControllerError("Can not configure after sweep has been started.")
+
+ def _validate(self, config: Dict) -> str:
+ violations = sweeps.schema_violations_from_proposed_config(config)
+ msg = (
+ sweep_config_err_text_from_jsonschema_violations(violations)
+ if len(violations) > 0
+ else ""
+ )
+ return msg
+
+ def create(self, from_dict: bool = False) -> str:
+ if self._started:
+ raise ControllerError("Can not create after sweep has been started.")
+ if not self._defer_sweep_creation and not from_dict:
+ raise ControllerError("Can not use create on already created sweep.")
+ if not self._create:
+ raise ControllerError("Must configure sweep before create.")
+
+ # validate sweep config
+ self._create = sweeps.SweepConfig(self._create)
+
+ # Create sweep
+ sweep_id, warnings = self._api.upsert_sweep(self._create)
+ handle_sweep_config_violations(warnings)
+
+ print("Create sweep with ID:", sweep_id) # noqa: T201
+ sweep_url = wandb_sweep._get_sweep_url(self._api, sweep_id)
+ if sweep_url:
+ print("Sweep URL:", sweep_url) # noqa: T201
+ self._sweep_id = sweep_id
+ self._defer_sweep_creation = False
+ return sweep_id
+
+ def run(
+ self,
+ verbose: bool = False,
+ print_status: bool = True,
+ print_actions: bool = False,
+ print_debug: bool = False,
+ ) -> None:
+ if verbose:
+ print_status = True
+ print_actions = True
+ print_debug = True
+ self._start_if_not_started()
+ while not self.done():
+ if print_status:
+ self.print_status()
+ self.step()
+ if print_actions:
+ self.print_actions()
+ if print_debug:
+ self.print_debug()
+ time.sleep(5)
+
+ def _sweep_object_read_from_backend(self) -> Optional[dict]:
+ specs_json = {}
+ if self._sweep_metric:
+ k = ["_step"]
+ k.append(self._sweep_metric)
+ specs_json = {"keys": k, "samples": 100000}
+ specs = json.dumps(specs_json)
+ # TODO(jhr): catch exceptions?
+ sweep_obj = self._api.sweep(self._sweep_id, specs)
+ if not sweep_obj:
+ return
+ self._sweep_obj = sweep_obj
+ self._sweep_config = yaml.safe_load(sweep_obj["config"])
+ self._sweep_metric = self._sweep_config.get("metric", {}).get("name")
+
+ _sweep_runs: List[sweeps.SweepRun] = []
+ for r in sweep_obj["runs"]:
+ rr = r.copy()
+ if "summaryMetrics" in rr:
+ if rr["summaryMetrics"]:
+ rr["summaryMetrics"] = json.loads(rr["summaryMetrics"])
+ if "config" not in rr:
+ raise ValueError("sweep object is missing config")
+ rr["config"] = json.loads(rr["config"])
+ if "history" in rr:
+ if isinstance(rr["history"], list):
+ rr["history"] = [json.loads(d) for d in rr["history"]]
+ else:
+ raise ValueError(
+ "Invalid history value: expected list of json strings: {}".format(
+ rr["history"]
+ )
+ )
+ if "sampledHistory" in rr:
+ sampled_history = []
+ for historyDictList in rr["sampledHistory"]:
+ sampled_history += historyDictList
+ rr["sampledHistory"] = sampled_history
+ _sweep_runs.append(sweeps.SweepRun(**rr))
+
+ self._sweep_runs = _sweep_runs
+ self._sweep_runs_map = {r.name: r for r in self._sweep_runs}
+
+ self._controller = json.loads(sweep_obj.get("controller") or "{}")
+ self._scheduler = json.loads(sweep_obj.get("scheduler") or "{}")
+ self._controller_prev_step = self._controller.copy()
+ return sweep_obj
+
+ def _sweep_object_sync_to_backend(self) -> None:
+ if self._controller == self._controller_prev_step:
+ return
+ sweep_obj_id = self._sweep_obj["id"]
+ controller = json.dumps(self._controller)
+ _, warnings = self._api.upsert_sweep(
+ self._sweep_config, controller=controller, obj_id=sweep_obj_id
+ )
+ handle_sweep_config_violations(warnings)
+ self._controller_prev_step = self._controller.copy()
+
+ def _start_if_not_started(self) -> None:
+ if self._started:
+ return
+ if self._defer_sweep_creation:
+ raise ControllerError(
+ "Must specify or create a sweep before running controller."
+ )
+ obj = self._sweep_object_read_from_backend()
+ if not obj:
+ return
+ is_local = self._sweep_config.get("controller", {}).get("type") == "local"
+ if not is_local:
+ raise ControllerError(
+ "Only sweeps with a local controller are currently supported."
+ )
+ self._started = True
+ # reset controller state, we might want to parse this and decide
+ # what we can continue and add a version key, but for now we can
+ # be safe and just reset things on start
+ self._controller = {}
+ self._sweep_object_sync_to_backend()
+
+ def _parse_scheduled(self):
+ scheduled_list = self._scheduler.get("scheduled") or []
+ started_ids = []
+ stopped_runs = []
+ done_runs = []
+ for s in scheduled_list:
+ runid = s.get("runid")
+ objid = s.get("id")
+ r = self._sweep_runs_map.get(runid)
+ if not r:
+ continue
+ if r.stopped:
+ stopped_runs.append(runid)
+ summary = r.summary_metrics
+ if r.state == SWEEP_INITIAL_RUN_STATE and not summary:
+ continue
+ started_ids.append(objid)
+ if r.state != "running":
+ done_runs.append(runid)
+ return started_ids, stopped_runs, done_runs
+
+ def _step(self) -> None:
+ self._start_if_not_started()
+ self._sweep_object_read_from_backend()
+
+ started_ids, stopped_runs, done_runs = self._parse_scheduled()
+
+ # Remove schedule entry from controller dict if already scheduled
+ schedule_list = self._controller.get("schedule", [])
+ new_schedule_list = [s for s in schedule_list if s.get("id") not in started_ids]
+ self._controller["schedule"] = new_schedule_list
+
+ # Remove earlystop entry from controller if already stopped
+ earlystop_list = self._controller.get("earlystop", [])
+ new_earlystop_list = [
+ r for r in earlystop_list if r not in stopped_runs and r not in done_runs
+ ]
+ self._controller["earlystop"] = new_earlystop_list
+
+ # Clear out step logs
+ self._log_actions = []
+ self._log_debug = []
+
+ def step(self) -> None:
+ self._step()
+ suggestion = self.search()
+ self.schedule(suggestion)
+ to_stop = self.stopping()
+ if len(to_stop) > 0:
+ self.stop_runs(to_stop)
+
+ def done(self) -> bool:
+ self._start_if_not_started()
+ state = self._sweep_obj.get("state")
+ if state in [
+ s.upper()
+ for s in (
+ sweeps.RunState.preempting.value,
+ SWEEP_INITIAL_RUN_STATE.value,
+ sweeps.RunState.running.value,
+ )
+ ]:
+ return False
+ return True
+
+ def _search(self) -> Optional[sweeps.SweepRun]:
+ search = self._custom_search or sweeps.next_run
+ next_run = search(self._sweep_config, self._sweep_runs or [])
+ if next_run is None:
+ self._done_scheduling = True
+ return next_run
+
+ def search(self) -> Optional[sweeps.SweepRun]:
+ self._start_if_not_started()
+ suggestion = self._search()
+ return suggestion
+
+ def _stopping(self) -> List[sweeps.SweepRun]:
+ if "early_terminate" not in self.sweep_config:
+ return []
+ stopper = self._custom_stopping or sweeps.stop_runs
+ stop_runs = stopper(self._sweep_config, self._sweep_runs or [])
+
+ debug_lines = [
+ " ".join([f"{k}={v}" for k, v in run.early_terminate_info.items()])
+ for run in stop_runs
+ if run.early_terminate_info is not None
+ ]
+ if debug_lines:
+ self._log_debug += debug_lines
+
+ return stop_runs
+
+ def stopping(self) -> List[sweeps.SweepRun]:
+ self._start_if_not_started()
+ return self._stopping()
+
+ def schedule(self, run: Optional[sweeps.SweepRun]) -> None:
+ self._start_if_not_started()
+
+ # only schedule one run at a time (for now)
+ if self._controller and self._controller.get("schedule"):
+ return
+
+ schedule_id = _id_generator()
+
+ if run is None:
+ schedule_list = [{"id": schedule_id, "data": {"args": None}}]
+ else:
+ param_list = [
+ "{}={}".format(k, v.get("value")) for k, v in sorted(run.config.items())
+ ]
+ self._log_actions.append(("schedule", ",".join(param_list)))
+
+ # schedule one run
+ schedule_list = [{"id": schedule_id, "data": {"args": run.config}}]
+
+ self._controller["schedule"] = schedule_list
+ self._sweep_object_sync_to_backend()
+
+ def stop_runs(self, runs: List[sweeps.SweepRun]) -> None:
+ earlystop_list = list({run.name for run in runs})
+ self._log_actions.append(("stop", ",".join(earlystop_list)))
+ self._controller["earlystop"] = earlystop_list
+ self._sweep_object_sync_to_backend()
+
+ def print_status(self) -> None:
+ status = _sweep_status(self._sweep_obj, self._sweep_config, self._sweep_runs)
+ if self._laststatus != status or self._logged:
+ print(status) # noqa: T201
+ self._laststatus = status
+ self._logged = 0
+
+ def print_actions(self) -> None:
+ for action, line in self._log_actions:
+ self._info(f"{action.capitalize()} ({line})")
+ self._log_actions = []
+
+ def print_debug(self) -> None:
+ for line in self._log_debug:
+ self._debug(line)
+ self._log_debug = []
+
+ def print_space(self) -> None:
+ self._warn("Method not implemented yet.")
+
+ def print_summary(self) -> None:
+ self._warn("Method not implemented yet.")
+
+
+def _get_run_counts(runs: List[sweeps.SweepRun]) -> Dict[str, int]:
+ metrics = {}
+ categories = [name for name, _ in sweeps.RunState.__members__.items()] + ["unknown"]
+ for r in runs:
+ state = r.state
+ found = "unknown"
+ for c in categories:
+ if state == c:
+ found = c
+ break
+ metrics.setdefault(found, 0)
+ metrics[found] += 1
+ return metrics
+
+
+def _get_runs_status(metrics):
+ categories = [name for name, _ in sweeps.RunState.__members__.items()] + ["unknown"]
+ mlist = []
+ for c in categories:
+ if not metrics.get(c):
+ continue
+ mlist.append(f"{c.capitalize()}: {metrics[c]}")
+ s = ", ".join(mlist)
+ return s
+
+
+def _sweep_status(
+ sweep_obj: dict,
+ sweep_conf: Union[dict, sweeps.SweepConfig],
+ sweep_runs: List[sweeps.SweepRun],
+) -> str:
+ sweep = sweep_obj["name"]
+ _ = sweep_obj["state"]
+ run_count = len(sweep_runs)
+ run_type_counts = _get_run_counts(sweep_runs)
+ stopped = len([r for r in sweep_runs if r.stopped])
+ stopping = len([r for r in sweep_runs if r.should_stop])
+ stopstr = ""
+ if stopped or stopping:
+ stopstr = f"Stopped: {stopped}"
+ if stopping:
+ stopstr += f" (Stopping: {stopping})"
+ runs_status = _get_runs_status(run_type_counts)
+ method = sweep_conf.get("method", "unknown")
+ stopping = sweep_conf.get("early_terminate", None)
+ sweep_options = []
+ sweep_options.append(method)
+ if stopping:
+ sweep_options.append(stopping.get("type", "unknown"))
+ sweep_options = ",".join(sweep_options)
+ sections = []
+ sections.append(f"Sweep: {sweep} ({sweep_options})")
+ if runs_status:
+ sections.append(f"Runs: {run_count} ({runs_status})")
+ else:
+ sections.append(f"Runs: {run_count}")
+ if stopstr:
+ sections.append(stopstr)
+ sections = " | ".join(sections)
+ return sections
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/wandb_run.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/wandb_run.py
new file mode 100644
index 0000000000000000000000000000000000000000..01cfb8ce2874a86f646c055127b8f568b3a55681
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/wandb/wandb_run.py
@@ -0,0 +1,8 @@
+"""Compatibility wandb_run module.
+
+Please use `wandb.Run` instead.
+"""
+
+from wandb.sdk.wandb_run import Run
+
+__all__ = ["Run"]