diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/licenses/LICENSE b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google_auth_oauthlib-1.4.0.dist-info/licenses/LICENSE @@ -0,0 +1,202 @@ + + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1ac0893931d37fc0a9de69767012f0bef43a16f Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/__pycache__/_impl.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/__pycache__/_impl.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..052a2069d6176d43057574ed8b50ce98d6a3b946 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/__pycache__/_impl.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/__pycache__/_version.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/__pycache__/_version.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd3f3b43941eb0ad884d39e8a177cb1110f88d49 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/__pycache__/_version.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_tests/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_tests/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94834252fad51a6f59af30601422ac8a41329222 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_tests/__pycache__/test_sniffio.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_tests/__pycache__/test_sniffio.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16df41ccb4bbeb4287b829f05df8071e4777fa16 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_tests/__pycache__/test_sniffio.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_tests/test_sniffio.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_tests/test_sniffio.py new file mode 100644 index 0000000000000000000000000000000000000000..02945a947527a9bfb396d0cd35ffee22eda665bb --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/sniffio/_tests/test_sniffio.py @@ -0,0 +1,84 @@ +import os +import sys + +import pytest + +from .. import ( + current_async_library, AsyncLibraryNotFoundError, + current_async_library_cvar, thread_local +) + + +def test_basics_cvar(): + with pytest.raises(AsyncLibraryNotFoundError): + current_async_library() + + token = current_async_library_cvar.set("generic-lib") + try: + assert current_async_library() == "generic-lib" + finally: + current_async_library_cvar.reset(token) + + with pytest.raises(AsyncLibraryNotFoundError): + current_async_library() + + +def test_basics_tlocal(): + with pytest.raises(AsyncLibraryNotFoundError): + current_async_library() + + old_name, thread_local.name = thread_local.name, "generic-lib" + try: + assert current_async_library() == "generic-lib" + finally: + thread_local.name = old_name + + with pytest.raises(AsyncLibraryNotFoundError): + current_async_library() + + +def test_asyncio(): + import asyncio + + with pytest.raises(AsyncLibraryNotFoundError): + current_async_library() + + ran = [] + + async def this_is_asyncio(): + assert current_async_library() == "asyncio" + # Call it a second time to exercise the caching logic + assert current_async_library() == "asyncio" + ran.append(True) + + asyncio.run(this_is_asyncio()) + assert ran == [True] + + with pytest.raises(AsyncLibraryNotFoundError): + current_async_library() + + +@pytest.mark.skipif( + sys.version_info >= (3, 12), + reason= + "curio broken on 3.12 (https://github.com/python-trio/sniffio/pull/42)", +) +def test_curio(): + import curio + + with pytest.raises(AsyncLibraryNotFoundError): + current_async_library() + + ran = [] + + async def this_is_curio(): + assert current_async_library() == "curio" + # Call it a second time to exercise the caching logic + assert current_async_library() == "curio" + ran.append(True) + + curio.run(this_is_curio) + assert ran == [True] + + with pytest.raises(AsyncLibraryNotFoundError): + current_async_library() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/mx_kernels/fused_pad_token_groups.cu b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/mx_kernels/fused_pad_token_groups.cu new file mode 100644 index 0000000000000000000000000000000000000000..de14784bfbbee767e956a900e5fe4462e6694813 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/mx_kernels/fused_pad_token_groups.cu @@ -0,0 +1,241 @@ +#include +#include +#include +#include + +#define CUDA_CHECK(call) \ + do { \ + cudaError_t error = call; \ + if (error != cudaSuccess) { \ + fprintf(stderr, "CUDA error at %s:%d: %s\n", __FILE__, __LINE__, \ + cudaGetErrorString(error)); \ + exit(EXIT_FAILURE); \ + } \ + } while(0) + +__host__ __device__ __forceinline__ int ceil_div(int a, int b) { + return (a + b - 1) / b; +} + +__device__ __forceinline__ int find_group_id( + int row_idx, + const int32_t* __restrict__ group_end_offsets, + int num_groups +) { + // linear prefix sum lookup (same or faster than binary search for small num groups, which ours are <= 32) + int group_id = 0; + while (group_id < num_groups - 1 && row_idx >= group_end_offsets[group_id]) { + ++group_id; + } + return group_id; +} + +__global__ void fused_pad_token_groups_kernel( + const __nv_bfloat16* __restrict__ input, + const int32_t* __restrict__ group_end_offsets, + const int32_t* __restrict__ padded_group_start_offsets, + __nv_bfloat16* __restrict__ output, + int num_tokens, + int dim, + int num_groups +) { + constexpr int WARP_SIZE = 32; + const int lane_id = threadIdx.x % WARP_SIZE; + const int warp_id_in_block = threadIdx.x / WARP_SIZE; + const int warps_per_block = blockDim.x / WARP_SIZE; // each warp handles 1 row + const int global_row_idx = blockIdx.x * warps_per_block + warp_id_in_block; + + if (global_row_idx >= num_tokens) return; + + // one thread finds which group this row belongs to, then broadcasts to other lanes via warp shuffle + int group_id; + if (lane_id == 0) { + group_id = find_group_id(global_row_idx, group_end_offsets, num_groups); + } + group_id = __shfl_sync(0xffffffff, group_id, 0); + + int group_start = (group_id > 0) ? group_end_offsets[group_id - 1] : 0; + int padded_start = padded_group_start_offsets[group_id]; + int offset_in_group = global_row_idx - group_start; + int output_row = padded_start + offset_in_group; + + const __nv_bfloat16* row_in = input + global_row_idx * dim; + __nv_bfloat16* row_out = output + output_row * dim; + + // vectorized copy for all complete float4 chunks (8 bf16 elements each) + int num_vecs = dim / 8; + if (num_vecs > 0) { + const float4* in_vec = reinterpret_cast(row_in); + float4* out_vec = reinterpret_cast(row_out); + + for (int i = lane_id; i < num_vecs; i += 32) { + out_vec[i] = in_vec[i]; + } + } + + // scalar copy for remaining elems + int elems_covered = num_vecs * 8; + for (int i = elems_covered + lane_id; i < dim; i += 32) { + row_out[i] = row_in[i]; + } +} + +__global__ void fused_unpad_token_groups_kernel( + const __nv_bfloat16* __restrict__ input, + const int32_t* __restrict__ group_end_offsets, + const int32_t* __restrict__ padded_group_start_offsets, + __nv_bfloat16* __restrict__ output, + int num_tokens, + int dim, + int num_groups +) { + constexpr int WARP_SIZE = 32; + const int lane_id = threadIdx.x % WARP_SIZE; + const int warp_id_in_block = threadIdx.x / WARP_SIZE; + const int warps_per_block = blockDim.x / WARP_SIZE; // each warp handles 1 row + const int global_row_idx = blockIdx.x * warps_per_block + warp_id_in_block; + + if (global_row_idx >= num_tokens) return; + + // one thread finds which group this row belongs to, then broadcasts to other lanes via warp shuffle + int group_id; + if (lane_id == 0) { + group_id = find_group_id(global_row_idx, group_end_offsets, num_groups); + } + group_id = __shfl_sync(0xffffffff, group_id, 0); + + int group_start = (group_id > 0) ? group_end_offsets[group_id - 1] : 0; + int padded_start = padded_group_start_offsets[group_id]; + int offset_in_group = global_row_idx - group_start; + int input_row = padded_start + offset_in_group; + + const __nv_bfloat16* row_in = input + input_row * dim; + __nv_bfloat16* row_out = output + global_row_idx * dim; + + // vectorized copy for all complete float4 chunks (8 bf16 elements each) + int num_vecs = dim / 8; + if (num_vecs > 0) { + const float4* in_vec = reinterpret_cast(row_in); + float4* out_vec = reinterpret_cast(row_out); + + for (int i = lane_id; i < num_vecs; i += 32) { + out_vec[i] = in_vec[i]; + } + } + + // scalar copy for remaining elems + int elems_covered = num_vecs * 8; + for (int i = elems_covered + lane_id; i < dim; i += 32) { + row_out[i] = row_in[i]; + } +} + +__global__ void compute_padded_offsets_kernel( + const int32_t* __restrict__ group_end_offsets, + int32_t* __restrict__ padded_group_start_offsets, + int32_t* __restrict__ padded_group_end_offsets, + int num_groups, + int alignment_size +) { + if (threadIdx.x == 0) { + int cumulative = 0; + + for (int g = 0; g < num_groups; g++) { + int group_start = (g > 0) ? group_end_offsets[g - 1] : 0; + int group_end = group_end_offsets[g]; + int group_size = group_end - group_start; + + int padded_size = ((group_size + alignment_size - 1) / alignment_size) * alignment_size; + + padded_group_start_offsets[g] = cumulative; + cumulative += padded_size; + padded_group_end_offsets[g] = cumulative; + } + } +} + +namespace mxfp8 { + +void launch_compute_padded_offsets_cuda( + const int32_t* group_end_offsets_ptr, + int32_t* padded_group_start_offsets_ptr, + int32_t* padded_group_end_offsets_ptr, + int num_groups, + int alignment_size, + cudaStream_t stream +) { + // Single warp is enough for num_groups <= 32 + compute_padded_offsets_kernel<<<1, 32, 0, stream>>>( + group_end_offsets_ptr, + padded_group_start_offsets_ptr, + padded_group_end_offsets_ptr, + num_groups, + alignment_size + ); + + CUDA_CHECK(cudaGetLastError()); +} + +void launch_fused_pad_token_groups_cuda( + const void* input_ptr, + const int32_t* group_end_offsets_ptr, + const int32_t* padded_group_start_offsets_ptr, + void* output_ptr, + int num_tokens, + int dim, + int num_groups, + int dtype_size, + int dtype_enum, + cudaStream_t stream +) { + const int WARPS_PER_BLOCK = 8; + const int THREADS_PER_WARP = 32; + const int THREADS_PER_BLOCK = WARPS_PER_BLOCK * THREADS_PER_WARP; // 256 threads + + const int num_blocks = ceil_div(num_tokens, WARPS_PER_BLOCK); + + fused_pad_token_groups_kernel<<>>( + reinterpret_cast(input_ptr), + group_end_offsets_ptr, + padded_group_start_offsets_ptr, + reinterpret_cast<__nv_bfloat16*>(output_ptr), + num_tokens, + dim, + num_groups + ); + + CUDA_CHECK(cudaGetLastError()); +} + +void launch_fused_unpad_token_groups_cuda( + const void* input_ptr, + const int32_t* group_end_offsets_ptr, + const int32_t* padded_group_start_offsets_ptr, + void* output_ptr, + int num_tokens, + int dim, + int num_groups, + int dtype_size, + int dtype_enum, + cudaStream_t stream +) { + const int WARPS_PER_BLOCK = 8; + const int THREADS_PER_WARP = 32; + const int THREADS_PER_BLOCK = WARPS_PER_BLOCK * THREADS_PER_WARP; // 256 threads + + const int num_blocks = ceil_div(num_tokens, WARPS_PER_BLOCK); + + fused_unpad_token_groups_kernel<<>>( + reinterpret_cast(input_ptr), + group_end_offsets_ptr, + padded_group_start_offsets_ptr, + reinterpret_cast<__nv_bfloat16*>(output_ptr), + num_tokens, + dim, + num_groups + ); + + CUDA_CHECK(cudaGetLastError()); +} + +} // namespace mxfp8 \ No newline at end of file diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/mx_kernels/mx_block_rearrange_2d_M_groups.cu b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/mx_kernels/mx_block_rearrange_2d_M_groups.cu new file mode 100644 index 0000000000000000000000000000000000000000..c072e053414e49fb1a9e6f6dd6bc850361b4f0c1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/mx_kernels/mx_block_rearrange_2d_M_groups.cu @@ -0,0 +1,878 @@ +/** + * MX Block Rearrange 2D Kernel for M-Groups (Groups along row dimension) + * + * TERMINOLOGY: + * - SF Tile: A 128x4 scale factor tile (512 bytes in blocked layout) + * - SF_ROWS = 128 rows + * - SF_COLS = 4 columns + * - Each SF tile is stored contiguously in the output blocked layout + * + * - Chunk: A 128xCHUNK_WIDTH region (128 rows × 16, 32, 64, or 128 columns) + * - One TMA load brings one chunk from GMEM to SMEM + * - Contains multiple SF tiles horizontally (CHUNK_WIDTH/SF_COLS = 4, 8, 16, or 32) + * - Each chunk is processed independently in the pipeline + * + * - Superblock: CHUNKS_PER_TB chunks stacked vertically + * - Processed by one thread block + * - Height = SF_ROWS * CHUNKS_PER_TB (128, 512, 1024, or 2048 rows) + * - Width = CHUNK_WIDTH (16, 32, 64, or 128 columns) + * - Grid is organized as (num_col_chunks, num_row_superblocks) + */ +#include +#include +#include + +#include +#include +#include +#include "ptx.cuh" + +// Overloaded error checking for both CUDA driver API (CUresult) and runtime API (cudaError_t) +inline void cuda_check_impl(CUresult result, const char* file, int line) { + if (result != CUDA_SUCCESS) { + fprintf(stderr, "CUDA Driver Error at %s:%d - Error code: %d\n", file, line, (int)result); + exit(EXIT_FAILURE); + } +} + +inline void cuda_check_impl(cudaError_t result, const char* file, int line) { + if (result != cudaSuccess) { + fprintf(stderr, "CUDA Runtime Error at %s:%d - %s\n", file, line, + cudaGetErrorString(result)); + exit(EXIT_FAILURE); + } +} + +#define CUDA_CHECK(result) cuda_check_impl((result), __FILE__, __LINE__) + +// Get the driver entry point for cuTensorMapEncodeTiled (used for TMA tensor maps) +inline void* get_driver_ptr() { + static void *driver_ptr = nullptr; + if (!driver_ptr) { + cudaDriverEntryPointQueryResult result; + CUDA_CHECK(cudaGetDriverEntryPoint("cuTensorMapEncodeTiled", &driver_ptr, + cudaEnableDefault, &result)); + } + return driver_ptr; +} + +// Device helper: ceiling division +__device__ __forceinline__ int ceil_div(int a, int b) { + return (a + b - 1) / b; +} + +#define SF_ROWS 128 +#define SF_COLS 4 + +// Each thread reads 16 bytes (vectorized uint4 load) +#define BYTES_PER_THREAD 16 + +// Double buffering for pipelined TMA loads/stores +#define NUM_BUFFERS 2 + + + +// Here the chunks are 128x64/128x128 and superblock contains multiple vertical chunks (e.g., 4 chunks of 128x64 would be 512x64). +template +__device__ void find_group_and_local_offset_for_superblock( + int row_superblock_pid, + const int32_t* __restrict__ input_group_end_offsets, + int num_groups, + int* __restrict__ smem_data, + int& group_id, + int& superblock_idx_in_group, + int& superblocks_until_end +) { + // Thread 0 computes how many superblocks span each group + if (threadIdx.x == 0) { + constexpr int SUPERBLOCK_ROWS = SF_ROWS * CHUNKS_PER_TB; + int superblock_cumsum = 0; + for (int g = 0; g < num_groups; g++) { + int input_group_start = (g > 0) ? input_group_end_offsets[g - 1] : 0; + int input_group_end = input_group_end_offsets[g]; + int group_size = input_group_end - input_group_start; + int num_superblocks_in_group = ceil_div(group_size, SUPERBLOCK_ROWS); + smem_data[g] = num_superblocks_in_group; + superblock_cumsum += num_superblocks_in_group; + smem_data[num_groups + g] = superblock_cumsum; + } + } + __syncthreads(); + + // All threads use the SMEM cumsum to find their group + group_id = 0; + int superblock_cumsum_before = 0; + for (int g = 0; g < num_groups; g++) { + int cumsum_at_g = smem_data[num_groups + g]; + if (row_superblock_pid < cumsum_at_g) { + group_id = g; + superblock_idx_in_group = row_superblock_pid - superblock_cumsum_before; + int superblocks_in_group = smem_data[g]; + superblocks_until_end = superblocks_in_group - superblock_idx_in_group; + return; + } + superblock_cumsum_before = cumsum_at_g; + } + + superblock_idx_in_group = 0; + superblocks_until_end = 0; +} + +/** + * Compute the starting row in the output buffer for a given group. + * Each group is padded to a multiple of SF_ROWS (128) in the output. + */ +__device__ __forceinline__ int compute_output_group_start_row( + int group_id, + const int32_t* input_group_end_offsets, + int num_groups, + int padding_size +) { + int start_idx = 0; + for (int i = 0; i < group_id; i++) { + int prev_offset = (i > 0) ? input_group_end_offsets[i - 1] : 0; + int curr_offset = input_group_end_offsets[i]; + int group_size = curr_offset - prev_offset; + int padded_size = ceil_div(group_size, padding_size) * padding_size; + start_idx += padded_size; + } + return start_idx; +} + +/** + * Pipelined kernel for rearranging row-major scale data to blocked layout. + * + * Template parameters: + * - CHUNK_WIDTH: Width of each chunk (16, 32, 64, or 128 columns) + * - CHUNKS_PER_TB: Number of chunks per superblock (1, 4, 8, or 16) + * + * Grid dimensions: + * - blockIdx.x = column chunk index + * - blockIdx.y = row superblock index + * + * Thread block dimensions: + * - 128 threads for CHUNK_WIDTH=16 (128 rows × 1 thread/row) + * - 256 threads for CHUNK_WIDTH=32 (128 rows × 2 threads/row) + * - 512 threads for CHUNK_WIDTH=64 (128 rows × 4 threads/row) + * - 1024 threads for CHUNK_WIDTH=128 (128 rows × 8 threads/row) + */ +template +__global__ void mx_blocked_layout_2d_M_groups_kernel( + const uint8_t* __restrict__ input_scales, + const int input_scale_stride_dim0, + const int scale_rows, + const int scale_cols, + const int padded_rows, + const int32_t* __restrict__ input_group_end_offsets, + uint8_t* __restrict__ output_scales, + const int output_stride_per_row_of_sf_tiles, + const int num_groups, + const __grid_constant__ CUtensorMap input_tensor_map +) { + constexpr int output_stride_per_sf_tile = SF_ROWS * SF_COLS; // 512 bytes per SF tile + const int row_superblock_pid = blockIdx.y; + const int col_chunk_pid = blockIdx.x; + const int tid = threadIdx.x; + const bool is_master_thread = tid == 0; + constexpr int THREADS_PER_ROW = CHUNK_WIDTH / BYTES_PER_THREAD; + const int row_idx = tid / THREADS_PER_ROW; + const int col_idx = tid % THREADS_PER_ROW; + + constexpr int CHUNK_SIZE_BYTES = SF_ROWS * CHUNK_WIDTH; + + __shared__ int smem_group_data[64]; // Max 32 groups: [0..31] = superblocks per group, [32..63] = cumsum + __shared__ __align__(128) uint8_t smem_buffers[NUM_BUFFERS][CHUNK_SIZE_BYTES]; + + // Find which group this superblock belongs to and compute offsets + int group_idx; + int superblock_idx_in_group; + int superblocks_until_end; + find_group_and_local_offset_for_superblock( + row_superblock_pid, + input_group_end_offsets, + num_groups, + smem_group_data, + group_idx, + superblock_idx_in_group, + superblocks_until_end + ); + + // Early exit for padding superblocks beyond all groups + if (superblocks_until_end <= 0) { + return; + } + + // Thread 0 computes group boundaries and broadcasts via SMEM + __shared__ int s_input_group_start_row; + __shared__ int s_input_group_end_row; + __shared__ int s_output_group_start_row; + if (tid == 0) { + s_input_group_start_row = (group_idx > 0) ? input_group_end_offsets[group_idx - 1] : 0; + s_input_group_end_row = input_group_end_offsets[group_idx]; + s_output_group_start_row = compute_output_group_start_row( + group_idx, input_group_end_offsets, num_groups, SF_ROWS); + } + __syncthreads(); + uint input_group_start_row = s_input_group_start_row; + uint input_group_end_row = s_input_group_end_row; + uint output_group_start_row = s_output_group_start_row; + + // Compute base addresses for this superblock + constexpr int SUPERBLOCK_ROWS = SF_ROWS * CHUNKS_PER_TB; + const uint global_row_base = input_group_start_row + (superblock_idx_in_group * SUPERBLOCK_ROWS); + const uint global_col_base = col_chunk_pid * CHUNK_WIDTH; + + // Thread's column offset and first SF tile index + const uint thread_col_start = col_idx * BYTES_PER_THREAD; + const uint first_sf_tile_idx = thread_col_start / SF_COLS; + + // Initialize mbarriers for TMA load coordination + constexpr int NUM_THREADS = SF_ROWS * THREADS_PER_ROW; + __shared__ __align__(8) uint64_t mbar[NUM_BUFFERS]; + initialize_barriers(mbar, is_master_thread); + + // Track barrier parity for double-buffered pipeline + int buf_parity[NUM_BUFFERS] = {0}; + + // Compute columns in this chunk (may be less than CHUNK_WIDTH for partial chunks) + // This is used for SMEM read stride and output bounds checking + // NOTE: TMA always loads the full tensor map box size regardless of this value + auto compute_cols_in_chunk = [&]() -> int { + const int remaining_cols = scale_cols - global_col_base; + return min(CHUNK_WIDTH, remaining_cols); + }; + const int cols_in_chunk = compute_cols_in_chunk(); + + // The tensor map box width is min(CHUNK_WIDTH, scale_cols) + // TMA always loads this full box size (with OOB elements zero-filled) + const int tma_box_width = min(CHUNK_WIDTH, scale_cols); + + // Func for async TMA load of a chunk of data to the given SMEM buffer + auto load_chunk = [&](int chunk_idx, int buf_idx) { + if (chunk_idx >= NUM_BUFFERS) { + // Wait for pending TMA stores to finish reading the SMEM buffer we're about to re-use + ptx::cp_async_bulk_wait_group_read<0>(); + __syncthreads(); + } + + uint64_t* mbar_ptr = &mbar[buf_idx]; + const uint32_t tma_x = global_col_base; + const uint32_t tma_y = global_row_base + (chunk_idx * SF_ROWS); + + // IMPORTANT: TMA with OOB_FILL_NONE zero-fills OOB elements but reports + // the FULL box size to mbarrier, not the clamped size. The box size is + // fixed in the tensor map descriptor as (tma_box_width x SF_ROWS). + const int expected_bytes = SF_ROWS * tma_box_width; + + copy_2d_to_shared( + (void*)&smem_buffers[buf_idx], + reinterpret_cast(&input_tensor_map), + tma_x, + tma_y, + expected_bytes, + mbar_ptr, + is_master_thread + ); + }; + + // Precompute blocked layout offset for this thread's row + int r_div_32 = row_idx >> 5; // row_idx / 32 + int r_mod_32 = row_idx & 31; // row_idx % 32 + int blocked_layout_row_offset = (r_mod_32 << 4) + (r_div_32 << 2); // r_mod_32 * 16 + r_div_32 * 4 + + // Func to process blocked layout transform in SMEM then store result to GMEM + auto process_chunk = [&](int chunk_idx, int buf_idx) { + // Wait for TMA load to complete + uint64_t* mbar_ptr = &mbar[buf_idx]; + ptx::mbarrier_wait_parity(mbar_ptr, buf_parity[buf_idx]); + buf_parity[buf_idx] ^= 1; + + // Fence to ensure TMA-written data is visible to all threads + ptx::fence_proxy_async_shared_cta(); + + // Read 16 bytes from row-major layout in SMEM. Coalesced, vectorized reads. + // TMA writes rows with stride = tma_box_width (the tensor map box size) + uint4 row_data = make_uint4(0, 0, 0, 0); + const uint32_t chunk_start_row = global_row_base + (chunk_idx * SF_ROWS); + const bool row_valid = chunk_start_row + row_idx < input_group_end_row; + const bool col_valid = thread_col_start < static_cast(cols_in_chunk); + + if (row_valid && col_valid) { + row_data = *reinterpret_cast( + &smem_buffers[buf_idx][row_idx * tma_box_width + thread_col_start]); + } + __syncthreads(); // All threads must finish reading before overwriting + + // Scatter 16 bytes to blocked layout (4 bytes per SF tile) + // Only write to SMEM if this thread's columns are within the valid range + constexpr int SF_TILES_PER_THREAD = BYTES_PER_THREAD / SF_COLS; + if (col_valid) { + #pragma unroll + for (int i = 0; i < SF_TILES_PER_THREAD; i++) { + const int sf_tile_idx = first_sf_tile_idx + i; + const uint32_t data = reinterpret_cast(&row_data)[i]; + *reinterpret_cast( + &smem_buffers[buf_idx][blocked_layout_row_offset + sf_tile_idx * output_stride_per_sf_tile] + ) = data; + } + } + __syncthreads(); + + // Fence to ensure SMEM writes are visible to TMA async proxy + ptx::fence_proxy_async_shared_cta(); + + // Compute output tile coordinates + const int chunk_sf_row_tile = (superblock_idx_in_group * CHUNKS_PER_TB) + chunk_idx; + const int global_sf_row_tile = (output_group_start_row / SF_ROWS) + chunk_sf_row_tile; + + // Number of valid SF tiles horizontally in this chunk (may be fewer for partial chunks) + const int valid_sf_tiles = ceil_div(cols_in_chunk, SF_COLS); + constexpr int SF_TILES_PER_CHUNK = CHUNK_WIDTH / SF_COLS; // Max tiles for full chunk + const int col_sf_tile_start = col_chunk_pid * SF_TILES_PER_CHUNK; + + // Check if this chunk has valid data + const uint32_t rows_remaining_in_group = (input_group_end_row > chunk_start_row) + ? (input_group_end_row - chunk_start_row) : 0; + + // Issue TMA 1D stores for each valid SF tile + // Each store moves one 512-byte SF tile from SMEM to GMEM + if (rows_remaining_in_group > 0 && is_master_thread) { + constexpr int SF_TILE_SIZE_BYTES = SF_ROWS * SF_COLS; // 512 bytes + const int sf_tiles_per_row = output_stride_per_row_of_sf_tiles / output_stride_per_sf_tile; + + // Only store valid SF tiles (not the full CHUNK_WIDTH for partial chunks) + for (int tile = 0; tile < valid_sf_tiles; tile++) { + const int col_sf_tile = col_sf_tile_start + tile; + const int linear_sf_tile_idx = global_sf_row_tile * sf_tiles_per_row + col_sf_tile; + + uint64_t* dst_gmem = reinterpret_cast( + output_scales + linear_sf_tile_idx * SF_TILE_SIZE_BYTES); + const uint32_t smem_sf_tile_offset = tile * SF_TILE_SIZE_BYTES; + + ptx::cp_async_bulk_tensor_1d_shared_to_global( + dst_gmem, + reinterpret_cast(&smem_buffers[buf_idx][smem_sf_tile_offset]), + SF_TILE_SIZE_BYTES + ); + } + ptx::cp_async_bulk_commit_group(); + } + }; + + // --- Main processing loop for superblock --- + // Compute how many chunks to process in this superblock + constexpr int BUFFER_MOD = NUM_BUFFERS - 1; + const int first_row_in_superblock = input_group_start_row + (superblock_idx_in_group * SUPERBLOCK_ROWS); + const int remaining_rows_in_group = input_group_end_row - first_row_in_superblock; + const int remaining_chunks = ceil_div(remaining_rows_in_group, SF_ROWS); + const int chunks_to_process = min(CHUNKS_PER_TB, remaining_chunks); + + if (chunks_to_process == 0) { + destroy_barriers(mbar, is_master_thread); + return; + } + + // Pipeline to overlap loads of chunk N+1 with process + store of chunk N + for (int chunk = 0; chunk < chunks_to_process; chunk++) { + int buf_idx = chunk & BUFFER_MOD; // chunk % num_buffers + load_chunk(chunk, buf_idx); + if (chunk > 0) { + int prev_buf_idx = (chunk - 1) & BUFFER_MOD; // (chunk - 1) % num_buffers + process_chunk(chunk - 1, prev_buf_idx); + } + } + + // Process last chunk + int last_buf_idx = (chunks_to_process - 1) & BUFFER_MOD; + process_chunk(chunks_to_process - 1, last_buf_idx); + + // Wait for all pending TMA stores to complete before exiting + ptx::cp_async_bulk_wait_group(); + + // Clean up barriers + destroy_barriers(mbar, is_master_thread); +} + +// Reference: https://docs.nvidia.com/cuda/cuda-c-programming-guide/#using-tma-to-transfer-multi-dimensional-arrays +void create_tensor_map( + void* tensor_ptr, + CUtensorMap& tensor_map, + const uint64_t gmem_width, + const uint64_t gmem_height, + const uint32_t smem_width, + const uint32_t smem_height +) { + // Validate tensor pointer + if (tensor_ptr == nullptr) { + fprintf(stderr, "ERROR: tensor_ptr is NULL!\n"); + exit(EXIT_FAILURE); + } + + constexpr uint32_t rank = 2; + uint64_t size[rank] = {gmem_width, gmem_height}; + uint64_t stride[rank - 1] = {gmem_width}; // Row major, 1 byte per e8m0 + uint32_t box_size[rank] = {smem_width, smem_height}; + uint32_t elem_stride[rank] = {1, 1}; + + // Validate TMA requirements for 2D transfers + // Reference: https://docs.nvidia.com/cuda/archive/12.6.3/cuda-driver-api/group__CUDA__TENSOR__MEMORY.html + // For 2D TMA transfers, the stride must be a multiple of 16 bytes. + // Since we use row-major layout with stride[0] = gmem_width (in bytes), gmem_width must be divisible by 16. + if (gmem_width % 16 != 0) { + fprintf(stderr, "ERROR: TMA requirement for 2D transfers: stride must be a multiple of 16 bytes.\n"); + fprintf(stderr, " Current stride (gmem_width): %lu bytes (remainder: %lu)\n", + gmem_width, gmem_width % 16); + fprintf(stderr, " Requested: gmem_width=%lu, gmem_height=%lu, smem_width=%u, smem_height=%u\n", + gmem_width, gmem_height, smem_width, smem_height); + fprintf(stderr, " For row-major layout, stride[0] = gmem_width must be divisible by 16.\n"); + fprintf(stderr, " Consider using Triton kernel instead with use_cuda_kernel_for_blocked_layout=False.\n"); + exit(EXIT_FAILURE); + } + + void *driver_ptr = get_driver_ptr(); + auto cuTensorMapEncodeTiled = reinterpret_cast(driver_ptr); + + CUresult res = cuTensorMapEncodeTiled( + &tensor_map, + CUtensorMapDataType::CU_TENSOR_MAP_DATA_TYPE_UINT8, + rank, + tensor_ptr, + size, + stride, + box_size, + elem_stride, + CUtensorMapInterleave::CU_TENSOR_MAP_INTERLEAVE_NONE, + CUtensorMapSwizzle::CU_TENSOR_MAP_SWIZZLE_NONE, + CUtensorMapL2promotion::CU_TENSOR_MAP_L2_PROMOTION_NONE, + CUtensorMapFloatOOBfill::CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE + ); + CUDA_CHECK(res); +} + + +namespace mxfp8 { + +void launch_mx_block_rearrange_2d_M_groups_cuda( + const uint8_t* scales_ptr, + int scale_stride_dim0, + int scale_rows, + int scale_cols, + int padded_rows, + const int32_t* input_group_end_offsets, + uint8_t* output_scales_ptr, + int num_groups, + int chunk_width, + int chunks_per_tb, // Chunks per superblock: 4, 8, or 16 + cudaStream_t stream +) { + // Calculate grid dimensions + int rows_per_superblock = SF_ROWS * chunks_per_tb; + + // Upper bound on superblocks: each group may add 1 due to ceiling division + int num_row_superblocks = (scale_rows + rows_per_superblock - 1) / rows_per_superblock + num_groups; + int num_col_chunks = (scale_cols + chunk_width - 1) / chunk_width; + + // Output strides for SF tile addressing + int sf_tiles_per_row = (scale_cols + SF_COLS - 1) / SF_COLS; + int output_stride_per_sf_tile = SF_ROWS * SF_COLS; // 512 bytes + int output_stride_per_row_of_sf_tiles = output_stride_per_sf_tile * sf_tiles_per_row; + + // Create TMA tensor map for input (chunk size = SF_ROWS × effective_chunk_width) + // When scale_cols < chunk_width, use scale_cols as box width to avoid OOB issues + const int effective_chunk_width = min(chunk_width, scale_cols); + alignas(128) CUtensorMap input_tensor_map = {}; + create_tensor_map( + (void*)scales_ptr, + input_tensor_map, + scale_cols, + scale_rows, + effective_chunk_width, + SF_ROWS + ); + + dim3 grid(num_col_chunks, num_row_superblocks); + + if (chunk_width == 16) { + dim3 block(128); // 128 rows × 1 thread/row + switch (chunks_per_tb) { + case 1: + mx_blocked_layout_2d_M_groups_kernel<16, 1><<>>( + scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows, + input_group_end_offsets, output_scales_ptr, + output_stride_per_row_of_sf_tiles, + num_groups, input_tensor_map); + break; + case 4: + mx_blocked_layout_2d_M_groups_kernel<16, 4><<>>( + scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows, + input_group_end_offsets, output_scales_ptr, + output_stride_per_row_of_sf_tiles, + num_groups, input_tensor_map); + break; + case 8: + mx_blocked_layout_2d_M_groups_kernel<16, 8><<>>( + scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows, + input_group_end_offsets, output_scales_ptr, + output_stride_per_row_of_sf_tiles, + num_groups, input_tensor_map); + break; + case 16: + mx_blocked_layout_2d_M_groups_kernel<16, 16><<>>( + scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows, + input_group_end_offsets, output_scales_ptr, + output_stride_per_row_of_sf_tiles, + num_groups, input_tensor_map); + break; + default: + printf("CUDA Error: chunks_per_tb must be 1, 4, 8, or 16, got %d\n", chunks_per_tb); + return; + } + } else if (chunk_width == 32) { + dim3 block(256); // 128 rows × 2 threads/row + switch (chunks_per_tb) { + case 1: + mx_blocked_layout_2d_M_groups_kernel<32, 1><<>>( + scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows, + input_group_end_offsets, output_scales_ptr, + output_stride_per_row_of_sf_tiles, + num_groups, input_tensor_map); + break; + case 4: + mx_blocked_layout_2d_M_groups_kernel<32, 4><<>>( + scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows, + input_group_end_offsets, output_scales_ptr, + output_stride_per_row_of_sf_tiles, + num_groups, input_tensor_map); + break; + case 8: + mx_blocked_layout_2d_M_groups_kernel<32, 8><<>>( + scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows, + input_group_end_offsets, output_scales_ptr, + output_stride_per_row_of_sf_tiles, + num_groups, input_tensor_map); + break; + case 16: + mx_blocked_layout_2d_M_groups_kernel<32, 16><<>>( + scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows, + input_group_end_offsets, output_scales_ptr, + output_stride_per_row_of_sf_tiles, + num_groups, input_tensor_map); + break; + default: + printf("CUDA Error: chunks_per_tb must be 1, 4, 8, or 16, got %d\n", chunks_per_tb); + return; + } + } else if (chunk_width == 64) { + dim3 block(512); // 128 rows × 4 threads/row + switch (chunks_per_tb) { + case 1: + mx_blocked_layout_2d_M_groups_kernel<64, 1><<>>( + scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows, + input_group_end_offsets, output_scales_ptr, + output_stride_per_row_of_sf_tiles, + num_groups, input_tensor_map); + break; + case 4: + mx_blocked_layout_2d_M_groups_kernel<64, 4><<>>( + scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows, + input_group_end_offsets, output_scales_ptr, + output_stride_per_row_of_sf_tiles, + num_groups, input_tensor_map); + break; + case 8: + mx_blocked_layout_2d_M_groups_kernel<64, 8><<>>( + scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows, + input_group_end_offsets, output_scales_ptr, + output_stride_per_row_of_sf_tiles, + num_groups, input_tensor_map); + break; + case 16: + mx_blocked_layout_2d_M_groups_kernel<64, 16><<>>( + scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows, + input_group_end_offsets, output_scales_ptr, + output_stride_per_row_of_sf_tiles, + num_groups, input_tensor_map); + break; + default: + printf("CUDA Error: chunks_per_tb must be 1, 4, 8, or 16, got %d\n", chunks_per_tb); + return; + } + } else if (chunk_width == 128) { + dim3 block(1024); // 128 rows × 8 threads/row + switch (chunks_per_tb) { + case 1: + mx_blocked_layout_2d_M_groups_kernel<128, 1><<>>( + scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows, + input_group_end_offsets, output_scales_ptr, + output_stride_per_row_of_sf_tiles, + num_groups, input_tensor_map); + break; + case 4: + mx_blocked_layout_2d_M_groups_kernel<128, 4><<>>( + scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows, + input_group_end_offsets, output_scales_ptr, + output_stride_per_row_of_sf_tiles, + num_groups, input_tensor_map); + break; + case 8: + mx_blocked_layout_2d_M_groups_kernel<128, 8><<>>( + scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows, + input_group_end_offsets, output_scales_ptr, + output_stride_per_row_of_sf_tiles, + num_groups, input_tensor_map); + break; + case 16: + mx_blocked_layout_2d_M_groups_kernel<128, 16><<>>( + scales_ptr, scale_stride_dim0, scale_rows, scale_cols, padded_rows, + input_group_end_offsets, output_scales_ptr, + output_stride_per_row_of_sf_tiles, + num_groups, input_tensor_map); + break; + default: + printf("CUDA Error: chunks_per_tb must be 1, 4, 8, or 16, got %d\n", chunks_per_tb); + return; + } + } else { + printf("CUDA Error: chunk_width must be 16, 32, 64, or 128, got %d\n", chunk_width); + return; + } +} + +// Non-pipelined kernel without TMA for loads, but uses TMA for stores +// Handles M-groups with one chunk per threadblock (equivalent to CHUNKS_PER_TB=1) +// Assumes input tensor is contiguous/row-major (stride = scale_cols) +template +__global__ void mx_blocked_layout_2d_simple_kernel( + const uint8_t* __restrict__ input_scales, + const int scale_rows, + const int scale_cols, + const int32_t* __restrict__ input_group_end_offsets, + uint8_t* __restrict__ output_scales, + const int output_stride_per_row_of_sf_tiles, + const int num_groups +) { + constexpr int THREADS_PER_ROW = CHUNK_WIDTH / BYTES_PER_THREAD; + constexpr int SF_TILES_PER_THREAD = BYTES_PER_THREAD / SF_COLS; // 4 tiles per thread + constexpr int SF_TILES_PER_CHUNK = CHUNK_WIDTH / SF_COLS; + constexpr int OUTPUT_STRIDE_PER_SF_TILE = SF_ROWS * SF_COLS; // 512 bytes + constexpr int CHUNK_SIZE_BYTES = SF_ROWS * CHUNK_WIDTH; + + const int row_chunk_pid = blockIdx.y; // Each chunk is one superblock with CHUNKS_PER_TB=1 + const int col_chunk_pid = blockIdx.x; + const int tid = threadIdx.x; + const int row_idx = tid / THREADS_PER_ROW; + const int col_idx = tid % THREADS_PER_ROW; + const bool is_master_thread = tid == 0; + + // Shared memory: group offset computation + data buffer for blocked layout + __shared__ int smem_group_data[64]; // Max 32 groups: [0..31] = chunks per group, [32..63] = cumsum + __shared__ __align__(128) uint8_t smem_chunk_buffer[CHUNK_SIZE_BYTES]; + + // Find which group this chunk belongs to (using CHUNKS_PER_TB=1) + int group_idx; + int chunk_idx_in_group; + int chunks_until_end; + find_group_and_local_offset_for_superblock<1>( // 1 chunk per superblock (i.e., 1 chunk per threadblock) since we aren't pipelining + row_chunk_pid, + input_group_end_offsets, + num_groups, + smem_group_data, + group_idx, + chunk_idx_in_group, + chunks_until_end + ); + + // Early exit for padding chunks beyond all groups + if (chunks_until_end <= 0) { + return; + } + + // Thread 0 computes group boundaries and broadcasts via SMEM + __shared__ int s_input_group_start_row; + __shared__ int s_input_group_end_row; + __shared__ int s_output_group_start_row; + if (tid == 0) { + s_input_group_start_row = (group_idx > 0) ? input_group_end_offsets[group_idx - 1] : 0; + s_input_group_end_row = input_group_end_offsets[group_idx]; + s_output_group_start_row = compute_output_group_start_row( + group_idx, input_group_end_offsets, num_groups, SF_ROWS); + } + __syncthreads(); + const int input_group_start_row = s_input_group_start_row; + const int input_group_end_row = s_input_group_end_row; + const int output_group_start_row = s_output_group_start_row; + + // Compute input row for this thread (within the group) + const int chunk_start_row = input_group_start_row + (chunk_idx_in_group * SF_ROWS); + const int global_row = chunk_start_row + row_idx; + const int global_col_base = col_chunk_pid * CHUNK_WIDTH + col_idx * BYTES_PER_THREAD; + + // Check if this is a valid row (not a padding row) + const bool row_valid = global_row < input_group_end_row && global_row < scale_rows; + + // Load data with vectorized loads, falling back to smaller loads at boundaries + // For padding rows, row_data stays zero (important for correct padding in output) + uint4 row_data = make_uint4(0, 0, 0, 0); + const uint8_t* read_ptr = input_scales + global_row * scale_cols + global_col_base; + + // TODO: the efficiency of loads can be improved but the kernel is already several times faster + // than Triton and we are going to port these to CuteDSL anyway so don't want to sink more time into this. + // Problem: this code will often result in single byte loads when stride is not a multiple of 16/8, + // because many reads will not meet alignment requirements for vectorized loads. + // We also can't use 2d TMA to read 128xCHUNK_SIZE chunks because 2d tma also requires global stride by multiple of 16 bytes. + if (row_valid) { + // Check alignment and bounds for vectorized loads + const bool is_aligned_16 = (reinterpret_cast(read_ptr) % 16) == 0; + const bool is_aligned_8 = (reinterpret_cast(read_ptr) % 8) == 0; + + if (global_col_base + 16 <= scale_cols && is_aligned_16) { + // Can safely load 16 bytes (int4) with proper alignment + row_data = *reinterpret_cast(read_ptr); + } else if (global_col_base + 8 <= scale_cols && is_aligned_8) { + // Can safely load 8 bytes (int2) with proper alignment + int2 data = *reinterpret_cast(read_ptr); + row_data.x = data.x; + row_data.y = data.y; + // Load remaining bytes individually if needed + const int remaining = scale_cols - (global_col_base + 8); + #pragma unroll + for (int i = 0; i < remaining && i < 8; i++) { + reinterpret_cast(&row_data)[8 + i] = read_ptr[8 + i]; + } + } else if (global_col_base < scale_cols) { + // Load remaining bytes individually (unaligned or small) + const int remaining = min(16, scale_cols - global_col_base); + #pragma unroll + for (int i = 0; i < remaining; i++) { + reinterpret_cast(&row_data)[i] = read_ptr[i]; + } + } + } + + // Compute blocked layout position within SF tile + // The blocked layout groups rows into blocks of 32 + int r_div_32 = row_idx >> 5; // row_idx / 32 + int r_mod_32 = row_idx & 31; // row_idx % 32 + int blocked_layout_row_offset = (r_mod_32 << 4) + (r_div_32 << 2); // r_mod_32 * 16 + r_div_32 * 4 + + // Compute SF tile indices for this thread + const int thread_col_start = col_idx * BYTES_PER_THREAD; + const int first_sf_tile_idx = thread_col_start / SF_COLS; + + // Compute output tile coordinates (accounting for group padding) + const int chunk_sf_tile_col_base = col_chunk_pid * SF_TILES_PER_CHUNK; + const int chunk_sf_tile_row = (output_group_start_row / SF_ROWS) + chunk_idx_in_group; + const int sf_tiles_per_row = output_stride_per_row_of_sf_tiles / OUTPUT_STRIDE_PER_SF_TILE; + + // Compute columns in this chunk (based on chunk start, not thread start) + const int chunk_col_base = col_chunk_pid * CHUNK_WIDTH; + const int remaining_cols_in_chunk = scale_cols - chunk_col_base; + const int cols_in_chunk = (remaining_cols_in_chunk < CHUNK_WIDTH) ? remaining_cols_in_chunk : CHUNK_WIDTH; + + // Scatter 16 bytes to SMEM in blocked layout (4 bytes per SF tile) + // Each thread writes 4 separate 4-byte chunks to different SF tiles in SMEM + // NOTE: this will cause bank conflicts but resolving them would prevent us + // from doing direct TMA stores for 128x4=512b contiguous bytes, which is worse in my prev experiments + #pragma unroll + for (int i = 0; i < SF_TILES_PER_THREAD; i++) { + // Check if this SF tile column is within bounds + if ((first_sf_tile_idx + i) * SF_COLS < cols_in_chunk) { + const uint32_t data = reinterpret_cast(&row_data)[i]; + // Offset within the SMEM chunk buffer for this SF tile + const int sf_tile_offset_in_chunk = (first_sf_tile_idx + i) * OUTPUT_STRIDE_PER_SF_TILE; + *reinterpret_cast(&smem_chunk_buffer[sf_tile_offset_in_chunk + blocked_layout_row_offset]) = data; + } + } + + // Ensure threads finish their smem writes and use explicit fence to ensure visibility to async proxy for TMA + __syncthreads(); + ptx::fence_proxy_async_shared_cta(); + + if (is_master_thread) { + // Issue separate 1D TMA stores for each valid SF tile + // Each store moves one 512-byte SF tile from SMEM to GMEM + constexpr int SF_TILE_SIZE_BYTES = SF_ROWS * SF_COLS; // 512 bytes + const int num_valid_sf_tiles = (cols_in_chunk + SF_COLS - 1) / SF_COLS; + + // Loop over each SF tile and do a separate TMA transfer + for (int tile = 0; tile < num_valid_sf_tiles; tile++) { + const int col_sf_tile = chunk_sf_tile_col_base + tile; + const int linear_sf_tile_idx = chunk_sf_tile_row * sf_tiles_per_row + col_sf_tile; + + uint64_t* dst_gmem = reinterpret_cast( + output_scales + linear_sf_tile_idx * SF_TILE_SIZE_BYTES); + const int smem_sf_tile_offset = tile * SF_TILE_SIZE_BYTES; + + ptx::cp_async_bulk_tensor_1d_shared_to_global( + dst_gmem, + reinterpret_cast(&smem_chunk_buffer[smem_sf_tile_offset]), + SF_TILE_SIZE_BYTES + ); + } + ptx::cp_async_bulk_commit_group(); + } + + // Wait for TMA transfer to complete + ptx::cp_async_bulk_wait_group(); +} + + +void launch_mx_block_rearrange_2d_simple_cuda( + const uint8_t* scales_ptr, + int scale_rows, + int scale_cols, + const int32_t* input_group_end_offsets, + uint8_t* output_scales_ptr, + int num_groups, + int chunk_width, + cudaStream_t stream +) { + // Calculate grid dimensions (upper bound to account for group padding) + int num_row_chunks = (scale_rows + SF_ROWS - 1) / SF_ROWS + num_groups; + int num_col_chunks = (scale_cols + chunk_width - 1) / chunk_width; + + // Output strides for SF tile addressing + int sf_tiles_per_row = (scale_cols + SF_COLS - 1) / SF_COLS; + int output_stride_per_sf_tile = SF_ROWS * SF_COLS; // 512 bytes + int output_stride_per_row_of_sf_tiles = output_stride_per_sf_tile * sf_tiles_per_row; + + dim3 grid(num_col_chunks, num_row_chunks); + + // Launch appropriate kernel based on chunk width + if (chunk_width == 16) { + dim3 block(128); // 128 rows × 1 thread/row + mx_blocked_layout_2d_simple_kernel<16><<>>( + scales_ptr, scale_rows, scale_cols, + input_group_end_offsets, output_scales_ptr, + output_stride_per_row_of_sf_tiles, num_groups); + } else if (chunk_width == 32) { + dim3 block(256); // 128 rows × 2 threads/row + mx_blocked_layout_2d_simple_kernel<32><<>>( + scales_ptr, scale_rows, scale_cols, + input_group_end_offsets, output_scales_ptr, + output_stride_per_row_of_sf_tiles, num_groups); + } else if (chunk_width == 64) { + dim3 block(512); // 128 rows × 4 threads/row + mx_blocked_layout_2d_simple_kernel<64><<>>( + scales_ptr, scale_rows, scale_cols, + input_group_end_offsets, output_scales_ptr, + output_stride_per_row_of_sf_tiles, num_groups); + } else if (chunk_width == 128) { + dim3 block(1024); // 128 rows × 8 threads/row + mx_blocked_layout_2d_simple_kernel<128><<>>( + scales_ptr, scale_rows, scale_cols, + input_group_end_offsets, output_scales_ptr, + output_stride_per_row_of_sf_tiles, num_groups); + } else { + fprintf(stderr, "CUDA Error: chunk_width must be 16, 32, 64, or 128, got %d\n", chunk_width); + return; + } + + // Check for launch errors + cudaError_t err = cudaGetLastError(); + if (err != cudaSuccess) { + fprintf(stderr, "CUDA kernel launch error: %s\n", cudaGetErrorString(err)); + } +} + +} // namespace mxfp8 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/mx_kernels/mxfp8_cuda.cu b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/mx_kernels/mxfp8_cuda.cu new file mode 100644 index 0000000000000000000000000000000000000000..4a1257a5dd07a1b27d9d49ebcc6208a64ebf2e68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/mx_kernels/mxfp8_cuda.cu @@ -0,0 +1,131 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD 3-Clause license found in the +// LICENSE file in the root directory of this source tree. + +// CUDA bridge for MXFP8 quantization + +#include "mxfp8_quantize.cuh" + +#include +#include +#include +#include +#include + +#include +#include + +using torch::stable::Tensor; + +namespace mxfp8 { + +// Convert PyTorch scalar type to our DType enum +DType get_input_dtype(const Tensor &t) { + switch (t.scalar_type()) { + case torch::headeronly::ScalarType::Float: + return DType::kFloat32; + case torch::headeronly::ScalarType::Half: + return DType::kFloat16; + case torch::headeronly::ScalarType::BFloat16: + return DType::kBFloat16; + case torch::headeronly::ScalarType::Byte: + return DType::kByte; + default: + STD_TORCH_CHECK(false, "Unsupported input tensor dtype: ", t.scalar_type()); + } +} + +ScaleCalculationMode get_scaling_mode(const std::string &scaling_mode) { + if (scaling_mode.compare("floor") == 0) { + return ScaleCalculationMode::FLOOR; + } else if (scaling_mode.compare("rceil") == 0) { + return ScaleCalculationMode::RCEIL; + } else { + STD_TORCH_CHECK(false, "Unsupported scaling mode: ", scaling_mode, ". Only ['floor', 'rceil'] are supported."); + } +} + +// Convert FP8 format string to DType enum +DType get_output_dtype(const std::string &fp8_format) { + if (fp8_format.compare("e4m3") == 0) { + return DType::kFloat8E4M3; + } else { + STD_TORCH_CHECK(false, "Unsupported FP8 format: ", fp8_format, + ". Only 'e4m3' is supported."); + } +} + +void mxfp8_quantize_cuda(const Tensor &input, + Tensor &output_rowwise, + Tensor &output_colwise, + Tensor &scales_rowwise, + Tensor &scales_colwise, + int64_t scale_dim_x, + int64_t scale_dim_y, + const std::string &fp8_format, + const std::string &scaling_mode) { + + // Get tensor properties + const int64_t rows = input.size(0); + const int64_t cols = input.size(1); + + // Get data pointers + const void *input_ptr = input.data_ptr(); + void *output_rowwise_ptr = + output_rowwise.numel() > 0 ? output_rowwise.data_ptr() : nullptr; + void *output_colwise_ptr = + output_colwise.numel() > 0 ? output_colwise.data_ptr() : nullptr; + e8m0_t *scales_rowwise_ptr = + scales_rowwise.numel() > 0 + ? reinterpret_cast(scales_rowwise.data_ptr()) + : nullptr; + e8m0_t *scales_colwise_ptr = + scales_colwise.numel() > 0 + ? reinterpret_cast(scales_colwise.data_ptr()) + : nullptr; + + // Get CUDA stream using stable ABI + void* stream_ptr = nullptr; + TORCH_ERROR_CODE_CHECK(aoti_torch_get_current_cuda_stream(input.get_device_index(), &stream_ptr)); + cudaStream_t stream = static_cast(stream_ptr); + + // Get strides of scale ptrs (guard against 1D empty tensors when rowwise/colwise is false) + int64_t scale_rowwise_stride_dim0 = scales_rowwise.dim() >= 2 ? scales_rowwise.stride(0) : 0; + int64_t scale_rowwise_stride_dim1 = scales_rowwise.dim() >= 2 ? scales_rowwise.stride(1) : 0; + int64_t scale_colwise_stride_dim0 = scales_colwise.dim() >= 2 ? scales_colwise.stride(0) : 0; + int64_t scale_colwise_stride_dim1 = scales_colwise.dim() >= 2 ? scales_colwise.stride(1) : 0; + +#if defined(DEBUG) + printf("mxfp8_quantize_cuda:\n"); + printf("Quantizing input tensor of size %ld x %ld\n", rows, cols); + printf("scaling_mode: %s\n", scaling_mode.c_str()); + printf("Scale dim x: %ld\n", scale_dim_x); + printf("Scale dim y: %ld\n", scale_dim_y); + printf("Rowwise scale shape: %ld x %ld\n", + scales_rowwise.dim() >= 1 ? scales_rowwise.size(0) : 0, + scales_rowwise.dim() >= 2 ? scales_rowwise.size(1) : 0); + printf("Colwise scale shape: %ld x %ld\n", + scales_colwise.dim() >= 1 ? scales_colwise.size(0) : 0, + scales_colwise.dim() >= 2 ? scales_colwise.size(1) : 0); + printf("scale_rowwise_stride_dim0 = %ld\n", scale_rowwise_stride_dim0); + printf("scale_rowwise_stride_dim1 = %ld\n", scale_rowwise_stride_dim1); + printf("scale_colwise_stride_dim0 = %ld\n", scale_colwise_stride_dim0); + printf("scale_colwise_stride_dim1 = %ld\n", scale_colwise_stride_dim1); +#endif + + // Call the quantization kernel + MXFP8Quantizer::quantize(input_ptr, + output_rowwise_ptr, output_colwise_ptr, + scales_rowwise_ptr, scales_colwise_ptr, + scale_rowwise_stride_dim0, scale_rowwise_stride_dim1, + scale_colwise_stride_dim0, scale_colwise_stride_dim1, + rows, cols, + get_input_dtype(input), get_output_dtype(fp8_format), + scale_dim_x, scale_dim_y, + get_scaling_mode(scaling_mode), + stream); +} + +} // namespace mxfp8 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/mx_kernels/mxfp8_extension.cpp b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/mx_kernels/mxfp8_extension.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3b62db15ad81bf9e20a6838e8acd8e1304b080a7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/mx_kernels/mxfp8_extension.cpp @@ -0,0 +1,428 @@ +// MXFP8 extension using STABLE_TORCH_LIBRARY (ABI stable) +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +using torch::stable::Tensor; +namespace tsa = torch::stable::accelerator; + +namespace mxfp8 { + +// Forward declarations +void mxfp8_quantize_cuda(const Tensor &input, + Tensor &output_rowwise, + Tensor &output_columnwise, + Tensor &scales_rowwise, + Tensor &scales_colwise, + int64_t scale_dim_x, + int64_t scale_dim_y, + const std::string &fp8_format, + const std::string &scaling_mode); + +void launch_mx_block_rearrange_2d_M_groups_cuda( + const uint8_t* scales_ptr, + int scale_stride_dim0, + int scale_rows, + int scale_cols, + int padded_rows, + const int32_t* input_group_end_offsets, + uint8_t* output_scales_ptr, + int num_groups, + int chunk_width, // Template selector: 64 or 128 + int chunks_per_tb, + cudaStream_t stream); + +void launch_mx_block_rearrange_2d_simple_cuda( + const uint8_t* scales_ptr, + int scale_rows, + int scale_cols, + const int32_t* input_group_end_offsets, + uint8_t* output_scales_ptr, + int num_groups, + int chunk_width, + cudaStream_t stream); + +void launch_compute_padded_offsets_cuda( + const int32_t* group_end_offsets_ptr, + int32_t* padded_group_start_offsets_ptr, + int32_t* padded_group_end_offsets_ptr, + int num_groups, + int alignment_size, + cudaStream_t stream); + +void launch_fused_pad_token_groups_cuda( + const void* input_ptr, + const int32_t* group_end_offsets_ptr, + const int32_t* padded_group_start_offsets_ptr, + void* output_ptr, + int num_tokens, + int dim, + int num_groups, + int dtype_size, + int dtype_enum, + cudaStream_t stream); + +void launch_fused_unpad_token_groups_cuda( + const void* input_ptr, + const int32_t* group_end_offsets_ptr, + const int32_t* padded_group_start_offsets_ptr, + void* output_ptr, + int num_tokens, + int dim, + int num_groups, + int dtype_size, + int dtype_enum, + cudaStream_t stream); + +// Helper for tensor validation +void check_cuda_tensor(const Tensor &t, const char *name) { + STD_TORCH_CHECK(t.is_cuda(), name, " must be a CUDA tensor"); + STD_TORCH_CHECK(t.is_contiguous(), name, " must be contiguous"); +} + +// Helper to validate FP8 format +void validate_fp8_format(const std::string &fp8_format) { + STD_TORCH_CHECK(fp8_format.compare("e4m3") == 0, + "fp8_format must be 'e4m3', got: ", fp8_format); +} + +// Helper to validate scale dimensions +void validate_scale_dimensions(int64_t scale_dim_x, int64_t scale_dim_y) { + STD_TORCH_CHECK(scale_dim_x == 1 || scale_dim_x == 32, + "scale_dim_x must be 1 or 32, got: ", scale_dim_x); + STD_TORCH_CHECK(scale_dim_y == 1 || scale_dim_y == 32, + "scale_dim_y must be 1 or 32, got: ", scale_dim_y); +} + +// Main quantization function +std::tuple +mxfp8_quantize(const Tensor& input, bool rowwise, bool colwise, + int64_t scale_dim_x, int64_t scale_dim_y, + const std::string &fp8_format, + const std::string &scaling_mode) { + + // Validate inputs + STD_TORCH_CHECK(!rowwise, "rowwise scaling is not supported yet"); + STD_TORCH_CHECK(input.is_cuda(), "input must be a CUDA tensor"); + STD_TORCH_CHECK(input.is_contiguous(), "input must be contiguous"); + STD_TORCH_CHECK(input.dim() == 2, "input must be 2D"); + STD_TORCH_CHECK(input.scalar_type() == torch::headeronly::ScalarType::Float || + input.scalar_type() == torch::headeronly::ScalarType::Half || + input.scalar_type() == torch::headeronly::ScalarType::BFloat16, + "Input must be float32, float16, or bfloat16"); + STD_TORCH_CHECK(rowwise || colwise, + "At least one of rowwise or colwise must be true"); + + validate_scale_dimensions(scale_dim_x, scale_dim_y); + validate_fp8_format(fp8_format); + + const int64_t rows = input.size(0); + const int64_t cols = input.size(1); + STD_TORCH_CHECK((rows >= 32) && (rows % 32 == 0), "rows must be a multiple of 32"); + STD_TORCH_CHECK((cols >= 32) && (cols % 32 == 0), "cols must be a multiple of 32"); + + tsa::DeviceGuard device_guard(input.get_device_index()); + + // Allocate output tensors + Tensor output_rowwise, output_colwise; + Tensor scales_rowwise, scales_colwise; + + if (rowwise) { + const int64_t num_col_blocks = (cols + scale_dim_x - 1) / scale_dim_x; + output_rowwise = torch::stable::new_empty(input, {rows, cols}, torch::headeronly::ScalarType::Float8_e4m3fn); + scales_rowwise = torch::stable::new_empty(input, {rows, num_col_blocks}, torch::headeronly::ScalarType::Float8_e8m0fnu); + } else { + output_rowwise = torch::stable::new_empty(input, {0}, torch::headeronly::ScalarType::Float8_e4m3fn); + scales_rowwise = torch::stable::new_empty(input, {0}, torch::headeronly::ScalarType::Float8_e8m0fnu); + } + + if (colwise) { + const int64_t num_row_blocks = (rows + scale_dim_y - 1) / scale_dim_y; + // Create column-major tensor by creating transposed shape and transposing + // We need shape {rows, cols} with strides {1, rows}, so create {cols, rows} and transpose + Tensor output_colwise_tmp = torch::stable::new_empty(input, {cols, rows}, torch::headeronly::ScalarType::Float8_e4m3fn); + output_colwise = torch::stable::transpose(output_colwise_tmp, 0, 1); + // For scales_colwise: need shape {cols, num_row_blocks} with strides {1, cols} + // Create {num_row_blocks, cols} and transpose + Tensor scales_colwise_tmp = torch::stable::new_empty(input, {num_row_blocks, cols}, torch::headeronly::ScalarType::Float8_e8m0fnu); + scales_colwise = torch::stable::transpose(scales_colwise_tmp, 0, 1); + } else { + output_colwise = torch::stable::new_empty(input, {0}, torch::headeronly::ScalarType::Float8_e4m3fn); + scales_colwise = torch::stable::new_empty(input, {0}, torch::headeronly::ScalarType::Float8_e8m0fnu); + } + + // Call CUDA kernels + mxfp8_quantize_cuda(input, + output_rowwise, output_colwise, + scales_rowwise, scales_colwise, + rowwise ? scale_dim_x : 1, // scale_dim_x + colwise ? scale_dim_y : 1, // scale_dim_y + fp8_format, scaling_mode); + + return std::make_tuple(output_rowwise, output_colwise, scales_rowwise, + scales_colwise); +} + +Tensor mx_block_rearrange_2d_M_groups( + Tensor scales_tensor, + Tensor input_group_end_offsets, + int64_t chunks_per_tb) { + + // Validate inputs + check_cuda_tensor(scales_tensor, "scales_tensor"); + check_cuda_tensor(input_group_end_offsets, "input_group_end_offsets"); + + STD_TORCH_CHECK(scales_tensor.dim() == 2, "scales_tensor must be 2D"); + STD_TORCH_CHECK(scales_tensor.is_contiguous(), "scales_tensor must be contiguous (row-major)"); + STD_TORCH_CHECK(scales_tensor.scalar_type() == torch::headeronly::ScalarType::Byte || // uint8 + scales_tensor.scalar_type() == torch::headeronly::ScalarType::Float8_e8m0fnu, + "scales_tensor must be uint8 or e8m0"); + STD_TORCH_CHECK(input_group_end_offsets.scalar_type() == torch::headeronly::ScalarType::Int, + "input_group_end_offsets must be int32"); + STD_TORCH_CHECK(input_group_end_offsets.dim() == 1, + "input_group_end_offsets must be 1D"); + STD_TORCH_CHECK(chunks_per_tb == 1 || chunks_per_tb == 4 || chunks_per_tb == 8 || chunks_per_tb == 16, + "chunks_per_tb must be 1, 4, 8, or 16, got: ", chunks_per_tb); + tsa::DeviceGuard device_guard(scales_tensor.get_device_index()); + + const int rows = scales_tensor.size(0); + const int cols = scales_tensor.size(1); + const int num_groups = input_group_end_offsets.size(0); + STD_TORCH_CHECK(num_groups <= 32, "num_groups must be <= 32"); + + // Automatically select chunk_width based on scale_cols + int chunk_width; + if (cols >= 64) { + chunk_width = 64; + } else if (cols >= 32) { + chunk_width = 32; + } else { + chunk_width = 16; + } + + // Calculate blocks needed - uses 128-row blocks + // For M groups, groups are along rows, so we pad each group to 128 rows + const int BLOCK_ROWS = 128; + const int BLOCK_COLS = 4; + + // Each group is padded to 128 rows upper bound + const int padded_rows = rows + num_groups * BLOCK_ROWS; + + // Columns are padded to multiple of BLOCK_COLS + const int num_col_blocks = (cols + BLOCK_COLS - 1) / BLOCK_COLS; + const int padded_cols = num_col_blocks * BLOCK_COLS; + + // Create output tensor + auto output = torch::stable::new_zeros(scales_tensor, {padded_rows, padded_cols}, scales_tensor.scalar_type()); + + // Get raw pointers + const uint8_t* scales_ptr = reinterpret_cast(scales_tensor.data_ptr()); + const int32_t* offsets_ptr = input_group_end_offsets.const_data_ptr(); + uint8_t* output_ptr = reinterpret_cast(output.data_ptr()); + + // Get CUDA stream using stable ABI + void* stream_ptr = nullptr; + TORCH_ERROR_CODE_CHECK(aoti_torch_get_current_cuda_stream(scales_tensor.get_device_index(), &stream_ptr)); + cudaStream_t stream = static_cast(stream_ptr); + + // pipelined kernel will be used if input meets 2d TMA constraint (cols >= 16 and cols % 16 bytes == 0) + // Otherwise, a fallback kernel will be used (slightly slower but supports any column count) + const bool can_use_pipelined_kernel = cols >= 16 && cols % 16 == 0; + if (can_use_pipelined_kernel) + { + // Launch pipelined TMA kernel + launch_mx_block_rearrange_2d_M_groups_cuda( + scales_ptr, + scales_tensor.stride(0), + rows, + cols, + padded_rows, + offsets_ptr, + output_ptr, + num_groups, + static_cast(chunk_width), + static_cast(chunks_per_tb), + stream); + } + else + { + // Launch simplified kernel (no TMA, works with any column dimension) + launch_mx_block_rearrange_2d_simple_cuda( + scales_ptr, + rows, + cols, + offsets_ptr, + output_ptr, + num_groups, + static_cast(chunk_width), + stream); + } + return output; +} + +std::tuple fused_pad_token_groups( + Tensor inputs, + Tensor group_end_offsets, + int64_t alignment_size) { + + // Validate inputs + check_cuda_tensor(inputs, "inputs"); + check_cuda_tensor(group_end_offsets, "group_end_offsets"); + + STD_TORCH_CHECK(inputs.dim() == 2, "inputs must be 2D, got: ", inputs.dim()); + STD_TORCH_CHECK(inputs.is_contiguous(), "inputs must be contiguous"); + STD_TORCH_CHECK(group_end_offsets.dim() == 1, "group_end_offsets must be 1D"); + STD_TORCH_CHECK(group_end_offsets.scalar_type() == torch::headeronly::ScalarType::Int, + "group_end_offsets must be int32"); + STD_TORCH_CHECK(inputs.scalar_type() == torch::headeronly::ScalarType::Float || + inputs.scalar_type() == torch::headeronly::ScalarType::BFloat16, + "inputs must be float32 or bfloat16"); + + tsa::DeviceGuard device_guard(inputs.get_device_index()); + + const int num_tokens = inputs.size(0); + const int dim = inputs.size(1); + const int num_groups = group_end_offsets.size(0); + + STD_TORCH_CHECK(num_groups <= 32, "num_groups must be <= 32, got: ", num_groups); + STD_TORCH_CHECK(alignment_size == 32, "alignment_size must be 32 for now"); + + // Allocate tensors for padded group offsets + Tensor padded_group_start_offsets = torch::stable::new_empty(group_end_offsets, {num_groups}, group_end_offsets.scalar_type()); + Tensor padded_group_end_offsets = torch::stable::new_empty(group_end_offsets, {num_groups}, group_end_offsets.scalar_type()); + + // Get CUDA stream using stable ABI + void* stream_ptr = nullptr; + TORCH_ERROR_CODE_CHECK(aoti_torch_get_current_cuda_stream(inputs.get_device_index(), &stream_ptr)); + cudaStream_t stream = static_cast(stream_ptr); + + // Launch GPU kernel to compute padded offsets (avoids multiple torch op launches) + launch_compute_padded_offsets_cuda( + reinterpret_cast(group_end_offsets.data_ptr()), + reinterpret_cast(padded_group_start_offsets.data_ptr()), + reinterpret_cast(padded_group_end_offsets.data_ptr()), + num_groups, + static_cast(alignment_size), + stream + ); + + // Calculate output size with upper bound padding, rounded up to alignment + // (required for quantization operations that expect aligned dimensions) + int output_rows = num_tokens + num_groups * alignment_size; + output_rows = ((output_rows + alignment_size - 1) / alignment_size) * alignment_size; + + // Allocate zero-initialized output (zeros for padding required by quantization) + Tensor output = torch::stable::new_zeros(inputs, {output_rows, dim}, inputs.scalar_type()); + + // Determine dtype parameters + int dtype_size = inputs.element_size(); + int dtype_enum = 0; // 0=fp32, 1=bf16 + if (inputs.scalar_type() == torch::headeronly::ScalarType::BFloat16) { + dtype_enum = 1; + } + + // Launch copy kernel (overwrites zeros with real data) + launch_fused_pad_token_groups_cuda( + inputs.data_ptr(), + reinterpret_cast(group_end_offsets.data_ptr()), + reinterpret_cast(padded_group_start_offsets.data_ptr()), + output.data_ptr(), + num_tokens, + dim, + num_groups, + dtype_size, + dtype_enum, + stream + ); + + return std::make_tuple(output, padded_group_start_offsets, padded_group_end_offsets); +} + +Tensor fused_unpad_token_groups( + Tensor inputs, + Tensor group_end_offsets, + Tensor padded_group_start_offsets, + int64_t num_tokens, + int64_t alignment_size) { + + // Validate inputs + check_cuda_tensor(inputs, "inputs"); + check_cuda_tensor(group_end_offsets, "group_end_offsets"); + check_cuda_tensor(padded_group_start_offsets, "padded_group_start_offsets"); + + STD_TORCH_CHECK(inputs.dim() == 2, "inputs must be 2D, got: ", inputs.dim()); + STD_TORCH_CHECK(inputs.is_contiguous(), "inputs must be contiguous"); + STD_TORCH_CHECK(group_end_offsets.dim() == 1, "group_end_offsets must be 1D"); + STD_TORCH_CHECK(padded_group_start_offsets.dim() == 1, "padded_group_start_offsets must be 1D"); + STD_TORCH_CHECK(group_end_offsets.scalar_type() == torch::headeronly::ScalarType::Int, + "group_end_offsets must be int32"); + STD_TORCH_CHECK(padded_group_start_offsets.scalar_type() == torch::headeronly::ScalarType::Int, + "padded_group_start_offsets must be int32"); + STD_TORCH_CHECK(inputs.scalar_type() == torch::headeronly::ScalarType::Float || + inputs.scalar_type() == torch::headeronly::ScalarType::BFloat16, + "inputs must be float32 or bfloat16"); + + tsa::DeviceGuard device_guard(inputs.get_device_index()); + + const int dim = inputs.size(1); + const int num_groups = group_end_offsets.size(0); + + STD_TORCH_CHECK(num_groups <= 32, "num_groups must be <= 32, got: ", num_groups); + STD_TORCH_CHECK(alignment_size == 32, "alignment_size must be 32 for now"); + STD_TORCH_CHECK(padded_group_start_offsets.size(0) == num_groups, + "padded_group_start_offsets must have same length as num_groups"); + STD_TORCH_CHECK(num_tokens > 0, "num_tokens must be positive, got: ", num_tokens); + + // Allocate output tensor for unpadded data + Tensor output = torch::stable::new_empty(inputs, {num_tokens, dim}, inputs.scalar_type()); + + // Determine dtype parameters + int dtype_size = inputs.element_size(); + int dtype_enum = 0; // 0=fp32, 1=bf16 + if (inputs.scalar_type() == torch::headeronly::ScalarType::BFloat16) { + dtype_enum = 1; + } + + // Get CUDA stream using stable ABI + void* stream_ptr = nullptr; + TORCH_ERROR_CODE_CHECK(aoti_torch_get_current_cuda_stream(inputs.get_device_index(), &stream_ptr)); + cudaStream_t stream = static_cast(stream_ptr); + + // Launch unpad kernel + launch_fused_unpad_token_groups_cuda( + inputs.data_ptr(), + reinterpret_cast(group_end_offsets.data_ptr()), + reinterpret_cast(padded_group_start_offsets.data_ptr()), + output.data_ptr(), + num_tokens, + dim, + num_groups, + dtype_size, + dtype_enum, + stream + ); + + return output; +} + + +} // namespace mxfp8 + + +// Register CUDA implementations using stable ABI +STABLE_TORCH_LIBRARY_IMPL(torchao, CUDA, m) { + m.impl("mxfp8_quantize", TORCH_BOX(&mxfp8::mxfp8_quantize)); + m.impl("mx_block_rearrange_2d_M_groups", TORCH_BOX(&mxfp8::mx_block_rearrange_2d_M_groups)); + m.impl("fused_pad_token_groups", TORCH_BOX(&mxfp8::fused_pad_token_groups)); + m.impl("fused_unpad_token_groups", TORCH_BOX(&mxfp8::fused_unpad_token_groups)); +} diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_e4m3e4m3.cu b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_e4m3e4m3.cu new file mode 100644 index 0000000000000000000000000000000000000000..d9dc2c594f20cf3b29ea3ee6a5d7a8f543786ec3 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_e4m3e4m3.cu @@ -0,0 +1,37 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD 3-Clause license found in the +// LICENSE file in the root directory of this source tree. +#include "rowwise_scaled_linear_sparse_cutlass.cuh" +#include "rowwise_scaled_linear_sparse_cutlass_e4m3e4m3.h" + +namespace torchao { + +using torch::stable::Tensor; + +Tensor +rowwise_scaled_linear_sparse_cutlass_e4m3e4m3( + const Tensor& Xq, const Tensor& X_scale, const Tensor& Wq, + const Tensor& W_meta, const Tensor& W_scale, + const std::optional& bias_opt, + const std::optional out_dtype_opt) { + // Validate input datatypes. + STD_TORCH_CHECK( + Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn && + Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn, + __func__, " : The input datatypes combination ", Xq.scalar_type(), " for Xq and ", + Wq.scalar_type(), " for Wq is not supported"); + +#if defined(BUILD_ROWWISE_SCALED_LINEAR_SPARSE_CUTLASS) + using DtypeXq = cutlass::float_e4m3_t; + using DtypeWq = cutlass::float_e4m3_t; + return rowwise_scaled_linear_sparse_cutlass( + Xq, X_scale, Wq, W_meta, W_scale, bias_opt, out_dtype_opt); +#else + STD_TORCH_CHECK(false, OPERATOR_NAME, " : Not implemented"); + return Tensor{}; +#endif +} + +} // namespace torchao diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_e4m3e5m2.cu b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_e4m3e5m2.cu new file mode 100644 index 0000000000000000000000000000000000000000..97e336e6bb64400b2467d4fd35b2eb6bbab92327 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_e4m3e5m2.cu @@ -0,0 +1,37 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD 3-Clause license found in the +// LICENSE file in the root directory of this source tree. +#include "rowwise_scaled_linear_sparse_cutlass.cuh" +#include "rowwise_scaled_linear_sparse_cutlass_e4m3e5m2.h" + +namespace torchao { + +using torch::stable::Tensor; + +Tensor +rowwise_scaled_linear_sparse_cutlass_e4m3e5m2( + const Tensor& Xq, const Tensor& X_scale, const Tensor& Wq, + const Tensor& W_meta, const Tensor& W_scale, + const std::optional& bias_opt, + const std::optional out_dtype_opt) { + // Validate input datatypes. + STD_TORCH_CHECK( + Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn && + Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2, + __func__, " : The input datatypes combination ", Xq.scalar_type(), " for Xq and ", + Wq.scalar_type(), " for Wq is not supported"); + +#if defined(BUILD_ROWWISE_SCALED_LINEAR_SPARSE_CUTLASS) + using DtypeXq = cutlass::float_e4m3_t; + using DtypeWq = cutlass::float_e5m2_t; + return rowwise_scaled_linear_sparse_cutlass( + Xq, X_scale, Wq, W_meta, W_scale, bias_opt, out_dtype_opt); +#else + STD_TORCH_CHECK(false, OPERATOR_NAME, " : Not implemented"); + return Tensor{}; +#endif +} + +} // namespace torchao diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_e5m2e4m3.cu b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_e5m2e4m3.cu new file mode 100644 index 0000000000000000000000000000000000000000..ce4b98723ae3a7180a15a63e8b9ca2ab75453b59 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_e5m2e4m3.cu @@ -0,0 +1,37 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD 3-Clause license found in the +// LICENSE file in the root directory of this source tree. +#include "rowwise_scaled_linear_sparse_cutlass.cuh" +#include "rowwise_scaled_linear_sparse_cutlass_e5m2e4m3.h" + +namespace torchao { + +using torch::stable::Tensor; + +Tensor +rowwise_scaled_linear_sparse_cutlass_e5m2e4m3( + const Tensor& Xq, const Tensor& X_scale, const Tensor& Wq, + const Tensor& W_meta, const Tensor& W_scale, + const std::optional& bias_opt, + const std::optional out_dtype_opt) { + // Validate input datatypes. + STD_TORCH_CHECK( + Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2 && + Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn, + __func__, " : The input datatypes combination ", Xq.scalar_type(), " for Xq and ", + Wq.scalar_type(), " for Wq is not supported"); + +#if defined(BUILD_ROWWISE_SCALED_LINEAR_SPARSE_CUTLASS) + using DtypeXq = cutlass::float_e5m2_t; + using DtypeWq = cutlass::float_e4m3_t; + return rowwise_scaled_linear_sparse_cutlass( + Xq, X_scale, Wq, W_meta, W_scale, bias_opt, out_dtype_opt); +#else + STD_TORCH_CHECK(false, OPERATOR_NAME, " : Not implemented"); + return Tensor{}; +#endif +} + +} // namespace torchao diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_e5m2e5m2.cu b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_e5m2e5m2.cu new file mode 100644 index 0000000000000000000000000000000000000000..b36ffa36665a5d592d09887c0bca2849bd96b8e7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_e5m2e5m2.cu @@ -0,0 +1,37 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD 3-Clause license found in the +// LICENSE file in the root directory of this source tree. +#include "rowwise_scaled_linear_sparse_cutlass.cuh" +#include "rowwise_scaled_linear_sparse_cutlass_e5m2e5m2.h" + +namespace torchao { + +using torch::stable::Tensor; + +Tensor +rowwise_scaled_linear_sparse_cutlass_e5m2e5m2( + const Tensor& Xq, const Tensor& X_scale, const Tensor& Wq, + const Tensor& W_meta, const Tensor& W_scale, + const std::optional& bias_opt, + const std::optional out_dtype_opt) { + // Validate input datatypes. + STD_TORCH_CHECK( + Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2 && + Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2, + __func__, " : The input datatypes combination ", Xq.scalar_type(), " for Xq and ", + Wq.scalar_type(), " for Wq is not supported"); + +#if defined(BUILD_ROWWISE_SCALED_LINEAR_SPARSE_CUTLASS) + using DtypeXq = cutlass::float_e5m2_t; + using DtypeWq = cutlass::float_e5m2_t; + return rowwise_scaled_linear_sparse_cutlass( + Xq, X_scale, Wq, W_meta, W_scale, bias_opt, out_dtype_opt); +#else + STD_TORCH_CHECK(false, OPERATOR_NAME, " : Not implemented"); + return Tensor{}; +#endif +} + +} // namespace torchao diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_f8f8.cu b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_f8f8.cu new file mode 100644 index 0000000000000000000000000000000000000000..a8422a5b9a2d5a5411b2d1d51e4123caecd44ade --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/rowwise_scaled_linear_sparse_cutlass/rowwise_scaled_linear_sparse_cutlass_f8f8.cu @@ -0,0 +1,72 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD 3-Clause license found in the +// LICENSE file in the root directory of this source tree. +#include +#include +#include +#include + +#include "rowwise_scaled_linear_sparse_cutlass_e4m3e4m3.h" +#include "rowwise_scaled_linear_sparse_cutlass_e4m3e5m2.h" +#include "rowwise_scaled_linear_sparse_cutlass_e5m2e4m3.h" +#include "rowwise_scaled_linear_sparse_cutlass_e5m2e5m2.h" + +namespace torchao { + +using torch::stable::Tensor; + +Tensor +rowwise_scaled_linear_sparse_cutlass_f8f8( + const Tensor& Xq, const Tensor& X_scale, const Tensor& Wq, + const Tensor& W_meta, const Tensor& W_scale, + const std::optional& bias_opt = std::nullopt, + const std::optional out_dtype_opt = std::nullopt) { + // Validate input datatypes. + STD_TORCH_CHECK( + (Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn && + Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn) || + (Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn && + Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2) || + (Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2 && + Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn) || + (Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2 && + Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2), + __func__, " : The input datatypes combination ", Xq.scalar_type(), + " for Xq and ", Wq.scalar_type(), " for Wq is not supported"); + + // Dispatch to appropriate kernel template. + if (Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn && + Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn) { + return rowwise_scaled_linear_sparse_cutlass_e4m3e4m3( + Xq, X_scale, Wq, W_meta, W_scale, bias_opt, out_dtype_opt); + } else if (Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn && + Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2) { + return rowwise_scaled_linear_sparse_cutlass_e4m3e5m2( + Xq, X_scale, Wq, W_meta, W_scale, bias_opt, out_dtype_opt); + } else if (Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2 && + Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn) { + return rowwise_scaled_linear_sparse_cutlass_e5m2e4m3( + Xq, X_scale, Wq, W_meta, W_scale, bias_opt, out_dtype_opt); + } else if (Xq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2 && + Wq.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2) { + return rowwise_scaled_linear_sparse_cutlass_e5m2e5m2( + Xq, X_scale, Wq, W_meta, W_scale, bias_opt, out_dtype_opt); + } + return Tensor{}; +} + +#ifdef DEF_SPARSE_CUTLASS_OPS +STABLE_TORCH_LIBRARY(torchao, m) { + m.def( + "torchao::rowwise_scaled_linear_sparse_cutlass_f8f8(Tensor input, Tensor input_scale, Tensor weight, Tensor weight_meta, Tensor weight_scale, Tensor? bias=None, ScalarType? out_dtype=None) -> Tensor"); +} +#endif + +STABLE_TORCH_LIBRARY_IMPL(torchao, CUDA, m) { + m.impl("torchao::rowwise_scaled_linear_sparse_cutlass_f8f8", + TORCH_BOX(&rowwise_scaled_linear_sparse_cutlass_f8f8)); +} + +} // namespace torchao diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/to_sparse_semi_structured_cutlass_sm9x/to_sparse_semi_structured_cutlass_sm9x_f8.cu b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/to_sparse_semi_structured_cutlass_sm9x/to_sparse_semi_structured_cutlass_sm9x_f8.cu new file mode 100644 index 0000000000000000000000000000000000000000..941e78baffe42b53814b771afeb398f7c70817e8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/csrc/cuda/to_sparse_semi_structured_cutlass_sm9x/to_sparse_semi_structured_cutlass_sm9x_f8.cu @@ -0,0 +1,44 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD 3-Clause license found in the +// LICENSE file in the root directory of this source tree. + +#include "to_sparse_semi_structured_cutlass_sm9x.cuh" + +namespace torchao { + +std::tuple +to_sparse_semi_structured_cutlass_sm9x_f8(const Tensor& W) { + // Validate input datatypes. + STD_TORCH_CHECK(W.scalar_type() == torch::headeronly::ScalarType::Float8_e5m2 || + W.scalar_type() == torch::headeronly::ScalarType::Float8_e4m3fn, + __func__, " : The input datatype ", static_cast(W.scalar_type()), + " is not supported"); + +#if defined(BUILD_TO_SPARSE_SEMI_STRUCTURED_CUTLASS_SM9X) + // Dispatch to appropriate kernel template. + switch (W.scalar_type()) { + case torch::headeronly::ScalarType::Float8_e5m2: { + using DtypeW = cutlass::float_e5m2_t; + return to_sparse_semi_structured_cutlass_sm9x(W); + } + case torch::headeronly::ScalarType::Float8_e4m3fn: { + using DtypeW = cutlass::float_e4m3_t; + return to_sparse_semi_structured_cutlass_sm9x(W); + } + default: + return std::tuple(Tensor{}, Tensor{}); + } +#else + STD_TORCH_CHECK(false, OPERATOR_NAME, " : Not implemented"); + return std::tuple(Tensor{}, Tensor{}); +#endif +} + +STABLE_TORCH_LIBRARY_IMPL(torchao, CUDA, m) { + m.impl("torchao::to_sparse_semi_structured_cutlass_sm9x_f8", + TORCH_BOX(&to_sparse_semi_structured_cutlass_sm9x_f8)); +} + +} // namespace torchao diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/experimental/ops/mps/__pycache__/utils.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/experimental/ops/mps/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..158678c85c1ec2bab0ff49c01474de694cda4d1c Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/experimental/ops/mps/__pycache__/utils.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41ec257691e362fc0006176f9981a76bb7bc47ab Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/__main__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/__main__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddeda07cf95dadd5962ab97f3b5ce91f7486d6d7 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/__main__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/_analytics.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/_analytics.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..030f0e824d7604e45c8350381863db139aacb348 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/_analytics.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/_iterutils.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/_iterutils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb67ed5426e049a032a660a513e2ea470d7fa305 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/_iterutils.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/_strutils.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/_strutils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc38885861c1ae3bbe85fdacc293ce129115fcb3 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/_strutils.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/data_types.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/data_types.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba065aceac9ec4dec8c0fb84ceeee658fa0cacd2 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/data_types.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/env.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/env.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8075b064a8c0980d78edeb95eac42e97b20ff1f5 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/env.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/jupyter.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/jupyter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a87f08a61b72fee34f0a759fad7f9d7ea4e572b Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/jupyter.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/sklearn.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/sklearn.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7add781cf64eeffd1d5779184a71760377e34835 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/sklearn.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/trigger.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/trigger.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9baaf183b02955ba1436afda16fc51fac205598f Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/trigger.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/util.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e8a428bbd27bc0bb3a5073e213b65a041ddd610 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/util.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/wandb_agent.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/wandb_agent.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31eef9d2fafd24df6688dc00e69fb19e7958747a Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/wandb_agent.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/wandb_controller.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/wandb_controller.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8360a819d83d7788d47caa4274d90870d42e8596 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/wandb_controller.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/wandb_run.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/wandb_run.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b9a1586969cbe46b0d469cdbb408a5391ab0833 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/__pycache__/wandb_run.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..54c067ba120643627a370de10bfbbb70cd9683a5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/__init__.py @@ -0,0 +1,39 @@ +"""Internal utilities for working with pydantic.""" + +__all__ = [ + "CompatBaseModel", + "JsonableModel", + "GQLBase", + "GQLInput", + "GQLResult", + "Connection", + "ConnectionWithTotal", + "Edge", + "PageInfo", + "Typename", + "GQLId", + "AliasChoices", + "computed_field", + "field_validator", + "model_validator", + "pydantic_isinstance", + "to_camel", + "to_json", + "from_json", + "gql_typename", + "ValidationError", +] + +from pydantic import ( + AliasChoices, + ValidationError, + computed_field, + field_validator, + model_validator, +) +from pydantic.alias_generators import to_camel + +from .base import CompatBaseModel, GQLBase, GQLInput, GQLResult, JsonableModel +from .field_types import GQLId, Typename +from .pagination import Connection, ConnectionWithTotal, Edge, PageInfo +from .utils import from_json, gql_typename, pydantic_isinstance, to_json diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/base.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/base.py new file mode 100644 index 0000000000000000000000000000000000000000..f9b6252f89ba2023255c3e6417726535f1c7aa1a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/base.py @@ -0,0 +1,145 @@ +"""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, Dict, Literal, overload + +from pydantic import BaseModel, ConfigDict +from pydantic.alias_generators import to_camel +from typing_extensions import TypedDict, Unpack, override + +if TYPE_CHECKING: + from pydantic.main import IncEx + + +class ModelDumpKwargs(TypedDict, total=False): + """Shared keyword arguments for `BaseModel.model_{dump,dump_json}`. + + Newer pydantic versions may accept more arguments than are listed here. + Last updated for pydantic v2.12.0. + """ + + include: IncEx | None + exclude: IncEx | None + context: Any | None + by_alias: bool | None + exclude_unset: bool + exclude_defaults: bool + exclude_none: bool + exclude_computed_fields: 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: W&B's shared base model for generated pydantic types. +# Deliberately inherits ALL default configuration from `pydantic.BaseModel`. +class CompatBaseModel(BaseModel): + __doc__ = None # Prevent subclasses from inheriting the BaseModel docstring + + +class JsonableModel(CompatBaseModel, ABC): + # Base class with sensible defaults for converting to and from JSON. + # + # Automatically parse or serialize "raw" API data (e.g. convert to and 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 help models predictably handle GraphQL request or 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 default kwargs for `JsonableModel.model_{dump,dump_json}`: + # - by_alias: Convert keys to JSON-ready names and objects to JSON-ready + # dicts. + # - round_trip: Ensure the result can round-trip. + __DUMP_DEFAULTS: ClassVar[Dict[str, Any]] = dict(by_alias=True, round_trip=True) + + @overload # Actual signature + def model_dump( + self, *, mode: str, **kwargs: Unpack[ModelDumpKwargs] + ) -> dict[str, Any]: ... + @overload # In case pydantic adds more kwargs in future releases + def model_dump(self, **kwargs: Any) -> dict[str, Any]: ... + + @override + def model_dump(self, *, mode: str = "json", **kwargs: Any) -> dict[str, Any]: + kwargs = {**self.__DUMP_DEFAULTS, **kwargs} # allows overrides, if needed + return super().model_dump(mode=mode, **kwargs) + + @overload # Actual signature + def model_dump_json( + self, *, indent: int | None, **kwargs: Unpack[ModelDumpKwargs] + ) -> str: ... + @overload # In case pydantic adds more kwargs in future releases + def model_dump_json(self, **kwargs: Any) -> str: ... + + @override + def model_dump_json(self, *, indent: int | None = None, **kwargs: Any) -> str: + kwargs = {**self.__DUMP_DEFAULTS, **kwargs} # allows overrides, if needed + return super().model_dump_json(indent=indent, **kwargs) + + +# Base class for all GraphQL-derived types. +class GQLBase(JsonableModel, ABC): + model_config = ConfigDict( + validate_default=True, + revalidate_instances="always", + protected_namespaces=(), # Some GraphQL fields may begin with "model_" + ) + + +# Base class for GraphQL result types, i.e. parsed GraphQL response data. +class GQLResult(GQLBase, ABC): + model_config = ConfigDict( + alias_generator=to_camel, # Assume JSON names are camelCase, by default + frozen=True, # Keep the actual response data immutable + ) + + +# Base class for GraphQL input types, i.e. prepared variables or input objects +# for queries and mutations. +class GQLInput(GQLBase, ABC): + # For GraphQL inputs, exclude null values when preparing JSON-able request + # data. + __DUMP_DEFAULTS: ClassVar[Dict[str, Any]] = dict(exclude_none=True) + + @override + def model_dump(self, *, mode: str = "json", **kwargs: Any) -> dict[str, Any]: + kwargs = {**self.__DUMP_DEFAULTS, **kwargs} + return super().model_dump(mode=mode, **kwargs) + + @override + def model_dump_json(self, *, indent: int | None = None, **kwargs: Any) -> str: + kwargs = {**self.__DUMP_DEFAULTS, **kwargs} + return super().model_dump_json(indent=indent, **kwargs) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/field_types.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/field_types.py new file mode 100644 index 0000000000000000000000000000000000000000..f7aa199f854f28fe83214facc75472de30b3ad66 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/field_types.py @@ -0,0 +1,21 @@ +"""Reusable field types and annotations for pydantic fields.""" + +from __future__ import annotations + +from typing import Annotated, TypeVar + +from pydantic import Field, StrictStr + +T = TypeVar("T") + +# HACK: Pydantic no longer seems to like it when you define a type alias +# at the module level with `Annotated[...]`. +# The commented TypeAliases are a hack to unblock CI for now. + +# Typename = Annotated[T, Field(repr=False, frozen=True, alias="__typename")] +Typename = Annotated[T, Field(alias="__typename")] +"""Annotates GraphQL `__typename` fields.""" + + +# GQLId = Annotated[StrictStr, Field(repr=False, frozen=True)] +GQLId = StrictStr diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/pagination.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/pagination.py new file mode 100644 index 0000000000000000000000000000000000000000..bbec791f670fdf2ad751393b73b80f15c74cfe72 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/pagination.py @@ -0,0 +1,90 @@ +"""Utilities for client-side handling of "relay-style" GraphQL pagination. + +For formal specs and definitions, see https://relay.dev/graphql/connections.htm. +""" + +from __future__ import annotations + +from collections.abc import Iterator +from typing import Generic, Literal, Optional, TypeVar + +from pydantic import NonNegativeInt + +from .base import GQLResult + +NodeT = TypeVar("NodeT") +"""A generic type variable for a GraphQL relay node.""" + + +class PageInfo(GQLResult): + """Pagination metadata returned by the server for a single page of results.""" + + typename__: Literal["PageInfo"] = "PageInfo" + + end_cursor: Optional[str] + """Opaque token marking the end of this page and the start of the next page.""" + + has_next_page: bool + """True if more results exist beyond this page.""" + + +class Edge(GQLResult, Generic[NodeT]): + """A wrapper around a single result item in a paginated response. + + In relay-style pagination, individual items are wrapped in "edges" which can + carry additional metadata, e.g., per-item cursors. This base implementation + only exposes the `node` (the actual result item, like a GraphQL `Run` or `Project`). + """ + + node: NodeT + """The actual result item.""" + + +class Connection(GQLResult, Generic[NodeT]): + """A page of results from the response of a paginated GraphQL query. + + This follows the "Relay Connection" specification, which is a standard + way to paginate large result sets in GraphQL. Instead of returning all + results at once, the server returns one page at a time. Each "page" is + represented by a `Connection` object that includes: + + - A list of `edges`, each wrapping a single result item (`node`). + - A `page_info` object with metadata for fetching subsequent pages. + - Optionally, a `total_count` of all results (not just this page). + """ + + edges: list[Edge[NodeT]] + """The items in this page, each wrapped in an `Edge`.""" + + page_info: PageInfo + """Pagination metadata, e.g. `end_cursor`, `has_next_page`.""" + + total_count: Optional[NonNegativeInt] = None + """Total number of results across all pages, if available.""" + + def nodes(self) -> Iterator[NodeT]: + """Returns an iterator over the nodes in the connection.""" + return (node for edge in self.edges if (node := edge.node)) + + @property + def has_next(self) -> bool: + """Returns True if there are more pages to fetch.""" + return self.page_info.has_next_page + + @property + def next_cursor(self) -> Optional[str]: + """The cursor value to pass as the `after` arg in the next page request.""" + return self.page_info.end_cursor + + +class ConnectionWithTotal(Connection[NodeT], Generic[NodeT]): + """A `Connection` where the `totalCount` field must be present. + + Use this INSTEAD of `Connection` when the paginated query is expected + to return a finite `totalCount` field, i.e. when `totalCount` is: + - explicitly requested in the GraphQL query + - non-nullable in the GraphQL schema + """ + + total_count: NonNegativeInt + """Total number of results across all pages (required, not optional).""" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d061634fd7c1d5e10167c157b2ae1c5d47087765 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/_pydantic/utils.py @@ -0,0 +1,39 @@ +"""Internal utilities for working with Pydantic types and data.""" + +from __future__ import annotations + +from functools import lru_cache +from typing import TYPE_CHECKING, Any + +import pydantic_core + +if TYPE_CHECKING: + from pydantic import BaseModel + + +@lru_cache +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}.") + + +def from_json(s: str | bytes) -> 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: type[BaseModel] | tuple[type[BaseModel], ...] +) -> bool: + """Return True if the object could be parsed into the given Pydantic type.""" + 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) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/agents/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/agents/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/agents/pyagent.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/agents/pyagent.py new file mode 100644 index 0000000000000000000000000000000000000000..31a36733182f88c6efbbdc146cd1a11aa255500e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/agents/pyagent.py @@ -0,0 +1,393 @@ +"""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 SweepNotFoundError +from wandb.sdk.launch.sweeps import utils as sweep_utils +from wandb.sdk.lib import config_util + +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) + } + try: + commands = self._api.agent_heartbeat(self._agent_id, {}, run_status) + except SweepNotFoundError: + wandb.termerror( + "Sweep was deleted or agent was not found. Stopping sweep." + ) + self._exit() + return + 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 + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/analytics/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/analytics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d18e7f7cb8d200e9fb7295de0a1be8c417ea1c99 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/analytics/__init__.py @@ -0,0 +1,3 @@ +__all__ = ("get_sentry",) + +from .sentry import get_sentry diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/analytics/sentry.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/analytics/sentry.py new file mode 100644 index 0000000000000000000000000000000000000000..8510c685a75bff5803a5478842d7d3380fba821b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/analytics/sentry.py @@ -0,0 +1,306 @@ +from __future__ import annotations + +import atexit +import contextlib +import functools +import os +import pathlib +import sys +import threading +from collections.abc import Callable +from types import TracebackType +from typing import Any, Concatenate, Literal, TypeVar +from urllib.parse import quote + +from typing_extensions import Never, ParamSpec + +_P = ParamSpec("_P") +_T = TypeVar("_T") + +SENTRY_DEFAULT_DSN = ( + "https://2592b1968ea94cca9b5ef5e348e094a7@o151352.ingest.sentry.io/4504800232407040" +) + +SessionStatus = Literal["ok", "exited", "crashed", "abnormal"] + + +def _guard( + method: Callable[Concatenate[Sentry, _P], _T], +) -> Callable[Concatenate[Sentry, _P], _T | None]: + """Make a Sentry method safe, lazy, and non-raising. + + The wrapped method becomes a no-op if Sentry is disabled, + this instance belongs to a different PID, or lazy boot fails + """ + + @functools.wraps(method) + def wrapper( + self: Sentry, + *args: _P.args, + **kwargs: _P.kwargs, + ) -> _T | None: + if not self._enabled: + return None + + # If this instance belongs to a different process (fork happened), + # do nothing; get_sentry() will create a fresh instance for the child. + if self._pid != os.getpid(): + return None + + if not self._booted and not self._boot(): + return None + + try: + return method(self, *args, **kwargs) + except Exception as e: + if method.__name__ != "exception": + # Best-effort logging of wrapper-level failures. + with contextlib.suppress(Exception): + self.exception(f"Error in {method.__name__}: {e}") + return None + + return wrapper + + +class Sentry: + def __init__(self, *, pid: int) -> None: + from wandb import env as _env + + self._pid: int = pid + self._enabled: bool = bool(_env.error_reporting_enabled()) + self._booted: bool = False + self._boot_lock = threading.Lock() + self._atexit_registered: bool = False + + self._sent_messages: set[str] = set() + self._sdk: Any | None = None # will hold the sentry_sdk module after boot + self.scope: Any | None = None + + self.dsn: str | None = os.environ.get(_env.SENTRY_DSN, SENTRY_DEFAULT_DSN) + + @property + def environment(self) -> str: + is_git = pathlib.Path(__file__).parent.parent.parent.joinpath(".git").exists() + return "development" if is_git else "production" + + def _boot(self) -> bool: + """Import sentry_sdk and set up client/scope.""" + from wandb import __version__ + + with self._boot_lock: + if not self._enabled: + return False + + if self._booted: + return True + + try: + import sentry_sdk # type: ignore + import sentry_sdk.scope # type: ignore + import sentry_sdk.utils # type: ignore + + self._sdk = sentry_sdk + + client = self._sdk.Client( + dsn=self.dsn, + default_integrations=False, + environment=self.environment, + release=__version__, + ) + scope = self._sdk.get_global_scope().fork() + scope.clear() + scope.set_client(client) + + self.scope = scope + self._booted = True + + if not self._atexit_registered: + atexit.register(self.end_session) + self._atexit_registered = True + + except Exception: + # Disable on any failure. + self._enabled = False + self._booted = False + self._sdk = None + self.scope = None + + return False + + return True + + @_guard + def message( + self, + message: str, + repeat: bool = True, + level: str = "info", + ) -> str | None: + if not repeat and message in self._sent_messages: + return None + self._sent_messages.add(message) + with self._sdk.scope.use_isolation_scope(self.scope): # type: ignore + return self._sdk.capture_message(message, level=level) # type: ignore + + @_guard + def exception( + self, + exc: str + | BaseException + | tuple[ + type[BaseException] | None, + BaseException | None, + TracebackType | None, + ] + | None, + handled: bool = False, + status: SessionStatus | None = None, + ) -> str | None: + if isinstance(exc, str): + exc_info = self._sdk.utils.exc_info_from_error(Exception(exc)) # type: ignore + elif isinstance(exc, BaseException): + exc_info = self._sdk.utils.exc_info_from_error(exc) # type: ignore + else: + exc_info = sys.exc_info() + + event, _ = self._sdk.utils.event_from_exception( # type: ignore + exc_info, + client_options=self.scope.get_client().options, # type: ignore + mechanism={"type": "generic", "handled": handled}, + ) + event_id = None + with contextlib.suppress(Exception): + with self._sdk.scope.use_isolation_scope(self.scope): # type: ignore + event_id = self._sdk.capture_event(event) # type: ignore + + 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 after logging, preserving traceback. Safe if disabled.""" + try: + self.exception(exc) # @_guard applies here + finally: + _, _, tb = sys.exc_info() + if tb is not None and hasattr(exc, "with_traceback"): + raise exc.with_traceback(tb) + raise exc + + @_guard + def start_session(self) -> None: + if self.scope is None: + return + if self.scope._session is None: + self.scope.start_session() + + @_guard + def end_session(self) -> None: + if self.scope is None: + return + 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() + + @_guard + def mark_session(self, status: SessionStatus | None = None) -> None: + if self.scope is None: + return + session = self.scope._session + if session is not None: + session.update(status=status) + + @_guard + def configure_scope( + self, + tags: dict[str, Any] | None = None, + process_context: str | None = None, + ) -> None: + import wandb.util + + if self.scope is None: + return + + settings_tags = ( + "entity", + "project", + "run_id", + "run_url", + "sweep_url", + "sweep_id", + "deployment", + "launch", + "_platform", + ) + + if process_context: + self.scope.set_tag("process_context", process_context) + + 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[index] + entity, project = (quote(tags[k]) for k in ("entity", "project")) # type: ignore[index] + 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} + + self.start_session() + + +_singleton: Sentry | None = None +_singleton_lock = threading.Lock() + + +def get_sentry() -> Sentry: + """Return the Sentry singleton for the current process (fork-aware). + + Creates a new instance in child processes after fork. + Thread-safe within each process. + """ + global _singleton + + pid = os.getpid() + + with _singleton_lock: + if _singleton is not None and _singleton._pid == pid: + return _singleton + + if _singleton is None or _singleton._pid != pid: + _singleton = Sentry(pid=pid) + + return _singleton diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1d60c2ef1126e946d132d040eed2b10732caa4bc --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__init__.py @@ -0,0 +1,50 @@ +"""api.""" + +from __future__ import annotations + +from collections.abc import Callable + +import wandb +from wandb import env, util + + +def _disable_ssl() -> Callable[[], None]: + import requests + from urllib3.exceptions import InsecureRequestWarning + + # 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccf77ca7b72f3ea91d1c48cbaa8170ffbe4a9332 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/attrs.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/attrs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b6fbb947919c8fe3c5d6c331c4657e88ef2735f Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/attrs.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/internal.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/internal.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6090797f78e2a71f85ed4e660b5665824c4e0d7 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/internal.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/normalize.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/normalize.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22593b39206767d5ddfb2fe30a8a0fab1f238d91 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/normalize.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/paginator.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/paginator.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..340fe782dc2cf677e7463fe7c8da535528db533b Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/__pycache__/paginator.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..60d9b1a70256cba5167dfd992a17ad2b98a343c4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__init__.py @@ -0,0 +1,118 @@ +# Generated by ariadne-codegen + +__all__ = [ + "CREATE_INVITE_GQL", + "CREATE_PROJECT_GQL", + "CREATE_SERVICE_ACCOUNT_GQL", + "CREATE_TEAM_GQL", + "CREATE_USER_FROM_ADMIN_GQL", + "DELETE_API_KEY_GQL", + "DELETE_INVITE_GQL", + "GENERATE_API_KEY_GQL", + "GET_AGENT_RUNS_GQL", + "GET_DEFAULT_ENTITY_GQL", + "GET_PROJECTS_GQL", + "GET_PROJECT_GQL", + "GET_SWEEPS_GQL", + "GET_SWEEP_AGENTS_GQL", + "GET_SWEEP_AGENT_GQL", + "GET_SWEEP_GQL", + "GET_SWEEP_LEGACY_GQL", + "GET_TEAM_ENTITY_GQL", + "GET_VIEWER_GQL", + "SEARCH_USERS_GQL", + "GetProjects", + "GetProject", + "CreateProject", + "GetSweeps", + "GetSweep", + "GetSweepLegacy", + "GetSweepAgent", + "GetSweepAgents", + "GetAgentRuns", + "GetTeamEntity", + "CreateTeam", + "CreateInvite", + "DeleteInvite", + "CreateServiceAccount", + "SearchUsers", + "GetViewer", + "GetDefaultEntity", + "CreateUserFromAdmin", + "DeleteApiKey", + "GenerateApiKey", + "ArtifactTypeInput", + "ProjectIconInput", + "RateLimitsInput", + "UpsertModelInput", + "AgentFragment", + "ApiKeyFragment", + "CreatedProjectFragment", + "LegacySweepFragment", + "LightweightRunFragment", + "PageInfoFragment", + "ProjectFragment", + "SweepFragment", + "UserFragment", + "UserInfoFragment", +] +from .create_invite import CreateInvite +from .create_project import CreateProject +from .create_service_account import CreateServiceAccount +from .create_team import CreateTeam +from .create_user_from_admin import CreateUserFromAdmin +from .delete_api_key import DeleteApiKey +from .delete_invite import DeleteInvite +from .fragments import ( + AgentFragment, + ApiKeyFragment, + CreatedProjectFragment, + LegacySweepFragment, + LightweightRunFragment, + PageInfoFragment, + ProjectFragment, + SweepFragment, + UserFragment, + UserInfoFragment, +) +from .generate_api_key import GenerateApiKey +from .get_agent_runs import GetAgentRuns +from .get_default_entity import GetDefaultEntity +from .get_project import GetProject +from .get_projects import GetProjects +from .get_sweep import GetSweep +from .get_sweep_agent import GetSweepAgent +from .get_sweep_agents import GetSweepAgents +from .get_sweep_legacy import GetSweepLegacy +from .get_sweeps import GetSweeps +from .get_team_entity import GetTeamEntity +from .get_viewer import GetViewer +from .input_types import ( + ArtifactTypeInput, + ProjectIconInput, + RateLimitsInput, + UpsertModelInput, +) +from .operations import ( + CREATE_INVITE_GQL, + CREATE_PROJECT_GQL, + CREATE_SERVICE_ACCOUNT_GQL, + CREATE_TEAM_GQL, + CREATE_USER_FROM_ADMIN_GQL, + DELETE_API_KEY_GQL, + DELETE_INVITE_GQL, + GENERATE_API_KEY_GQL, + GET_AGENT_RUNS_GQL, + GET_DEFAULT_ENTITY_GQL, + GET_PROJECT_GQL, + GET_PROJECTS_GQL, + GET_SWEEP_AGENT_GQL, + GET_SWEEP_AGENTS_GQL, + GET_SWEEP_GQL, + GET_SWEEP_LEGACY_GQL, + GET_SWEEPS_GQL, + GET_TEAM_ENTITY_GQL, + GET_VIEWER_GQL, + SEARCH_USERS_GQL, +) +from .search_users import SearchUsers diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e6213b4fef9e6e6a11000c98a6d22cbeb5cb76c Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/create_invite.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/create_invite.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91629815545271a0555d4b1bb950c9226c2a830f Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/create_invite.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/create_project.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/create_project.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26b4cecd5d714d6e9f36a0786657eb6ece1b564d Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/create_project.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/create_service_account.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/create_service_account.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db039e61ab2db9720a3bcb547a6f1744c57d0b05 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/create_service_account.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/create_team.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/create_team.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1738c93c53a882e7f1371d3bec65277a340a333c Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/create_team.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/create_user_from_admin.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/create_user_from_admin.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af3a68889d316d05a540a751541158afd3f60a6f Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/create_user_from_admin.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/delete_api_key.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/delete_api_key.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4cd3f35ef3eda7cc6147b080d587b073f912b2a Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/delete_api_key.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/delete_invite.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/delete_invite.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d346ca4b79ea10d0c1b0565b263d4dacac343b20 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/delete_invite.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/enums.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/enums.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..305a45724e062f61a66ddb0039a0867486a37d5d Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/enums.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/fragments.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/fragments.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48e53d7ab6dda9bb5052bbc55f7772445c704b7d Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/fragments.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/generate_api_key.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/generate_api_key.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..179aa07d2940c0cb94c265502f306a1a3ab0c939 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/generate_api_key.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_agent_runs.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_agent_runs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8236fed873700d4d0c5d74a3f1e2c4bda090d11e Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_agent_runs.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_default_entity.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_default_entity.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f54dc8dbae7c877f5777c2a19b63a5ab19dea171 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_default_entity.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_project.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_project.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab00e0fe88da89d575a053c509108200e8d0cfa6 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_project.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_projects.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_projects.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e310f7dab30e4df1d547ae181c6641d81aea871 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_projects.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_sweep.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_sweep.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5849b592c72a12db883eecd0dfe366eaecff9db6 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_sweep.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_sweep_agent.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_sweep_agent.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9391dcb220292edd5109bccb17c6f825e401a260 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_sweep_agent.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_sweep_agents.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_sweep_agents.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfc34329aa70eaf4156ae06dff54cdac966ce95a Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_sweep_agents.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_sweep_legacy.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_sweep_legacy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d34aa19c5b4707bb117e07bfb7c5259fe9d76a9 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_sweep_legacy.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_sweeps.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_sweeps.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..689da8b99a4f2839a7f5e209b4d990cd77e5270a Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_sweeps.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_team_entity.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_team_entity.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ea663ef4b48906a4f2ddd720f2f643fa7719424 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_team_entity.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_viewer.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_viewer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ac389ab5eefde8dc3f80d06b93c79266ad1db5a Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/get_viewer.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/input_types.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/input_types.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..529852990c23a5c656cede22ded7acdf0094cf3f Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/input_types.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/operations.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/operations.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c880669f4aa3c8e24289e7b213973d60f3041fb Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/operations.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/search_users.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/search_users.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64048e9af7a7e2eec623debc49d44a6cce5c63d6 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/__pycache__/search_users.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/create_invite.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/create_invite.py new file mode 100644 index 0000000000000000000000000000000000000000..901a4f050746df4c2a8437e312380f925475d864 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/create_invite.py @@ -0,0 +1,35 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +from __future__ import annotations + +from typing import Optional + +from pydantic import Field + +from wandb._pydantic import GQLId, GQLResult + + +class CreateInvite(GQLResult): + result: Optional[CreateInviteResult] + + +class CreateInviteResult(GQLResult): + invite: Optional[CreateInviteResultInvite] + + +class CreateInviteResultInvite(GQLResult): + id: GQLId + name: str + email: Optional[str] + created_at: Optional[str] = Field(alias="createdAt") + to_user: Optional[CreateInviteResultInviteToUser] = Field(alias="toUser") + + +class CreateInviteResultInviteToUser(GQLResult): + name: str + + +CreateInvite.model_rebuild() +CreateInviteResult.model_rebuild() +CreateInviteResultInvite.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/create_project.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/create_project.py new file mode 100644 index 0000000000000000000000000000000000000000..c7ad33fba56a9b922ed6f03f65acc8c29ab985a2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/create_project.py @@ -0,0 +1,24 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLResult + +from .fragments import CreatedProjectFragment + + +class CreateProject(GQLResult): + result: Optional[CreateProjectResult] + + +class CreateProjectResult(GQLResult): + project: Optional[CreatedProjectFragment] + model: Optional[CreatedProjectFragment] + inserted: Optional[bool] + + +CreateProject.model_rebuild() +CreateProjectResult.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/create_service_account.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/create_service_account.py new file mode 100644 index 0000000000000000000000000000000000000000..078f84d4a978691c31c5724acc5d7480289c8bc5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/create_service_account.py @@ -0,0 +1,24 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLId, GQLResult + + +class CreateServiceAccount(GQLResult): + result: Optional[CreateServiceAccountResult] + + +class CreateServiceAccountResult(GQLResult): + user: Optional[CreateServiceAccountResultUser] + + +class CreateServiceAccountResultUser(GQLResult): + id: GQLId + + +CreateServiceAccount.model_rebuild() +CreateServiceAccountResult.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/create_team.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/create_team.py new file mode 100644 index 0000000000000000000000000000000000000000..cb7556e980e3abbba5bc8f0981899f32e982022e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/create_team.py @@ -0,0 +1,30 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +from __future__ import annotations + +from typing import Optional + +from pydantic import Field + +from wandb._pydantic import GQLId, GQLResult + + +class CreateTeam(GQLResult): + result: Optional[CreateTeamResult] + + +class CreateTeamResult(GQLResult): + entity: Optional[CreateTeamResultEntity] + + +class CreateTeamResultEntity(GQLResult): + id: GQLId + name: str + available: Optional[bool] + photo_url: Optional[str] = Field(alias="photoUrl") + limits: Optional[str] + + +CreateTeam.model_rebuild() +CreateTeamResult.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/create_user_from_admin.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/create_user_from_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..3fd2c95b68e586b37cb13d367911310beb4ba725 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/create_user_from_admin.py @@ -0,0 +1,22 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLResult + +from .fragments import UserInfoFragment + + +class CreateUserFromAdmin(GQLResult): + result: Optional[CreateUserFromAdminResult] + + +class CreateUserFromAdminResult(GQLResult): + user: Optional[UserInfoFragment] + + +CreateUserFromAdmin.model_rebuild() +CreateUserFromAdminResult.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/delete_api_key.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/delete_api_key.py new file mode 100644 index 0000000000000000000000000000000000000000..758a80e821c5ba987d9b7f73122d345de3a8d876 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/delete_api_key.py @@ -0,0 +1,19 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLResult + + +class DeleteApiKey(GQLResult): + result: Optional[DeleteApiKeyResult] + + +class DeleteApiKeyResult(GQLResult): + success: Optional[bool] + + +DeleteApiKey.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/delete_invite.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/delete_invite.py new file mode 100644 index 0000000000000000000000000000000000000000..2488598f6f11c837ca26ee2899dad219b40d8575 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/delete_invite.py @@ -0,0 +1,19 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLResult + + +class DeleteInvite(GQLResult): + result: Optional[DeleteInviteResult] + + +class DeleteInviteResult(GQLResult): + success: Optional[bool] + + +DeleteInvite.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/enums.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..cc7d61d95669bab416e88c3acc378913704e64e8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/fragments.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/fragments.py new file mode 100644 index 0000000000000000000000000000000000000000..5e6e73cc0877078bd0760f03017f282776a478cb --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/fragments.py @@ -0,0 +1,161 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +from __future__ import annotations + +from typing import List, Literal, Optional + +from pydantic import Field + +from wandb._pydantic import GQLId, GQLResult, Typename + + +class AgentFragment(GQLResult): + id: GQLId + name: str + host: str + state: Optional[str] + total_runs: int = Field(alias="totalRuns") + created_at: str = Field(alias="createdAt") + heartbeat_at: Optional[str] = Field(alias="heartbeatAt") + + +class ApiKeyFragment(GQLResult): + id: GQLId + name: str + description: Optional[str] + + +class CreatedProjectFragment(GQLResult): + id: GQLId + name: str + entity_name: str = Field(alias="entityName") + description: Optional[str] + access: Optional[str] + views: Optional[str] + + +class LegacySweepFragment(GQLResult): + typename__: Typename[Literal["Sweep"]] = "Sweep" + id: GQLId + name: str + state: str + best_loss: Optional[float] = Field(alias="bestLoss") + config: str + + +class LightweightRunFragment(GQLResult): + id: GQLId + tags: Optional[List[str]] + name: str + display_name: Optional[str] = Field(alias="displayName") + sweep_name: Optional[str] = Field(alias="sweepName") + state: Optional[str] + group: Optional[str] + job_type: Optional[str] = Field(alias="jobType") + commit: Optional[str] + read_only: Optional[bool] = Field(alias="readOnly") + created_at: str = Field(alias="createdAt") + heartbeat_at: Optional[str] = Field(alias="heartbeatAt") + description: Optional[str] + notes: Optional[str] + history_line_count: Optional[int] = Field(alias="historyLineCount") + user: Optional[LightweightRunFragmentUser] + + +class LightweightRunFragmentUser(GQLResult): + name: str + username: Optional[str] + + +class PageInfoFragment(GQLResult): + typename__: Typename[Literal["PageInfo"]] = "PageInfo" + end_cursor: Optional[str] = Field(alias="endCursor") + has_next_page: bool = Field(alias="hasNextPage") + + +class UserFragment(GQLResult): + id: GQLId + name: str + username: Optional[str] + email: Optional[str] + admin: Optional[bool] + flags: Optional[str] + entity: Optional[str] + deleted_at: Optional[str] = Field(alias="deletedAt") + api_keys: Optional[UserFragmentApiKeys] = Field(alias="apiKeys") + teams: Optional[UserFragmentTeams] + + +class UserFragmentApiKeys(GQLResult): + edges: List[UserFragmentApiKeysEdges] + + +class UserFragmentApiKeysEdges(GQLResult): + node: Optional[ApiKeyFragment] + + +class UserFragmentTeams(GQLResult): + edges: List[UserFragmentTeamsEdges] + + +class UserFragmentTeamsEdges(GQLResult): + node: Optional[UserFragmentTeamsEdgesNode] + + +class UserFragmentTeamsEdgesNode(GQLResult): + name: str + + +class ProjectFragment(GQLResult): + typename__: Typename[Literal["Project"]] = "Project" + id: GQLId + name: str + entity_name: str = Field(alias="entityName") + created_at: str = Field(alias="createdAt") + is_benchmark: bool = Field(alias="isBenchmark") + user: Optional[UserFragment] + + +class SweepFragment(GQLResult): + typename__: Typename[Literal["Sweep"]] = "Sweep" + id: GQLId + name: str + display_name: Optional[str] = Field(alias="displayName") + method: str + state: str + description: Optional[str] + best_loss: Optional[float] = Field(alias="bestLoss") + config: str + created_at: str = Field(alias="createdAt") + updated_at: Optional[str] = Field(alias="updatedAt") + run_count: int = Field(alias="runCount") + run_count_expected: Optional[int] = Field(alias="runCountExpected") + + +class UserInfoFragment(GQLResult): + id: GQLId + name: str + username: Optional[str] + email: Optional[str] + admin: Optional[bool] + + +AgentFragment.model_rebuild() +ApiKeyFragment.model_rebuild() +CreatedProjectFragment.model_rebuild() +LegacySweepFragment.model_rebuild() +LightweightRunFragment.model_rebuild() +LightweightRunFragmentUser.model_rebuild() +PageInfoFragment.model_rebuild() +UserFragment.model_rebuild() +UserFragmentApiKeys.model_rebuild() +UserFragmentApiKeysEdges.model_rebuild() +ApiKeyFragment.model_rebuild() +UserFragmentTeams.model_rebuild() +UserFragmentTeamsEdges.model_rebuild() +UserFragmentTeamsEdgesNode.model_rebuild() +ProjectFragment.model_rebuild() +UserFragment.model_rebuild() +SweepFragment.model_rebuild() +UserInfoFragment.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/generate_api_key.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/generate_api_key.py new file mode 100644 index 0000000000000000000000000000000000000000..790ed09a87d5eed0d84992c2fe2777f23e7feca7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/generate_api_key.py @@ -0,0 +1,24 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +from __future__ import annotations + +from typing import Optional + +from pydantic import Field + +from wandb._pydantic import GQLResult + +from .fragments import ApiKeyFragment + + +class GenerateApiKey(GQLResult): + result: Optional[GenerateApiKeyResult] + + +class GenerateApiKeyResult(GQLResult): + api_key: Optional[ApiKeyFragment] = Field(alias="apiKey") + + +GenerateApiKey.model_rebuild() +GenerateApiKeyResult.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_agent_runs.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_agent_runs.py new file mode 100644 index 0000000000000000000000000000000000000000..ad7dbb41f162c3b3a297619699bcdd9bf5452510 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_agent_runs.py @@ -0,0 +1,46 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +from __future__ import annotations + +from typing import List, Optional + +from pydantic import Field + +from wandb._pydantic import GQLResult + +from .fragments import LightweightRunFragment, PageInfoFragment + + +class GetAgentRuns(GQLResult): + project: Optional[GetAgentRunsProject] + + +class GetAgentRunsProject(GQLResult): + sweep: Optional[GetAgentRunsProjectSweep] + + +class GetAgentRunsProjectSweep(GQLResult): + agent: Optional[GetAgentRunsProjectSweepAgent] + + +class GetAgentRunsProjectSweepAgent(GQLResult): + runs: GetAgentRunsProjectSweepAgentRuns + + +class GetAgentRunsProjectSweepAgentRuns(GQLResult): + page_info: PageInfoFragment = Field(alias="pageInfo") + edges: List[GetAgentRunsProjectSweepAgentRunsEdges] + + +class GetAgentRunsProjectSweepAgentRunsEdges(GQLResult): + cursor: str + node: LightweightRunFragment + + +GetAgentRuns.model_rebuild() +GetAgentRunsProject.model_rebuild() +GetAgentRunsProjectSweep.model_rebuild() +GetAgentRunsProjectSweepAgent.model_rebuild() +GetAgentRunsProjectSweepAgentRuns.model_rebuild() +GetAgentRunsProjectSweepAgentRunsEdges.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_default_entity.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_default_entity.py new file mode 100644 index 0000000000000000000000000000000000000000..88b8fc29317c668a489879403268bd8953788ac9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_default_entity.py @@ -0,0 +1,20 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLId, GQLResult + + +class GetDefaultEntity(GQLResult): + viewer: Optional[GetDefaultEntityViewer] + + +class GetDefaultEntityViewer(GQLResult): + id: GQLId + entity: Optional[str] + + +GetDefaultEntity.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_project.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_project.py new file mode 100644 index 0000000000000000000000000000000000000000..e1232e15da7dd6826053752a4c4a6868ed484ece --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_project.py @@ -0,0 +1,17 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLResult + +from .fragments import ProjectFragment + + +class GetProject(GQLResult): + project: Optional[ProjectFragment] + + +GetProject.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_projects.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_projects.py new file mode 100644 index 0000000000000000000000000000000000000000..6c83f3bcd220eee360c86aaf806e1d67b3402547 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_projects.py @@ -0,0 +1,30 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +from __future__ import annotations + +from typing import List, Optional + +from pydantic import Field + +from wandb._pydantic import GQLResult + +from .fragments import PageInfoFragment, ProjectFragment + + +class GetProjects(GQLResult): + models: Optional[GetProjectsModels] + + +class GetProjectsModels(GQLResult): + page_info: PageInfoFragment = Field(alias="pageInfo") + edges: List[GetProjectsModelsEdges] + + +class GetProjectsModelsEdges(GQLResult): + node: Optional[ProjectFragment] + + +GetProjects.model_rebuild() +GetProjectsModels.model_rebuild() +GetProjectsModelsEdges.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_sweep.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_sweep.py new file mode 100644 index 0000000000000000000000000000000000000000..92360640b7d99f20e9f3fba36294c0ea3774098c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_sweep.py @@ -0,0 +1,22 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLResult + +from .fragments import SweepFragment + + +class GetSweep(GQLResult): + project: Optional[GetSweepProject] + + +class GetSweepProject(GQLResult): + sweep: Optional[SweepFragment] + + +GetSweep.model_rebuild() +GetSweepProject.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_sweep_agent.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_sweep_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..b79407566eed7d7d94aafe0e2aa428cfab1dd334 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_sweep_agent.py @@ -0,0 +1,27 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLResult + +from .fragments import AgentFragment + + +class GetSweepAgent(GQLResult): + project: Optional[GetSweepAgentProject] + + +class GetSweepAgentProject(GQLResult): + sweep: Optional[GetSweepAgentProjectSweep] + + +class GetSweepAgentProjectSweep(GQLResult): + agent: Optional[AgentFragment] + + +GetSweepAgent.model_rebuild() +GetSweepAgentProject.model_rebuild() +GetSweepAgentProjectSweep.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_sweep_agents.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_sweep_agents.py new file mode 100644 index 0000000000000000000000000000000000000000..3ea56f54cbb5dcdce2ed793615d7379ab40f6908 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_sweep_agents.py @@ -0,0 +1,37 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +from __future__ import annotations + +from typing import List, Optional + +from wandb._pydantic import GQLResult + +from .fragments import AgentFragment + + +class GetSweepAgents(GQLResult): + project: Optional[GetSweepAgentsProject] + + +class GetSweepAgentsProject(GQLResult): + sweep: Optional[GetSweepAgentsProjectSweep] + + +class GetSweepAgentsProjectSweep(GQLResult): + agents: GetSweepAgentsProjectSweepAgents + + +class GetSweepAgentsProjectSweepAgents(GQLResult): + edges: List[GetSweepAgentsProjectSweepAgentsEdges] + + +class GetSweepAgentsProjectSweepAgentsEdges(GQLResult): + node: AgentFragment + + +GetSweepAgents.model_rebuild() +GetSweepAgentsProject.model_rebuild() +GetSweepAgentsProjectSweep.model_rebuild() +GetSweepAgentsProjectSweepAgents.model_rebuild() +GetSweepAgentsProjectSweepAgentsEdges.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_sweep_legacy.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_sweep_legacy.py new file mode 100644 index 0000000000000000000000000000000000000000..18e4da464bbc7dd1f18f2902d2e6c6837a9dbcd5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_sweep_legacy.py @@ -0,0 +1,22 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLResult + +from .fragments import LegacySweepFragment + + +class GetSweepLegacy(GQLResult): + project: Optional[GetSweepLegacyProject] + + +class GetSweepLegacyProject(GQLResult): + sweep: Optional[LegacySweepFragment] + + +GetSweepLegacy.model_rebuild() +GetSweepLegacyProject.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_sweeps.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_sweeps.py new file mode 100644 index 0000000000000000000000000000000000000000..ff74e654bf31620aa7245cfa274050d13a27e87b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_sweeps.py @@ -0,0 +1,36 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +from __future__ import annotations + +from typing import List, Optional + +from pydantic import Field + +from wandb._pydantic import GQLResult + +from .fragments import PageInfoFragment, SweepFragment + + +class GetSweeps(GQLResult): + project: Optional[GetSweepsProject] + + +class GetSweepsProject(GQLResult): + total_sweeps: int = Field(alias="totalSweeps") + sweeps: Optional[GetSweepsProjectSweeps] + + +class GetSweepsProjectSweeps(GQLResult): + page_info: PageInfoFragment = Field(alias="pageInfo") + edges: List[GetSweepsProjectSweepsEdges] + + +class GetSweepsProjectSweepsEdges(GQLResult): + node: SweepFragment + + +GetSweeps.model_rebuild() +GetSweepsProject.model_rebuild() +GetSweepsProjectSweeps.model_rebuild() +GetSweepsProjectSweepsEdges.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_team_entity.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_team_entity.py new file mode 100644 index 0000000000000000000000000000000000000000..ac6647132735708fdbdfa6ee232f82161525db02 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_team_entity.py @@ -0,0 +1,46 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +from __future__ import annotations + +from typing import List, Optional + +from pydantic import Field + +from wandb._pydantic import GQLId, GQLResult + + +class GetTeamEntity(GQLResult): + entity: Optional[GetTeamEntityEntity] + + +class GetTeamEntityEntity(GQLResult): + id: GQLId + name: str + available: Optional[bool] + photo_url: Optional[str] = Field(alias="photoUrl") + read_only: Optional[bool] = Field(alias="readOnly") + read_only_admin: bool = Field(alias="readOnlyAdmin") + is_team: bool = Field(alias="isTeam") + private_only: bool = Field(alias="privateOnly") + storage_bytes: int = Field(alias="storageBytes") + code_saving_enabled: bool = Field(alias="codeSavingEnabled") + default_access: str = Field(alias="defaultAccess") + is_paid: Optional[bool] = Field(alias="isPaid") + members: List[GetTeamEntityEntityMembers] + + +class GetTeamEntityEntityMembers(GQLResult): + id: Optional[str] + admin: Optional[bool] + pending: Optional[bool] + email: Optional[str] + username: Optional[str] + name: str + photo_url: Optional[str] = Field(alias="photoUrl") + account_type: Optional[str] = Field(alias="accountType") + api_key: Optional[str] = Field(alias="apiKey") + + +GetTeamEntity.model_rebuild() +GetTeamEntityEntity.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_viewer.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_viewer.py new file mode 100644 index 0000000000000000000000000000000000000000..41ac3884942b3edb756611a33c6bac85cddeff30 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/get_viewer.py @@ -0,0 +1,17 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLResult + +from .fragments import UserFragment + + +class GetViewer(GQLResult): + viewer: Optional[UserFragment] + + +GetViewer.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/input_types.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/input_types.py new file mode 100644 index 0000000000000000000000000000000000000000..b908c54f8f41640412d317ade9db254cf8798db6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/input_types.py @@ -0,0 +1,68 @@ +# Generated by ariadne-codegen +# Source: core/api/graphql/schemas/schema-latest.graphql + +from __future__ import annotations + +from typing import List, Optional + +from pydantic import Field + +from wandb._pydantic import GQLId, GQLInput + + +class ArtifactTypeInput(GQLInput): + description: Optional[str] = None + name: str = Field(max_length=128, pattern="^[-\\w]+([ ]*[-.\\w]+)*$") + + +class ProjectIconInput(GQLInput): + color: str + name: str + + +class RateLimitsInput(GQLInput): + create_artifacts: Optional[int] = Field(alias="createArtifacts", default=None) + create_artifacts_time_window: Optional[int] = Field( + alias="createArtifactsTimeWindow", default=None + ) + filestream_count: Optional[float] = Field(alias="filestreamCount", default=None) + filestream_per_run_count: Optional[float] = Field( + alias="filestreamPerRunCount", default=None + ) + filestream_size: Optional[int] = Field(alias="filestreamSize", default=None) + graphql: Optional[int] = None + run_update_count: Optional[float] = Field(alias="runUpdateCount", default=None) + sdk_graphql: Optional[int] = Field(alias="sdkGraphql", default=None) + sdk_graphql_query_seconds: Optional[float] = Field( + alias="sdkGraphqlQuerySeconds", default=None + ) + + +class UpsertModelInput(GQLInput): + access: Optional[str] = None + allow_all_artifact_types_in_registry: Optional[bool] = Field( + alias="allowAllArtifactTypesInRegistry", default=None + ) + artifact_types: Optional[List[ArtifactTypeInput]] = Field( + alias="artifactTypes", default=None + ) + client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None) + description: Optional[str] = None + docker_image: Optional[str] = Field( + alias="dockerImage", default=None, max_length=512 + ) + entity_name: Optional[str] = Field(alias="entityName", default=None) + framework: Optional[str] = None + icon: Optional[ProjectIconInput] = None + id: Optional[str] = None + is_benchmark: Optional[bool] = Field(alias="isBenchmark", default=None) + is_published: Optional[bool] = Field(alias="isPublished", default=None) + linked_benchmark: Optional[GQLId] = Field(alias="linkedBenchmark", default=None) + name: Optional[str] = Field(default=None, max_length=128) + owner: Optional[GQLId] = None + rate_limits: Optional[RateLimitsInput] = Field(alias="rateLimits", default=None) + repo: Optional[str] = Field(default=None, max_length=256) + views: Optional[str] = None + + +UpsertModelInput.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/operations.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/operations.py new file mode 100644 index 0000000000000000000000000000000000000000..2d8368a6ec27e880954e7b3dbba1daa0d99e81a6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/operations.py @@ -0,0 +1,563 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +__all__ = [ + "CREATE_INVITE_GQL", + "CREATE_PROJECT_GQL", + "CREATE_SERVICE_ACCOUNT_GQL", + "CREATE_TEAM_GQL", + "CREATE_USER_FROM_ADMIN_GQL", + "DELETE_API_KEY_GQL", + "DELETE_INVITE_GQL", + "GENERATE_API_KEY_GQL", + "GET_AGENT_RUNS_GQL", + "GET_DEFAULT_ENTITY_GQL", + "GET_PROJECTS_GQL", + "GET_PROJECT_GQL", + "GET_SWEEPS_GQL", + "GET_SWEEP_AGENTS_GQL", + "GET_SWEEP_AGENT_GQL", + "GET_SWEEP_GQL", + "GET_SWEEP_LEGACY_GQL", + "GET_TEAM_ENTITY_GQL", + "GET_VIEWER_GQL", + "SEARCH_USERS_GQL", +] + +GET_PROJECTS_GQL = """ +query GetProjects($entity: String, $cursor: String, $perPage: Int = 50) { + models(entityName: $entity, after: $cursor, first: $perPage) { + pageInfo { + ...PageInfoFragment + } + edges { + node { + ...ProjectFragment + } + } + } +} + +fragment ApiKeyFragment on ApiKey { + id + name + description +} + +fragment PageInfoFragment on PageInfo { + __typename + endCursor + hasNextPage +} + +fragment ProjectFragment on Project { + __typename + id + name + entityName + createdAt + isBenchmark + user { + ...UserFragment + } +} + +fragment UserFragment on User { + id + name + username + email + admin + flags + entity + deletedAt + apiKeys { + edges { + node { + ...ApiKeyFragment + } + } + } + teams { + edges { + node { + name + } + } + } +} +""" + +GET_PROJECT_GQL = """ +query GetProject($name: String!, $entity: String!) { + project(name: $name, entityName: $entity) { + ...ProjectFragment + } +} + +fragment ApiKeyFragment on ApiKey { + id + name + description +} + +fragment ProjectFragment on Project { + __typename + id + name + entityName + createdAt + isBenchmark + user { + ...UserFragment + } +} + +fragment UserFragment on User { + id + name + username + email + admin + flags + entity + deletedAt + apiKeys { + edges { + node { + ...ApiKeyFragment + } + } + } + teams { + edges { + node { + name + } + } + } +} +""" + +CREATE_PROJECT_GQL = """ +mutation CreateProject($input: UpsertModelInput!) { + result: upsertModel(input: $input) { + project { + ...CreatedProjectFragment + } + model { + ...CreatedProjectFragment + } + inserted + } +} + +fragment CreatedProjectFragment on Project { + id + name + entityName + description + access + views +} +""" + +GET_SWEEPS_GQL = """ +query GetSweeps($project: String!, $entity: String!, $cursor: String, $perPage: Int = 50) { + project(name: $project, entityName: $entity) { + totalSweeps + sweeps(after: $cursor, first: $perPage) { + pageInfo { + ...PageInfoFragment + } + edges { + node { + ...SweepFragment + } + } + } + } +} + +fragment PageInfoFragment on PageInfo { + __typename + endCursor + hasNextPage +} + +fragment SweepFragment on Sweep { + __typename + id + name + displayName + method + state + description + bestLoss + config + createdAt + updatedAt + runCount + runCountExpected +} +""" + +GET_SWEEP_GQL = """ +query GetSweep($name: String!, $project: String, $entity: String) { + project(name: $project, entityName: $entity) { + sweep(sweepName: $name) { + ...SweepFragment + } + } +} + +fragment SweepFragment on Sweep { + __typename + id + name + displayName + method + state + description + bestLoss + config + createdAt + updatedAt + runCount + runCountExpected +} +""" + +GET_SWEEP_LEGACY_GQL = """ +query GetSweepLegacy($name: String!, $project: String, $entity: String) { + project(name: $project, entityName: $entity) { + sweep(sweepName: $name) { + ...LegacySweepFragment + } + } +} + +fragment LegacySweepFragment on Sweep { + __typename + id + name + state + bestLoss + config +} +""" + +GET_SWEEP_AGENT_GQL = """ +query GetSweepAgent($agentID: String!, $sweep: String!, $entity: String, $project: String) { + project(name: $project, entityName: $entity) { + sweep(sweepName: $sweep) { + agent(agentName: $agentID) { + ...AgentFragment + } + } + } +} + +fragment AgentFragment on Agent { + id + name + host + state + totalRuns + createdAt + heartbeatAt +} +""" + +GET_SWEEP_AGENTS_GQL = """ +query GetSweepAgents($sweep: String!, $entity: String, $project: String) { + project(name: $project, entityName: $entity) { + sweep(sweepName: $sweep) { + agents { + edges { + node { + ...AgentFragment + } + } + } + } + } +} + +fragment AgentFragment on Agent { + id + name + host + state + totalRuns + createdAt + heartbeatAt +} +""" + +GET_AGENT_RUNS_GQL = """ +query GetAgentRuns($agentID: String!, $sweep: String!, $entity: String, $project: String, $after: String, $before: String, $first: Int, $last: Int, $order: String) { + project(name: $project, entityName: $entity) { + sweep(sweepName: $sweep) { + agent(agentName: $agentID) { + runs(after: $after, before: $before, first: $first, last: $last, order: $order) { + pageInfo { + ...PageInfoFragment + } + edges { + cursor + node { + ...LightweightRunFragment + } + } + } + } + } + } +} + +fragment LightweightRunFragment on Run { + id + tags + name + displayName + sweepName + state + group + jobType + commit + readOnly + createdAt + heartbeatAt + description + notes + historyLineCount + user { + name + username + } +} + +fragment PageInfoFragment on PageInfo { + __typename + endCursor + hasNextPage +} +""" + +GET_TEAM_ENTITY_GQL = """ +query GetTeamEntity($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_TEAM_GQL = """ +mutation CreateTeam($teamName: String!, $teamAdminUserName: String) { + result: createTeam( + input: {teamName: $teamName, teamAdminUserName: $teamAdminUserName} + ) { + entity { + id + name + available + photoUrl + limits + } + } +} +""" + +CREATE_INVITE_GQL = """ +mutation CreateInvite($entity: String!, $email: String, $username: String, $admin: Boolean) { + result: createInvite( + input: {entityName: $entity, email: $email, username: $username, admin: $admin} + ) { + invite { + id + name + email + createdAt + toUser { + name + } + } + } +} +""" + +DELETE_INVITE_GQL = """ +mutation DeleteInvite($id: String, $entity: String) { + result: deleteInvite(input: {id: $id, entityName: $entity}) { + success + } +} +""" + +CREATE_SERVICE_ACCOUNT_GQL = """ +mutation CreateServiceAccount($entity: String!, $description: String!) { + result: createServiceAccount( + input: {description: $description, entityName: $entity} + ) { + user { + id + } + } +} +""" + +SEARCH_USERS_GQL = """ +query SearchUsers($query: String) { + users(query: $query) { + edges { + node { + ...UserFragment + } + } + } +} + +fragment ApiKeyFragment on ApiKey { + id + name + description +} + +fragment UserFragment on User { + id + name + username + email + admin + flags + entity + deletedAt + apiKeys { + edges { + node { + ...ApiKeyFragment + } + } + } + teams { + edges { + node { + name + } + } + } +} +""" + +GET_VIEWER_GQL = """ +query GetViewer { + viewer { + ...UserFragment + } +} + +fragment ApiKeyFragment on ApiKey { + id + name + description +} + +fragment UserFragment on User { + id + name + username + email + admin + flags + entity + deletedAt + apiKeys { + edges { + node { + ...ApiKeyFragment + } + } + } + teams { + edges { + node { + name + } + } + } +} +""" + +GET_DEFAULT_ENTITY_GQL = """ +query GetDefaultEntity { + viewer { + id + entity + } +} +""" + +CREATE_USER_FROM_ADMIN_GQL = """ +mutation CreateUserFromAdmin($email: String!, $admin: Boolean) { + result: createUser(input: {email: $email, admin: $admin}) { + user { + ...UserInfoFragment + } + } +} + +fragment UserInfoFragment on User { + id + name + username + email + admin +} +""" + +DELETE_API_KEY_GQL = """ +mutation DeleteApiKey($id: String!) { + result: deleteApiKey(input: {id: $id}) { + success + } +} +""" + +GENERATE_API_KEY_GQL = """ +mutation GenerateApiKey($description: String) { + result: generateApiKey(input: {description: $description}) { + apiKey { + ...ApiKeyFragment + } + } +} + +fragment ApiKeyFragment on ApiKey { + id + name + description +} +""" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/search_users.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/search_users.py new file mode 100644 index 0000000000000000000000000000000000000000..4bcce4995139fc80cf9477b9274ff8ef919bc079 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/_generated/search_users.py @@ -0,0 +1,27 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/api/ + +from __future__ import annotations + +from typing import List, Optional + +from wandb._pydantic import GQLResult + +from .fragments import UserFragment + + +class SearchUsers(GQLResult): + users: Optional[SearchUsersUsers] + + +class SearchUsersUsers(GQLResult): + edges: List[SearchUsersUsersEdges] + + +class SearchUsersUsersEdges(GQLResult): + node: Optional[UserFragment] + + +SearchUsers.model_rebuild() +SearchUsersUsers.model_rebuild() +SearchUsersUsersEdges.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/attrs.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/attrs.py new file mode 100644 index 0000000000000000000000000000000000000000..39bc5b633473b2cd6aeb0a32a3681c0003dec4c9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/attrs.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import wandb + +from ..sdk.lib import ipython + + +class Attrs: + def __init__(self, attrs: Mapping[str, Any]): + self._attrs = dict(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: + return self._attrs[key] + elif name in self._attrs: + return self._attrs[name] + else: + raise AttributeError(f"{repr(self)!r} object has no attribute {name!r}") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0266b9f204d4a5487c5d66a6d2487c3670055082 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/__init__.py @@ -0,0 +1 @@ +from .internals.util import Namespace diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23d3e695b1a84e48dbcafc9c478a2847dbeecdc9 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/__pycache__/mlflow.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/__pycache__/mlflow.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..018c592435f5e08bdf71a05caa10bebb9052c696 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/__pycache__/mlflow.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/__pycache__/validation.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/__pycache__/validation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b36b9ae0590bbfaa027aecae04b2fd4e586d8a99 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/__pycache__/validation.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/__pycache__/wandb.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/__pycache__/wandb.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c63f74c26d583ffd5e2edb801b7e8ab3a933c630 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/__pycache__/wandb.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/internals/__pycache__/internal.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/internals/__pycache__/internal.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32f2a39c1b85ccd64f1f4a58e76defb343ab372e Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/internals/__pycache__/internal.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/internals/__pycache__/protocols.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/internals/__pycache__/protocols.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b672c727aedf5019d5a84362dd4bebc5591db1d3 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/internals/__pycache__/protocols.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/internals/__pycache__/util.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/internals/__pycache__/util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c2766d98e02c96fedbd4701840fc8508a9fa166 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/internals/__pycache__/util.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/internals/internal.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/internals/internal.py new file mode 100644 index 0000000000000000000000000000000000000000..ec49f8b837a3fe81898a22df039ca2f0e7066124 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/internals/internal.py @@ -0,0 +1,378 @@ +from __future__ import annotations + +import json +import logging +import math +import os +import queue +from collections.abc import Iterable +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +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: Iterable[Artifact] | None = None, + used_artifacts: Iterable[Artifact] | None = 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 + and (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 and (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 and (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: dict[str, Any] | None = 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: Iterable[Artifact] | None = None, + extra_used_arts: Iterable[Artifact] | None = None, + config: SendManagerConfig | None = None, + overrides: dict[str, Any] | None = None, + settings_override: dict[str, Any] | None = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/internals/protocols.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/internals/protocols.py new file mode 100644 index 0000000000000000000000000000000000000000..e3c4af604e1f7a7935ee30887e2475dda85f3c1c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/internals/protocols.py @@ -0,0 +1,96 @@ +from __future__ import annotations + +import logging +from collections.abc import Iterable +from typing import Any, Literal, Protocol, 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) -> str | None: ... # pragma: no cover + + def job_type(self) -> str | None: ... # pragma: no cover + + def display_name(self) -> str: ... # pragma: no cover + + def notes(self) -> str | None: ... # pragma: no cover + + def tags(self) -> list[str] | None: ... # pragma: no cover + + def artifacts(self) -> Iterable[Artifact] | None: ... # pragma: no cover + + def used_artifacts(self) -> Iterable[Artifact] | None: ... # pragma: no cover + + def os_version(self) -> str | None: ... # pragma: no cover + + def python_version(self) -> str | None: ... # pragma: no cover + + def cuda_version(self) -> str | None: ... # pragma: no cover + + def program(self) -> str | None: ... # pragma: no cover + + def host(self) -> str | None: ... # pragma: no cover + + def username(self) -> str | None: ... # pragma: no cover + + def executable(self) -> str | None: ... # pragma: no cover + + def gpus_used(self) -> str | None: ... # pragma: no cover + + def cpus_used(self) -> int | None: ... # pragma: no cover + + def memory_used(self) -> int | None: ... # pragma: no cover + + def runtime(self) -> int | None: ... # pragma: no cover + + def start_time(self) -> int | None: ... # pragma: no cover + + def code_path(self) -> str | None: ... # pragma: no cover + + def cli_version(self) -> str | None: ... # pragma: no cover + + def files( + self, + ) -> Iterable[tuple[PathStr, Policy]] | None: ... # pragma: no cover + + def logs(self) -> Iterable[str] | None: ... # pragma: no cover diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/internals/util.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/internals/util.py new file mode 100644 index 0000000000000000000000000000000000000000..4c8c6234aee88c1de35fc321c37cee497b1c75c4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/internals/util.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +import logging +import sys +import traceback +from collections.abc import Iterable +from concurrent.futures import ThreadPoolExecutor, as_completed +from dataclasses import dataclass + + +@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: int | None = 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: int | None = None +): + if parallel: + return parallelize( + func, + iterable, + max_workers=max_workers, + ) + + return [func(x) for x in iterable] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/mlflow.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/mlflow.py new file mode 100644 index 0000000000000000000000000000000000000000..24ef23e84bc1e0f6e589e7db735ea830592f2af9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/mlflow.py @@ -0,0 +1,257 @@ +from __future__ import annotations + +import itertools +import logging +import re +from collections import defaultdict +from collections.abc import Iterable +from typing import Any + +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: + 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) -> str | None: + # this is nesting? Parent at `run.info.tags.get("mlflow.parentRunId")` + return f"Experiment {self.run.info.experiment_id}" + + def job_type(self) -> str | None: + # 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) -> str | None: + return self.run.data.tags.get("mlflow.note.content") + + def tags(self) -> list[str] | None: + ... + + # 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) -> Iterable[Artifact] | None: # 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) -> Iterable[Artifact] | None: # type: ignore + ... # pragma: no cover + + def os_version(self) -> str | None: ... # pragma: no cover + + def python_version(self) -> str | None: ... # pragma: no cover + + def cuda_version(self) -> str | None: ... # pragma: no cover + + def program(self) -> str | None: ... # pragma: no cover + + def host(self) -> str | None: ... # pragma: no cover + + def username(self) -> str | None: ... # pragma: no cover + + def executable(self) -> str | None: ... # pragma: no cover + + def gpus_used(self) -> str | None: ... # pragma: no cover + + def cpus_used(self) -> int | None: # can we get the model? + ... # pragma: no cover + + def memory_used(self) -> int | None: ... # pragma: no cover + + def runtime(self) -> int | None: + 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) -> int | None: + return self.run.info.start_time // 1000 + + def code_path(self) -> str | None: ... # pragma: no cover + + def cli_version(self) -> str | None: ... # pragma: no cover + + def files(self) -> Iterable[tuple[str, str]] | None: ... # pragma: no cover + + def logs(self) -> Iterable[str] | None: ... # 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: str | None = None, + *, + custom_api_kwargs: dict[str, Any] | None = 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: int | None = 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: Namespace | None = None, + config: internal.SendManagerConfig | None = 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: Namespace | None = None, + parallel: bool = True, + max_workers: int | None = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/validation.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/validation.py new file mode 100644 index 0000000000000000000000000000000000000000..f07d9a7bd8427fc2879710803be73023b980a801 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/validation.py @@ -0,0 +1,102 @@ +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) + return all(_check_entry_is_downloable(entry) for entry in entries) + + +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) + + return expected_size == actual_size diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/wandb.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/wandb.py new file mode 100644 index 0000000000000000000000000000000000000000..1ab88f98ed572aaad3c5897f54164d4e6be1a32c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/importers/wandb.py @@ -0,0 +1,1610 @@ +"""Tooling for the W&B Importer.""" + +from __future__ import annotations + +import itertools +import json +import logging +import numbers +import os +import re +import shutil +from collections.abc import Iterable, Iterator +from dataclasses import dataclass, field +from datetime import datetime as dt +from pathlib import Path +from typing import Any +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.sdk.lib import json_util +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: Iterable[tuple[str, str]] | None = None + self._artifacts: Iterable[Artifact] | None = None + self._used_artifacts: Iterable[Artifact] | None = None + self._parquet_history_paths: Iterable[str] | None = 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) -> str | None: + return self.run.group + + def job_type(self) -> str | None: + return self.run.job_type + + def display_name(self) -> str: + return self.run.display_name + + def notes(self) -> str | None: + # 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) -> list[str] | None: + return self.run.tags + + def artifacts(self) -> Iterable[Artifact] | None: + 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) -> Iterable[Artifact] | None: + 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) -> str | None: ... # pragma: no cover + + def python_version(self) -> str | None: + return self._metadata_file().get("python") + + def cuda_version(self) -> str | None: ... # pragma: no cover + + def program(self) -> str | None: ... # pragma: no cover + + def host(self) -> str | None: + return self._metadata_file().get("host") + + def username(self) -> str | None: ... # pragma: no cover + + def executable(self) -> str | None: ... # pragma: no cover + + def gpus_used(self) -> str | None: ... # pragma: no cover + + def cpus_used(self) -> int | None: # can we get the model? + ... # pragma: no cover + + def memory_used(self) -> int | None: ... # pragma: no cover + + def runtime(self) -> int | None: + 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) -> int | None: + t = dt.fromisoformat(self.run.created_at).timestamp() * 1000 + return int(t) + + def code_path(self) -> str | None: + path = self._metadata_file().get("codePath", "") + return f"code/{path}" + + def cli_version(self) -> str | None: + return self._config_file().get("_wandb", {}).get("value", {}).get("cli_version") + + def files(self) -> Iterable[tuple[PathStr, Policy]] | None: + 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) -> Iterable[str] | None: + 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) -> str | None: + 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: dict[str, Any] | None = 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: Namespace | None = None, + config: internal.SendManagerConfig | None = 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": "allow", + "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: Namespace | None = 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: Namespace | None = 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": "allow", + "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: Run | None = _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: str | None = None, project: str | None = 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 = 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: Iterable[Namespace] | None = None, + api: Api | None = None, + remapping: dict[Namespace, Namespace] | None = 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: Namespace | None = 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: Namespace | None = 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": "allow", + "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: Iterable[Namespace] | None = None, + remapping: dict[Namespace, Namespace] | None = None, + parallel: bool = True, + incremental: bool = True, + max_workers: int | None = None, + limit: int | None = 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: Iterable[Namespace] | None = None, + limit: int | None = None, + remapping: dict[Namespace, Namespace] | None = 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: Iterable[Namespace] | None = None, + incremental: bool = True, + max_workers: int | None = None, + remapping: dict[Namespace, Namespace] | None = 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: Iterable[Namespace] | None = None, + incremental: bool = True, + remapping: dict[Namespace, Namespace] | None = 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: dict[Namespace, Namespace] | None = 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: dict[Namespace, Namespace] | None = 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: dict[Namespace, Namespace] | None = 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: dict[Namespace, Namespace] | None = 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: Iterable[Namespace] | None = None, + limit: int | None = None, + skip_ids: list[str] | None = None, + start_date: str | None = None, + api: Api | None = 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: str | None = None, api: Api | None = 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: Iterable[Namespace] | None = None, + limit: int | None = None, + api: Api | None = 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: Iterable[Namespace] | None = None, + limit: int | None = None, + api: Api | None = 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) -> pl.DataFrame | None: + 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) -> str | None: + 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: str | None = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/internal.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/internal.py new file mode 100644 index 0000000000000000000000000000000000000000..ed2ffa390aefd0dda271c2fe2917a3e720a6b354 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/internal.py @@ -0,0 +1,224 @@ +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 + + 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) -> None: + return self.api.clear_setting(key) + + def set_setting(self, key: str, value: Any) -> None: + return self.api.set_setting(key, value) + + 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 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 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/normalize.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/normalize.py new file mode 100644 index 0000000000000000000000000000000000000000..ee58a11a3e50f66faf5d3ec3044755bfcfb4b1eb --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/normalize.py @@ -0,0 +1,85 @@ +"""normalize.""" + +from __future__ import annotations + +import ast +import sys +from collections.abc import Callable +from functools import wraps +from typing import TypeVar + +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): + import requests + + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/paginator.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/paginator.py new file mode 100644 index 0000000000000000000000000000000000000000..506ea65851bbd826aad535869c8c3ac17b443eff --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/paginator.py @@ -0,0 +1,204 @@ +from __future__ import annotations + +from abc import ABC, abstractmethod +from collections.abc import Iterable, Iterator, Mapping, Sized +from typing import TYPE_CHECKING, Any, ClassVar, Generic, TypeVar, overload + +import wandb +from wandb._strutils import nameof + +if TYPE_CHECKING: + from wandb_graphql.language.ast import Document + + from wandb._pydantic import Connection + from wandb.apis.public.api import RetryingClient + +_WandbT = TypeVar("_WandbT") +"""Generic type variable for a W&B object.""" + +_NodeT = TypeVar("_NodeT") +"""Generic type variable for a parsed GraphQL relay node.""" + + +class Paginator(Iterator[_WandbT], ABC): + """An iterator for paginated objects from GraphQL requests.""" + + QUERY: Document | ClassVar[Document | None] + + def __init__( + self, + client: RetryingClient, + variables: Mapping[str, Any], + per_page: int = 50, # We don't allow unbounded paging + ): + self.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[_WandbT] = [] + self.index: int = -1 + self.last_response: Any | None = None + + def __iter__(self) -> Iterator[_WandbT]: + 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) -> Iterable[_WandbT]: + """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) -> _WandbT: ... + @overload + def __getitem__(self, index: slice) -> list[_WandbT]: ... + + def __getitem__(self, index: int | slice) -> _WandbT | list[_WandbT]: + 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) -> _WandbT: + 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[_WandbT], Sized, ABC): + """A Paginator for objects with a known total count.""" + + last_response: dict[str, Any] | None = None + + @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 + + +class RelayPaginator(Paginator[_WandbT], Generic[_NodeT, _WandbT], ABC): + """A Paginator for GQL relay-style nodes parsed via Pydantic. + + + """ + + last_response: Connection[_NodeT] | None + + _start: str | None + """Optional, opaque cursor used to "resume" pagination from a previous query. + + If present, this is only used to fetch the first page. + """ + + def __init__( + self, + client: RetryingClient, + variables: Mapping[str, Any], + per_page: int = 50, + start: str | None = None, + ): + super().__init__(client, variables, per_page) + self._start = start + + @property + def more(self) -> bool: + return (conn := self.last_response) is None or conn.has_next + + @property + def cursor(self) -> str | None: + """An opaque cursor that marks the start of the next page to fetch. + + This value may be saved and passed as `start=` to a later paginated query + to resume iteration from where this paginator left off. + """ + return conn.next_cursor if (conn := self.last_response) else self._start + + @abstractmethod + def _convert(self, node: _NodeT) -> _WandbT | Any: + """Convert a parsed GraphQL node into the iterated object. + + If a falsey value is returned, it will be skipped during iteration. + """ + raise NotImplementedError + + def convert_objects(self) -> Iterable[_WandbT]: + # Default implementation. Subclasses can override this if if more complex + # logic is needed, but ideally most shouldn't need to. + if conn := self.last_response: + yield from filter(None, map(self._convert, conn.nodes())) + + +class SizedRelayPaginator(RelayPaginator[_NodeT, _WandbT], Sized, ABC): + """A Paginator for GQL nodes parsed via Pydantic, with a known total count. + + + """ + + last_response: Connection[_NodeT] | None + + def __len__(self) -> int: + """Returns the total number of objects to expect.""" + # If the first page hasn't been fetched yet, do that first + if self.last_response is None: + self._load_page() + if (conn := self.last_response) and (total := conn.total_count) is not None: + return total + raise NotImplementedError(f"{nameof(type(self))!r} doesn't provide length") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c185dcce30c94f695f924614026c3ffc3736b28c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__init__.py @@ -0,0 +1,87 @@ +__all__ = ( + "Api", + "RetryingClient", # doc:exclude + "requests", # doc:exclude + "ArtifactCollection", + "ArtifactCollections", + "ProjectArtifactCollections", + "ArtifactFiles", + "Artifacts", + "ArtifactType", + "ArtifactTypes", + "DownloadHistoryResult", + "RunArtifacts", + "Automations", + "File", + "Files", + "HistoryScan", # doc:exclude + "IncompleteRunHistoryError", + "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", + "AgentRuns", + "Sweep", + "Member", + "Team", + "User", +) + + +from wandb.apis.public.api import Api, RetryingClient +from wandb.apis.public.artifacts import ( + ArtifactCollection, + ArtifactCollections, + ArtifactFiles, + Artifacts, + ArtifactType, + ArtifactTypes, + ProjectArtifactCollections, + RunArtifacts, +) +from wandb.apis.public.automations import Automations +from wandb.apis.public.files import FILE_FRAGMENT, File, Files +from wandb.apis.public.history import BetaHistoryScan, 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, 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.runhistory.downloads import ( + DownloadHistoryResult, + IncompleteRunHistoryError, +) +from wandb.apis.public.runs import RUN_FRAGMENT, AgentRuns, Run, Runs +from wandb.apis.public.sweeps import Sweep +from wandb.apis.public.teams import Member, Team +from wandb.apis.public.users import User diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..daac12147326d2ab267d95e4588294442c2fce5e Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/api.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1d48ba72c2b646486a948c31a7a06ef42df6323 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/api.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/artifacts.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/artifacts.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcf8d582ad9cd0bda992d2fc1b9277de544ce78a Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/artifacts.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/automations.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/automations.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e10ad3fdd03dd721fbf58e2241927e07614c921c Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/automations.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/const.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/const.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebf10dd823b22de41a9d190f759bf7cacb904f79 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/const.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/files.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/files.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c6c0a9d08e527fd64c873226851b99fd2ceea23 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/files.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/history.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/history.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61d4ee515af54ecb27e1964f9fd891f11f4377cd Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/history.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/integrations.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/integrations.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac57dc931ea41b7d5204bda91e66e04fccf49c93 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/integrations.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/jobs.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/jobs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e01b0a9f04a86c80c637ea16eeffec921fdaaac5 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/jobs.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/projects.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/projects.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88b988df9bcb52a3963685136c76d8779b5c2fac Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/projects.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/query_generator.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/query_generator.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56372a9e8de5174d70755d3c5020573a740203db Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/query_generator.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/reports.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/reports.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9aa74d57113fd9e4b42a20aee385e3976eee0f49 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/reports.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/runs.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/runs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e924e7ba6085c1edac0ecdfe166bd442966b0c8 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/runs.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/service_api.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/service_api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d43d22d55c909ec460c85913a6081da27514e0e Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/service_api.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/sweeps.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/sweeps.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e00579f9c89d83dfb3345f72281d50b051dccf6 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/sweeps.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/teams.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/teams.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8aebadaa7e3774289a83ba2405c5fcd37d31691e Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/teams.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/users.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/users.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..628cea6cfec64e8b40d392501b11cca2c96863bf Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/users.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/utils.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13d0dc3c2f16440795753d9eec62271b24fc0017 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/__pycache__/utils.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/api.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/api.py new file mode 100644 index 0000000000000000000000000000000000000000..615963def646f230ea08fc66a60a72e44d6452fe --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/api.py @@ -0,0 +1,2705 @@ +"""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/models/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.ai/models/track/public-api-guide). +""" + +from __future__ import annotations + +import json +import logging +import os +import urllib +from collections.abc import Callable, Iterator +from http import HTTPStatus +from typing import TYPE_CHECKING, Any, Literal + +from pydantic import ValidationError +from typing_extensions import Unpack, overload +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.service_api import ServiceApi +from wandb.apis.public.utils import ( + PathType, + fetch_org_from_settings_or_entity, + gql_compat, + parse_org_from_registry_path, +) +from wandb.errors import UsageError +from wandb.proto import wandb_internal_pb2 as pb +from wandb.proto.wandb_telemetry_pb2 import Deprecated +from wandb.sdk import wandb_login, wandb_setup +from wandb.sdk.artifacts._gqlutils import resolve_org_entity_name +from wandb.sdk.internal.internal_api import Api as InternalApi +from wandb.sdk.launch.utils import LAUNCH_DEFAULT_PROJECT +from wandb.sdk.lib import retry, runid, wbauth +from wandb.sdk.lib.deprecation import warn_and_record_deprecation +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: + """Legacy GraphQL client for public API requests not yet routed through wandb-core. + + New public API GraphQL calls should use `ServiceApi.execute_graphql`. + Delete this once all `execute()` call sites have moved to wandb-core. + + + """ + + INFO_QUERY = gql( + """ + query ServerInfo{ + serverInfo { + cliVersionInfo + latestLocalVersionInfo { + outOfDate + latestVersionString + versionOnThisInstanceString + } + } + } + """ + ) + + def __init__(self, client: Client): + self._server_info = None + self._client = client + self._execute_decorated: Callable[..., Any] | None = None + + def execute(self, *args, **kwargs): + if self._execute_decorated is None: + self._execute_decorated = self._build_execute_wrapper() + return self._execute_decorated(*args, **kwargs) + + def _build_execute_wrapper(self) -> Callable[..., Any]: + import requests + + @retry.retriable( + retry_timedelta=RETRY_TIMEDELTA, + check_retry_fn=util.no_retry_auth, + retryable_exceptions=(RetryError, requests.RequestException), + ) + def _wrapped(*args, **kwargs): + 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., " + f"`api = wandb.Api(timeout={timeout + 10})` to increase the graphql timeout." + ) + raise + + return _wrapped + + @property + def app_url(self): + return util.app_url(self._client.transport.url.replace("/graphql", "")) + "/" + + @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) + + 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() + self.settings.update(overrides or {}) + self.settings["base_url"] = self.settings["base_url"].rstrip("/") + + if api_key: + self._auth = wbauth.AuthApiKey( + host=self.settings["base_url"], + api_key=api_key, + ) + else: + self._auth = self._load_auth(base_url=self.settings["base_url"]) + + base_url = self._auth.host.url + + if isinstance(self._auth, wbauth.AuthApiKey): + self.api_key = self._auth.api_key + wandb_login._verify_login( + key=self.api_key, + base_url=base_url, + ) + else: + self.api_key = None + + session_auth = self._auth.as_requests_auth() + + 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 + proxies = self.settings.get("_proxies") or json.loads( + os.environ.get("WANDB__PROXIES", "{}") + ) + settings = wandb_setup.singleton().settings.model_copy() + settings.base_url = base_url + settings.api_key = self.api_key or "" + self._service_api: ServiceApi = ServiceApi(settings=settings) + + self._base_client = Client( + transport=GraphQLSession( + headers={ + "User-Agent": self.user_agent, + "Use-Admin-Privileges": "true", + }, + 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=session_auth, + url="{}/graphql".format(base_url), + proxies=proxies, + ) + ) + self._client = RetryingClient(self._base_client) + self._sentry = wandb.analytics.sentry.Sentry(pid=os.getpid()) + self._configure_sentry() + + def _load_auth(self, base_url: str) -> wbauth.Auth: + """Load or prompt for authentication credentials.""" + auth = wbauth.authenticate_session( + host=base_url, + source="wandb.Api()", + no_offline=True, + input_timeout=wandb_setup.singleton().settings.login_timeout, + ) + + if not auth: + raise UsageError( + "No authentication configured. Use `wandb login` to log in." + ) + + return auth + + def _configure_sentry(self) -> None: + if not env.error_reporting_enabled(): + return + + import requests + + 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. + """ + from wandb.apis._generated import CREATE_PROJECT_GQL, UpsertModelInput + + gql_input = UpsertModelInput(name=name, entity_name=entity) + self.client.execute(gql(CREATE_PROJECT_GQL), {"input": gql_input.model_dump()}) + + 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 self._create_run(run_id=run_id, project=project, entity=entity) + + def _create_run( + self, + *, + run_id: str | None = None, + project: str | None = None, + entity: str | None = None, + state: Literal["running", "pending"] = "running", + ) -> public.Run: + self._sentry.message("Invoking Run.create", level="info") + run_id = run_id or runid.generate_id() + project = project or self.settings.get("project") or "uncategorized" + mutation = """ + 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 = self._service_api.execute_graphql( + mutation, + variables, + ) + res = res["upsertBucket"]["bucket"] + return public.Run( + self.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 + service_api=self._service_api, + ) + + 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, + service_api=self._service_api, + ) + + 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, + service_api=self._service_api, + ) + + 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.""" + from wandb.apis._generated import GET_DEFAULT_ENTITY_GQL, GetDefaultEntity + + if self._default_entity is None: + data = self._client.execute(gql(GET_DEFAULT_ENTITY_GQL)) + result = GetDefaultEntity.model_validate(data) + if (viewer := result.viewer) and (entity := viewer.entity): + self._default_entity = 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 wandb.apis._generated import GET_VIEWER_GQL, GetViewer + + from .users import User + + if self._viewer is None: + data = self._client.execute(gql(GET_VIEWER_GQL)) + result = GetViewer.model_validate(data) + if (viewer := result.viewer) is None: + msg = "Unable to fetch user data from W&B, please verify your API key is valid." + raise ValueError(msg) + self._viewer = User(self._client, viewer.model_dump(), api_key=self.api_key) + 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], + service_api=self._service_api, + ) + 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: str) -> tuple[str, str, str]: + """Parse url, filepath, or docker paths. + + Allows paths in the following formats: + - entity/project/runs/id (URL) + - entity/project/id + - entity/project:id (Docker style) + - project/id + - project:id + - id (cannot contain colons) + + The path may also start with /runs/ or /sweeps/. + + Returns: + A tuple with the extracted (entity, project, id). + + Raises: + ValueError: If the path is in an invalid format or is missing + an entity that is not otherwise provided. + """ + # NOTE: This may result in a GQL call. Ideally we'd only access + # `self.default_entity` lazily, but changing this requires care as it + # changes when `self._default_entity` is cached and could impact other + # code. + entity: str | None = self.settings["entity"] or self.default_entity + project: str | None = self.settings["project"] + id: str | None = None + + input_path = path + path = path.replace("/runs/", "/") + path = path.replace("/sweeps/", "/") + path = path.strip("/ ") # slashes and spaces + + parts = path.split("/") + + # "entity/project/runs/id" + if len(parts) == 4 and parts[2] == "runs": + entity, project, id = parts[0], parts[1], parts[3] + + # "entity/project/id" + elif len(parts) == 3: + entity, project, id = parts[0], parts[1], parts[2] + + elif len(parts) == 2: + # "entity/project:id" + if ":" in parts[1]: + entity = parts[0] + project, id = parts[1].split(":", maxsplit=1) + + # "project/id" + else: + project, id = parts[0], parts[1] + + elif len(parts) == 1 and parts[0]: # Don't match the empty string. + # "project:id" + if ":" in parts[0]: + project, id = parts[0].split(":", maxsplit=1) + + # "id" + else: + id = parts[0] + + # Ignore whitespace. + entity = entity and entity.strip() + project = project and project.strip() + id = id and id.strip() + + if not entity: + raise ValueError(f"Invalid path: {input_path!r} (missing entity)") + if not project: + raise ValueError(f"Invalid path: {input_path!r} (missing project)") + if not id: + raise ValueError(f"Invalid path: {input_path!r}") + + return entity, project, id + + @overload + def _parse_artifact_path(self, path: None) -> tuple[str | None, str]: ... + @overload + def _parse_artifact_path(self, path: str) -> tuple[str | None, str, str]: ... + + def _parse_artifact_path(self, path: str | None) -> tuple[str | None, ...]: + """Return project, entity and artifact name for project specified by path.""" + from wandb.sdk.artifacts._validators import ArtifactPath + + 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. + 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, + service_api=self._service_api, + ) + 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. + """ + from wandb.sdk.artifacts._validators import is_artifact_registry_project + + # 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 = resolve_org_entity_name( + self.client, non_org_entity=settings_entity, org_or_entity=org + ) + return public.Project( + self.client, entity, name, {}, service_api=self._service_api + ) + + 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. + 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, + {}, + service_api=self._service_api, + ), + name=name, + per_page=per_page, + service_api=self._service_api, + ) + 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 wandb.apis._generated import SEARCH_USERS_GQL, SearchUsers + + from .users import User + + data = self._client.execute(gql(SEARCH_USERS_GQL), {"query": username_or_email}) + result = SearchUsers.model_validate(data) + if not (conn := result.users) or not (edges := conn.edges): + return None + if len(edges) > 1: + msg = f"Found multiple users, returning the first user matching {username_or_email!r}" + wandb.termwarn(msg) + return User(self._client, edges[0].node.model_dump(), api_key=self.api_key) + + 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 wandb.apis._generated import SEARCH_USERS_GQL, SearchUsers + + from .users import User + + data = self._client.execute(gql(SEARCH_USERS_GQL), {"query": username_or_email}) + result = SearchUsers.model_validate(data) + if not ((conn := result.users) and (edges := conn.edges)): + return [] + return [ + User(self._client, edge.node.model_dump(), api_key=self.api_key) + for edge in 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 + import wandb + from wandb.apis.public import Api + + # 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, + service_api=self._service_api, + ) + 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, + service_api=self._service_api, + ) + 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, + service_api=self._service_api, + ) + + 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, + service_api=self._service_api, + ) + + @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, + service_api=self._service_api, + ) + return self._sweeps[path] + + def _get_sweep( + self, + entity: str | None = None, + project: str | None = None, + sweep_id: str | None = None, + order: str | None = None, + query: Any | None = None, + **kwargs: Any, + ) -> public.Sweep | None: + return public.Sweep.get( + self.client, + entity, + project, + sweep_id, + order=order, + query=query, + service_api=self._service_api, + **kwargs, + ) + + @normalize_exceptions + def artifact_types( + self, + project: str | None = None, + start: str | None = None, + ) -> ArtifactTypes: + """Returns a collection of matching artifact types. + + Args: + project: The project name or path to filter on. + start: Pagination cursor for resuming a past query, captured + from a previous paginator's `.cursor` attribute. + + Returns: + An iterable `ArtifactTypes` object. + """ + from wandb.sdk.artifacts._validators import is_artifact_registry_project + + 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 = resolve_org_entity_name( + self.client, non_org_entity=settings_entity, org_or_entity=org + ) + return ArtifactTypes( + self.client, entity, project, start=start, service_api=self._service_api + ) + + @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 wandb.sdk.artifacts._validators import is_artifact_registry_project + + 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 = resolve_org_entity_name( + self.client, non_org_entity=settings_entity, org_or_entity=org + ) + return ArtifactType( + self.client, entity, project, type_name, service_api=self._service_api + ) + + @normalize_exceptions + def artifact_collections( + self, + project_name: str, + type_name: str, + per_page: int = 50, + start: str | None = None, + ) -> 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. + Usually there is no reason to change this. + start: Pagination cursor for resuming a past query, captured + from a previous paginator's `.cursor` attribute. + + Returns: + An iterable `ArtifactCollections` object. + """ + from wandb.sdk.artifacts._validators import is_artifact_registry_project + + 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 = resolve_org_entity_name( + self.client, non_org_entity=settings_entity, org_or_entity=org + ) + return ArtifactCollections( + self.client, + entity, + project, + type_name, + per_page=per_page, + start=start, + service_api=self._service_api, + ) + + @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 wandb.sdk.artifacts._validators import is_artifact_registry_project + + 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 = resolve_org_entity_name( + self.client, non_org_entity=settings_entity, org_or_entity=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, + service_api=self._service_api, + ) + + @normalize_exceptions + def artifact_versions(self, type_name, name, per_page=50): + """Deprecated. Use `Api.artifacts(type_name, name)` method instead.""" + warn_and_record_deprecation( + feature=Deprecated(api__artifact_versions=True), + 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, + start: 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. Usually + there is no reason to change this. + tags: Only return artifacts with all of these tags. + start: Pagination cursor for resuming a past query, captured + from a previous paginator's `.cursor` attribute. + + 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") + ``` + + Pause iteration and resume later from the same position by saving + the paginator's `.cursor` and passing it as `start=`: + + ```python + from itertools import islice + + import wandb + + api = wandb.Api() + + # Consume the first page of results, then save the cursor. + page_size = 10 + artifacts = api.artifacts( + type_name="type", + name="entity/project/artifact_name", + per_page=page_size, + ) + first_page = list(islice(artifacts, page_size)) + + saved_cursor = artifacts.cursor + + # Later (e.g. in a new process), resume iteration from the saved cursor. + remaining_artifacts = api.artifacts( + type_name="type", + name="entity/project/artifact_name", + per_page=page_size, + start=saved_cursor, + ) + ``` + """ + from wandb.sdk.artifacts._validators import is_artifact_registry_project + + 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 = resolve_org_entity_name( + self.client, non_org_entity=settings_entity, org_or_entity=org + ) + return Artifacts( + self.client, + entity, + project, + collection_name, + type_name, + per_page=per_page, + tags=tags, + start=start, + service_api=self._service_api, + ) + + @normalize_exceptions + def _artifact( + self, name: str, type: str | None = None, enable_tracking: bool = False + ) -> Artifact: + from wandb.sdk.artifacts._validators import ( + FullArtifactPath, + is_artifact_registry_project, + ) + 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 = resolve_org_entity_name( + self.client, non_org_entity=settings_entity, org_or_entity=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, + service_api=self._service_api, + 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 + + def _artifact_from_id(self, artifact_id: str) -> Artifact | None: + from wandb.sdk.artifacts.artifact import Artifact + + return Artifact._from_id( + artifact_id, + self.client, + service_api=self._service_api, + ) + + @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 following 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, service_api=self._service_api) + + @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. + """ + import requests + + 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") + ``` + + """ + import requests + + 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") + ``` + """ + import requests + + 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, + per_page: int = 100, + start: str | 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` + per_page: Sets the page size for query pagination. + start: Pagination cursor for resuming a past query, captured + from a previous paginator's `.cursor` attribute. + + 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"}]} + ) + ``` + + Pause iteration and resume later from the same position by saving + the paginator's `.cursor` and passing it as `start=`: + + ```python + from itertools import islice + + import wandb + + api = wandb.Api() + + # Consume the first page of results, then save the cursor. + page_size = 10 + registries = api.registries(per_page=page_size) + first_page = list(islice(registries, page_size)) + + saved_cursor = registries.cursor + + # Later (e.g. in a new process), resume iteration from the saved cursor. + remaining_registries = api.registries(per_page=page_size, start=saved_cursor) + ``` + """ + if not self._service_api.feature_enabled(pb.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=organization, + filter=filter, + per_page=per_page, + start=start, + service_api=self._service_api, + ) + + @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 self._service_api.feature_enabled(pb.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, + service_api=self._service_api, + ) + 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 self._service_api.feature_enabled( + pb.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, + service_api=self._service_api, + ) + + @tracked + def integrations( + self, + entity: str | None = None, + *, + per_page: int = 50, + start: str | None = None, + ) -> 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 + + variables = {"entity": entity or self.default_entity} + return Integrations( + self.client, variables=variables, per_page=per_page, start=start + ) + + @tracked + def webhook_integrations( + self, entity: str | None = None, *, per_page: int = 50, start: str | None = None + ) -> 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 + + variables = {"entity": entity or self.default_entity} + return WebhookIntegrations( + self.client, variables=variables, per_page=per_page, start=start + ) + + @tracked + def slack_integrations( + self, *, entity: str | None = None, per_page: int = 50, start: str | None = None + ) -> 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 + + variables = {"entity": entity or self.default_entity} + return SlackIntegrations( + self.client, variables=variables, per_page=per_page, start=start + ) + + 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, + ) + + supports_event = ( + (event is None) + or (event in ALWAYS_SUPPORTED_EVENTS) + or self._service_api.feature_enabled(f"AUTOMATION_EVENT_{event.value}") + ) + supports_action = ( + (action is None) + or (action in ALWAYS_SUPPORTED_ACTIONS) + or self._service_api.feature_enabled(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, + start: str | None = None, + ) -> 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. + start: Pagination cursor for resuming a past query, captured + from a previous paginator's `.cursor` attribute. + + 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 = {"entity": 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( + self.client, + variables=variables, + per_page=per_page, + start=start, + _query=query, + ) + + # FIXME: this is crude, move this client-side filtering logic into backend + if name is not None: + return filter(lambda x: x.name == name, iterator) + return 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.", + ) + ``` + """ + import requests + + 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 = {"input": gql_input.model_dump()} + + 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.", + ) + ``` + """ + import requests + + 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 = {"input": gql_input.model_dump()} + + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/artifacts.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/artifacts.py new file mode 100644 index 0000000000000000000000000000000000000000..d0186d080f8e5966e2dfd15202915805c664ddfb --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/artifacts.py @@ -0,0 +1,1139 @@ +"""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 +from collections.abc import Collection, Iterable, Mapping, Sequence +from copy import copy +from functools import lru_cache +from typing import TYPE_CHECKING, Any, ClassVar, List, Literal, TypeVar # noqa: UP035 + +from typing_extensions import override +from wandb_gql import gql + +from wandb._iterutils import always_list +from wandb._pydantic import Connection, ConnectionWithTotal, Edge +from wandb._strutils import nameof +from wandb.apis.normalize import normalize_exceptions +from wandb.apis.paginator import RelayPaginator, SizedRelayPaginator +from wandb.errors.errors import UnsupportedError +from wandb.errors.term import termlog +from wandb.proto import wandb_internal_pb2 as pb +from wandb.proto.wandb_telemetry_pb2 import Deprecated +from wandb.sdk.artifacts._gqlutils import server_supports +from wandb.sdk.artifacts._models import ArtifactCollectionData +from wandb.sdk.lib.deprecation import warn_and_record_deprecation + +from .files import File +from .utils import gql_compat + +if TYPE_CHECKING: + from wandb_graphql.language.ast import Document + + from wandb.apis.public.api import RetryingClient + from wandb.apis.public.service_api import ServiceApi + from wandb.sdk.artifacts._generated import ( + ArtifactAliasFragment, + ArtifactCollectionFragment, + ArtifactFragment, + ArtifactTypeFragment, + FileFragment, + ) + from wandb.sdk.artifacts._models.pagination import ( + ArtifactCollectionConnection, + ArtifactFileConnection, + ArtifactTypeConnection, + ) + from wandb.sdk.artifacts.artifact import Artifact + + from . import Run + + +TNode = TypeVar("TNode") + + +@lru_cache(maxsize=1) +def _run_artifacts_mode_to_gql() -> dict[Literal["logged", "used"], str]: + """Lazily import and cache the run artifact GQL query strings. + + This keeps import-time light and only loads the generated GQL + when RunArtifacts is actually used. + """ + from wandb.sdk.artifacts._generated import ( + RUN_INPUT_ARTIFACTS_GQL, + RUN_OUTPUT_ARTIFACTS_GQL, + ) + + return {"logged": RUN_OUTPUT_ARTIFACTS_GQL, "used": RUN_INPUT_ARTIFACTS_GQL} + + +class _ArtifactCollectionAliases(RelayPaginator["ArtifactAliasFragment", str]): + """An internal iterator of collection alias names. + + + """ + + QUERY: ClassVar[Document | None] = None + last_response: Connection[ArtifactAliasFragment] | None + + def __init__( + self, + client: RetryingClient, + collection_id: str, + per_page: int = 1_000, + start: str | None = None, + ): + if self.QUERY is None: + from wandb.sdk.artifacts._generated import ARTIFACT_COLLECTION_ALIASES_GQL + + type(self).QUERY = gql(ARTIFACT_COLLECTION_ALIASES_GQL) + + variables = {"id": collection_id} + super().__init__(client, variables=variables, per_page=per_page, start=start) + + def _update_response(self) -> None: + from wandb.sdk.artifacts._generated import ( + ArtifactAliasFragment, + ArtifactCollectionAliases, + ) + + data = self.client.execute(self.QUERY, variable_values=self.variables) + result = ArtifactCollectionAliases.model_validate(data) + + # Extract the inner `*Connection` result for faster/easier access. + if not ((coll := result.artifact_collection) and (conn := coll.aliases)): + raise ValueError(f"Unable to parse {nameof(type(self))!r} response data") + + self.last_response = Connection[ArtifactAliasFragment].model_validate(conn) + + def _convert(self, node: ArtifactAliasFragment) -> str: + return node.alias + + +class ArtifactTypes(RelayPaginator["ArtifactTypeFragment", "ArtifactType"]): + """An lazy iterator of `ArtifactType` objects for a specific project. + + + """ + + QUERY: ClassVar[Document | None] = None + last_response: ArtifactTypeConnection | None + + def __init__( + self, + client: RetryingClient, + entity: str, + project: str, + per_page: int = 50, + start: str | None = None, + *, + service_api: ServiceApi | None = None, + ): + if self.QUERY is None: + from wandb.sdk.artifacts._generated import PROJECT_ARTIFACT_TYPES_GQL + + type(self).QUERY = gql(PROJECT_ARTIFACT_TYPES_GQL) + + self.entity = entity + self.project = project + self._service_api = service_api + variables = {"entity": entity, "project": project} + super().__init__(client, variables=variables, per_page=per_page, start=start) + + @override + def _update_response(self) -> None: + """Fetch and validate the response data for the current page.""" + from wandb.sdk.artifacts._generated import ProjectArtifactTypes + from wandb.sdk.artifacts._models.pagination import ArtifactTypeConnection + + 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 = ArtifactTypeConnection.model_validate(conn) + + def _convert(self, node: ArtifactTypeFragment) -> ArtifactType: + return ArtifactType( + client=self.client, + entity=self.entity, + project=self.project, + type_name=node.name, + attrs=node, + service_api=self._service_api, + ) + + +class ArtifactType: + """An artifact object that satisfies query based on the specified type. + + Args: + client: Legacy GraphQL client retained for API compatibility. + service_api: Interface to the wandb-core service that performs + W&B API calls for this artifact type. + 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 attributes to initialize the ArtifactType. + If omitted, the object will load its attributes from W&B upon + initialization. + + + """ + + _attrs: ArtifactTypeFragment + + def __init__( + self, + client: RetryingClient, + entity: str, + project: str, + type_name: str, + attrs: ArtifactTypeFragment | None = None, + *, + service_api: ServiceApi | None = None, + ): + from wandb.sdk.artifacts._generated import ArtifactTypeFragment + + self.client = client + self.entity = entity + self.project = project + self.type = type_name + self._service_api = service_api + + # FIXME: Make this lazy, so we don't (re-)fetch the attributes until they are needed + self._attrs = ArtifactTypeFragment.model_validate(attrs or self.load()) + + def load(self) -> ArtifactTypeFragment: + """Load the artifact type attributes from W&B. + + + """ + from wandb.sdk.artifacts._generated import ( + PROJECT_ARTIFACT_TYPE_GQL, + ArtifactTypeFragment, + ProjectArtifactType, + ) + + gql_op = gql(PROJECT_ARTIFACT_TYPE_GQL) + gql_vars = {"entity": self.entity, "project": self.project, "type": self.type} + data = self.client.execute(gql_op, variable_values=gql_vars) + 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!r}") + return ArtifactTypeFragment.model_validate(artifact_type) + + @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, + filters: Mapping[str, Any] | None = None, + order: str | None = None, + per_page: int = 50, + start: str | None = None, + ) -> ArtifactCollections: + """Get all artifact collections associated with this artifact type. + + Args: + filters (dict): Optional mapping of filters to apply to the query. + order (str): Optional string to specify the order of the results. + If you prepend order with a + order is ascending (default). + If you prepend order with a - order is descending. + The default order is the collection ID in descending order. + per_page (int): The number of artifact collections to fetch per page. + Default is 50. + start: Pagination cursor for resuming a past query, captured + from a previous paginator's `.cursor` attribute. + """ + return ArtifactCollections( + self.client, + entity=self.entity, + project=self.project, + filters=filters, + order=order, + type_name=self.type, + per_page=per_page, + start=start, + service_api=self._service_api, + ) + + 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, + entity=self.entity, + project=self.project, + name=name, + type=self.type, + service_api=self._service_api, + ) + + def __repr__(self) -> str: + return f"" + + +class ArtifactCollections( + SizedRelayPaginator["ArtifactCollectionFragment", "ArtifactCollection"] +): + """Artifact collections of a specific type in a project. + + Args: + client: Legacy GraphQL client retained for API compatibility. + service_api: Interface to the wandb-core service that performs + W&B API calls for this collection. + 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. + filters: Optional mapping of filters to apply to the query. + order: Optional string to specify the order of the results. + If you prepend order with a + order is ascending (default). + If you prepend order with a - order is descending. + per_page: The number of artifact collections to fetch per page. Default is 50. + + + """ + + QUERY: ClassVar[Document | None] = None + last_response: ArtifactCollectionConnection | None + + def __init__( + self, + client: RetryingClient, + entity: str, + project: str, + type_name: str, + filters: Mapping[str, Any] | None = None, + order: str | None = None, + per_page: int = 50, + start: str | None = None, + *, + service_api: ServiceApi | None = None, + ): + if self.QUERY is None: + from wandb.sdk.artifacts._generated import ( + ARTIFACT_TYPE_ARTIFACT_COLLECTIONS_GQL, + ) + + type(self).QUERY = gql(ARTIFACT_TYPE_ARTIFACT_COLLECTIONS_GQL) + + if (order is not None or filters is not None) and not server_supports( + client, pb.ARTIFACT_COLLECTIONS_FILTERING_SORTING + ): + raise UnsupportedError( + "Filtering and ordering of artifact collections is not supported on this wandb server version. " + "Please upgrade your server version or contact support at support@wandb.com." + ) + + self.entity = entity + self.project = project + self.type_name = type_name + self.filters = filters + self.order = order + self._service_api = service_api + variables = { + "entity": entity, + "project": project, + "type": type_name, + "order": order, + "filters": json.dumps(f) if (f := filters) else None, + } + super().__init__(client, variables=variables, per_page=per_page, start=start) + + @override + def _update_response(self) -> None: + """Fetch and validate the response data for the current page.""" + from wandb.sdk.artifacts._generated import ArtifactTypeArtifactCollections + from wandb.sdk.artifacts._models.pagination import ArtifactCollectionConnection + + data = self.client.execute(self.QUERY, variable_values=self.variables) + result = ArtifactTypeArtifactCollections.model_validate(data) + + # Extract the inner `*Connection` result for faster/easier access. + if not ( + (proj := result.project) + and (artifact_type := proj.artifact_type) + and (conn := artifact_type.artifact_collections) + ): + raise ValueError(f"Unable to parse {nameof(type(self))!r} response data") + + self.last_response = ArtifactCollectionConnection.model_validate(conn) + + def _convert(self, node: ArtifactCollectionFragment) -> ArtifactCollection | None: + if not node.project: + return None + return ArtifactCollection( + client=self.client, + entity=node.project.entity.name, + project=node.project.name, + name=node.name, + type=node.type.name, + attrs=node, + service_api=self._service_api, + ) + + +class ProjectArtifactCollections( + SizedRelayPaginator["ArtifactCollectionFragment", "ArtifactCollection"] +): + """Artifact collections in a project. + + Args: + client: Legacy GraphQL client retained for API compatibility. + service_api: Interface to the wandb-core service that performs + W&B API calls for this collection. + entity: The entity (user or team) that owns the project. + project: The name of the project to query for artifact collections. + filters: Optional mapping of filters to apply to the query. + order: Optional string to specify the order of the results. + If you prepend order with a + order is ascending (default). + If you prepend order with a - order is descending. + per_page: The number of artifact collections to fetch per page. Default is 50. + + + """ + + QUERY: ClassVar[Document | None] = None + last_response: ArtifactCollectionConnection | None + + def __init__( + self, + client: RetryingClient, + entity: str, + project: str, + filters: Mapping[str, Any] | None = None, + order: str | None = None, + per_page: int = 50, + start: str | None = None, + *, + service_api: ServiceApi | None = None, + ): + if (order is not None or filters is not None) and not server_supports( + client, pb.ARTIFACT_COLLECTIONS_FILTERING_SORTING + ): + raise UnsupportedError( + "Filtering and ordering of artifact collections is not supported on this wandb server version. " + "Please upgrade your server version or contact support at support@wandb.com." + ) + + if self.QUERY is None: + from wandb.sdk.artifacts._generated import PROJECT_ARTIFACT_COLLECTIONS_GQL + + omit_fields = ( + None + if server_supports(client, pb.ARTIFACT_COLLECTIONS_FILTERING_SORTING) + else {"totalCount"} + ) + + omit_variables = ( + None + if server_supports(client, pb.ARTIFACT_COLLECTIONS_FILTERING_SORTING) + else {"filters"} + ) + + type(self).QUERY = gql_compat( + PROJECT_ARTIFACT_COLLECTIONS_GQL, + omit_variables=omit_variables, + omit_fields=omit_fields, + ) + + self.entity = entity + self.project = project + self.filters = filters + self.order = order + self._service_api = service_api + variables = { + "entity": entity, + "project": project, + "order": order, + "filters": json.dumps(f) if (f := filters) else None, + } + + super().__init__(client, variables=variables, per_page=per_page, start=start) + + @override + def _update_response(self) -> None: + """Fetch and validate the response data for the current page.""" + from wandb.sdk.artifacts._generated import ProjectArtifactCollections + from wandb.sdk.artifacts._models.pagination import ( + ProjectArtifactCollectionConnection, + ) + + 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 (conn := proj.artifact_collections)): + raise ValueError(f"Unable to parse {nameof(type(self))!r} response data") + + self.last_response = ProjectArtifactCollectionConnection.model_validate(conn) + + def _convert(self, node: ArtifactCollectionFragment) -> ArtifactCollection | None: + if not node.project: + return None + return ArtifactCollection( + client=self.client, + entity=node.project.entity.name, + project=node.project.name, + name=node.name, + type=node.type.name, + attrs=node, + service_api=self._service_api, + ) + + +class ArtifactCollection: + """An artifact collection that represents a group of related artifacts. + + Args: + client: Legacy GraphQL client retained for API compatibility. + service_api: Interface to the wandb-core service that performs + W&B API calls for this collection. + 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. + + + """ + + _saved: ArtifactCollectionData + """The saved artifact collection data as last fetched from the W&B server.""" + + _current: ArtifactCollectionData + """The local, editable artifact collection data.""" + + def __init__( + self, + client: RetryingClient, + entity: str, + project: str, + name: str, + type: str, + organization: str | None = None, + attrs: ArtifactCollectionFragment | None = None, + *, + service_api: ServiceApi | None = None, + ): + self.client = client + self._service_api = service_api + + # FIXME: Make this lazy, so we don't (re-)fetch the attributes until they are needed + self._update_data(attrs or self.load(entity, project, type, name)) + + self.organization = organization + + def _update_data(self, fragment: ArtifactCollectionFragment) -> None: + """Update the saved/current state of this collection with the given fragment. + + Can be used after receiving a GraphQL response with ArtifactCollection data. + """ + # Separate "saved" vs "current" copies of the artifact collection data + validated = ArtifactCollectionData.from_fragment(fragment) + self._saved = validated + self._current = validated.model_copy(deep=True) + + @property + def id(self) -> str: + """The unique identifier of the artifact collection.""" + return self._current.id + + @property + def entity(self) -> str: + """The entity (user or team) that owns the project.""" + return self._current.entity + + @property + def project(self) -> str: + """The project that contains the artifact collection.""" + return self._current.project + + @normalize_exceptions + def artifacts( + self, + per_page: int = 50, + start: str | None = None, + ) -> Artifacts: + """Get all artifacts in the collection. + + Args: + per_page: The number of artifacts to fetch per page. + start: Pagination cursor for resuming a past query, captured + from a previous paginator's `.cursor` attribute. + """ + return Artifacts( + client=self.client, + entity=self.entity, + project=self.project, + # Use the saved name and type, as they're mutable attributes + # and may have been edited locally. + collection_name=self._saved.name, + type=self._saved.type, + per_page=per_page, + start=start, + service_api=self._service_api, + ) + + @property + def aliases(self) -> list[str]: + """The aliases for all artifact versions contained in this collection.""" + if self._saved.aliases is None: + aliases = list( + _ArtifactCollectionAliases(self.client, collection_id=self.id) + ) + self._saved = self._saved.model_copy(update={"aliases": aliases}) + self._current = self._current.model_copy(update={"aliases": aliases}) + + return list(self._saved.aliases) + + @property + def created_at(self) -> str: + """The creation date of the artifact collection.""" + return self._saved.created_at + + @property + def updated_at(self) -> str | None: + """The date at which the artifact collection was last updated.""" + return self._saved.updated_at + + def load( + self, entity: str, project: str, type_: str, name: str + ) -> ArtifactCollectionFragment: + """Fetch and return the validated artifact collection data from W&B. + + + """ + from wandb.sdk.artifacts._generated import ( + PROJECT_ARTIFACT_COLLECTION_GQL, + ProjectArtifactCollection, + ) + + gql_op = gql(PROJECT_ARTIFACT_COLLECTION_GQL) + gql_vars = {"entity": entity, "project": project, "type": type_, "name": name} + data = self.client.execute(gql_op, variable_values=gql_vars) + result = ProjectArtifactCollection.model_validate(data) + if not ( + result.project + and (proj := result.project) + and (artifact_type := proj.artifact_type) + and (collection := artifact_type.artifact_collection) + ): + raise ValueError(f"Could not find artifact type {type_!r}") + return collection + + @normalize_exceptions + def change_type(self, new_type: str) -> None: + """Deprecated, change type directly with `save` instead.""" + from wandb.sdk.artifacts._generated import ( + UPDATE_ARTIFACT_SEQUENCE_TYPE_GQL, + MoveArtifactSequenceInput, + ) + from wandb.sdk.artifacts._validators import validate_artifact_type + + warn_and_record_deprecation( + feature=Deprecated(artifact_collection__change_type=True), + message="ArtifactCollection.change_type(type) is deprecated, use ArtifactCollection.save() instead.", + ) + + if (old_type := self._saved.type) != new_type: + try: + validate_artifact_type(old_type, self.name) + except ValueError as e: + raise ValueError( + f"The current type {old_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 + new_type = 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 {old_type!r} to {new_type!r}") + + gql_op = gql(UPDATE_ARTIFACT_SEQUENCE_TYPE_GQL) + gql_input = MoveArtifactSequenceInput( + artifact_sequence_id=self.id, + destination_artifact_type_name=new_type, + ) + self.client.execute(gql_op, variable_values={"input": gql_input.model_dump()}) + self._saved.type = new_type + self._current.type = new_type + + def is_sequence(self) -> bool: + """Return whether the artifact collection is a sequence.""" + return self._saved.is_sequence + + @normalize_exceptions + def delete(self) -> None: + """Delete the entire artifact collection.""" + from wandb.sdk.artifacts._generated import ( + DELETE_ARTIFACT_PORTFOLIO_GQL, + DELETE_ARTIFACT_SEQUENCE_GQL, + ) + + gql_op = gql( + DELETE_ARTIFACT_SEQUENCE_GQL + if self.is_sequence() + else DELETE_ARTIFACT_PORTFOLIO_GQL + ) + self.client.execute(gql_op, variable_values={"id": self.id}) + + @property + def description(self) -> str | None: + """A description of the artifact collection.""" + return self._current.description + + @description.setter + def description(self, description: str | None) -> None: + """Set the description of the artifact collection.""" + self._current.description = description + + @property + def tags(self) -> list[str]: + """The tags associated with the artifact collection.""" + return self._current.tags + + @tags.setter + def tags(self, tags: Collection[str]) -> None: + """Set the tags associated with the artifact collection.""" + self._current.tags = tags + + @property + def name(self) -> str: + """The name of the artifact collection.""" + return self._current.name + + @name.setter + def name(self, name: str) -> None: + """Set the name of the artifact collection.""" + self._current.name = name + + @property + def type(self): + """Returns the type of the artifact collection.""" + return self._current.type + + @type.setter + def type(self, type: 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._current.type = type + + def _update_collection(self) -> None: + from wandb.sdk.artifacts._generated import ( + UPDATE_ARTIFACT_PORTFOLIO_GQL, + UPDATE_ARTIFACT_SEQUENCE_GQL, + UpdateArtifactPortfolioInput, + UpdateArtifactSequenceInput, + ) + + if self.is_sequence(): + gql_op = gql(UPDATE_ARTIFACT_SEQUENCE_GQL) + gql_input = UpdateArtifactSequenceInput( + artifact_sequence_id=self.id, + name=self.name, + description=self.description, + ) + else: + gql_op = gql(UPDATE_ARTIFACT_PORTFOLIO_GQL) + gql_input = UpdateArtifactPortfolioInput( + artifact_portfolio_id=self.id, + name=self.name, + description=self.description, + ) + self.client.execute(gql_op, variable_values={"input": gql_input.model_dump()}) + self._saved.name = self._current.name + self._saved.description = self._current.description + self._saved.updated_at = self._current.updated_at + + def _update_sequence_type(self) -> None: + from wandb.sdk.artifacts._generated import ( + UPDATE_ARTIFACT_SEQUENCE_TYPE_GQL, + MoveArtifactSequenceInput, + ) + + gql_op = gql(UPDATE_ARTIFACT_SEQUENCE_TYPE_GQL) + gql_input = MoveArtifactSequenceInput( + artifact_sequence_id=self.id, + destination_artifact_type_name=self.type, + ) + self.client.execute(gql_op, variable_values={"input": gql_input.model_dump()}) + self._saved.type = self._current.type + + def _add_tags(self, tag_names: Iterable[str]) -> None: + from wandb.sdk.artifacts._generated import ( + ADD_ARTIFACT_COLLECTION_TAGS_GQL, + CreateArtifactCollectionTagAssignmentsInput, + ) + + gql_op = gql(ADD_ARTIFACT_COLLECTION_TAGS_GQL) + gql_input = CreateArtifactCollectionTagAssignmentsInput( + entity_name=self.entity, + project_name=self.project, + artifact_collection_name=self._saved.name, + tags=[{"tagName": tag} for tag in tag_names], + ) + self.client.execute(gql_op, variable_values={"input": gql_input.model_dump()}) + + def _delete_tags(self, tag_names: Iterable[str]) -> None: + from wandb.sdk.artifacts._generated import ( + DELETE_ARTIFACT_COLLECTION_TAGS_GQL, + DeleteArtifactCollectionTagAssignmentsInput, + ) + + gql_op = gql(DELETE_ARTIFACT_COLLECTION_TAGS_GQL) + gql_input = DeleteArtifactCollectionTagAssignmentsInput( + entity_name=self.entity, + project_name=self.project, + artifact_collection_name=self._saved.name, + tags=[{"tagName": tag} for tag in tag_names], + ) + self.client.execute(gql_op, variable_values={"input": gql_input.model_dump()}) + + @normalize_exceptions + def save(self) -> None: + """Persist any changes made to the artifact collection.""" + from wandb.sdk.artifacts._validators import validate_artifact_type + + if (old_type := self._saved.type) != (new_type := self.type): + try: + validate_artifact_type(new_type, self.name) + except ValueError as e: + reason = str(e) + raise ValueError( + f"Failed to save artifact collection {self.name!r}: {reason}" + ) from e + try: + validate_artifact_type(old_type, self.name) + except ValueError as e: + reason = f"The current type {old_type!r} is an internal type and cannot be changed." + raise ValueError( + f"Failed to save artifact collection {self.name!r}: {reason}" + ) from e + + # FIXME: Consider consolidating the multiple GQL mutations into a single call. + self._update_collection() + + if self.is_sequence() and (old_type != new_type): + self._update_sequence_type() + + if (new_tags := set(self._current.tags)) != (old_tags := set(self._saved.tags)): + if added_tags := (new_tags - old_tags): + self._add_tags(added_tags) + if deleted_tags := (old_tags - new_tags): + self._delete_tags(deleted_tags) + self._saved.tags = copy(new_tags) + + def __repr__(self) -> str: + return f"" + + +class _ArtifactEdgeGeneric(Edge[TNode]): + version: str # Extra field defined only on VersionedArtifactEdge + + +class _ArtifactConnectionGeneric(ConnectionWithTotal[TNode]): + edges: List[_ArtifactEdgeGeneric] # noqa: UP006 + + +class Artifacts(SizedRelayPaginator["ArtifactFragment", "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: Legacy GraphQL client retained for API compatibility. + service_api: Interface to the wandb-core service that performs + W&B API calls for these artifact versions. + 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. + + + """ + + QUERY: Document # Must be set per-instance + + # Loosely-annotated to avoid importing heavy types at module import time. + last_response: _ArtifactConnectionGeneric | None + + def __init__( + self, + client: RetryingClient, + 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, + start: str | None = None, + *, + service_api: ServiceApi | None = None, + ): + from wandb.sdk.artifacts._generated import PROJECT_ARTIFACTS_GQL + + self.QUERY = gql(PROJECT_ARTIFACTS_GQL) + + 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 = always_list(tags or []) + self.order = order + self._service_api = service_api + variables = { + "entity": self.entity, + "project": self.project, + "order": self.order, + "type": self.type, + "collection": self.collection_name, + "filters": json.dumps(self.filters), + } + super().__init__(client, variables=variables, per_page=per_page, start=start) + + @override + def _update_response(self) -> None: + from wandb.sdk.artifacts._generated import ArtifactFragment, ProjectArtifacts + + 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 = _ArtifactConnectionGeneric[ + ArtifactFragment + ].model_validate(conn) + + # FIXME: For now, we deliberately override the signatures of: + # - `_convert()` + # - `convert_objects()` + # ... since the prior implementation must get `version` from the GQL edge + # (i.e. `edge.version`), which lives outside of the GQL node (`edge.node`). + # + # In the future, we should move to fetching artifacts via (GQL) artifactMemberships, + # not (GQL) artifacts, so we don't have to deal with this hack. + @override + def _convert(self, edge: _ArtifactEdgeGeneric[ArtifactFragment]) -> Artifact: + from wandb.sdk.artifacts._validators import FullArtifactPath + from wandb.sdk.artifacts.artifact import Artifact + + return Artifact._from_attrs( + path=FullArtifactPath( + prefix=self.entity, + project=self.project, + name=f"{self.collection_name}:{edge.version}", + ), + src_art=edge.node, + client=self.client, + service_api=self._service_api, + ) + + @override + def convert_objects(self) -> list[Artifact]: + """Convert the raw response data into a list of wandb.Artifact objects. + + + """ + if (conn := self.last_response) is None: + return [] + artifacts = (self._convert(edge) for edge in conn.edges if edge.node) + required_tags = set(self.tags or []) + return [art for art in artifacts if required_tags.issubset(art.tags)] + + +class RunArtifacts(SizedRelayPaginator["ArtifactFragment", "Artifact"]): + """An iterable collection of artifacts associated with a specific run. + + + """ + + QUERY: Document # Must be set per-instance + last_response: ConnectionWithTotal[ArtifactFragment] | None + + def __init__( + self, + client: RetryingClient, + run: Run, + mode: Literal["logged", "used"] = "logged", + per_page: int = 50, + start: str | None = None, + *, + service_api: ServiceApi, + ): + try: + query_str = _run_artifacts_mode_to_gql()[mode] + except LookupError: + raise ValueError("mode must be logged or used") + else: + self.QUERY = gql(query_str) + + self.run = run + self._service_api = service_api + variables = {"entity": run.entity, "project": run.project, "run": run.id} + super().__init__(client, variables=variables, per_page=per_page, start=start) + + @override + def _update_response(self) -> None: + from wandb.sdk.artifacts._models.pagination import RunArtifactConnection + + data = self.client.execute(self.QUERY, variable_values=self.variables) + + # Extract the inner `*Connection` result for faster/easier access. + inner_data = data["project"]["run"]["artifacts"] + self.last_response = RunArtifactConnection.model_validate(inner_data) + + def _convert(self, node: ArtifactFragment) -> Artifact | None: + from wandb.sdk.artifacts._validators import FullArtifactPath + from wandb.sdk.artifacts.artifact import Artifact + + if node.artifact_sequence.project is None: + return None + return Artifact._from_attrs( + path=FullArtifactPath( + prefix=node.artifact_sequence.project.entity.name, + project=node.artifact_sequence.project.name, + name=f"{node.artifact_sequence.name}:v{node.version_index}", + ), + src_art=node, + client=self.client, + service_api=self._service_api, + ) + + +class ArtifactFiles(SizedRelayPaginator["FileFragment", "File"]): + """A paginator for files in an artifact. + + + """ + + QUERY: Document # Must be set per-instance + last_response: ArtifactFileConnection | None + + def __init__( + self, + client: RetryingClient, + artifact: Artifact, + names: Sequence[str] | None = None, + per_page: int = 50, + start: str | None = None, + ): + from wandb.sdk.artifacts._generated import ( + GET_ARTIFACT_FILES_GQL, + GET_ARTIFACT_MEMBERSHIP_FILES_GQL, + ) + from wandb.sdk.artifacts._gqlutils import server_supports + + self.query_via_membership = server_supports( + client, pb.ARTIFACT_COLLECTION_MEMBERSHIP_FILES + ) + self.artifact = artifact + + if self.query_via_membership: + query_str = GET_ARTIFACT_MEMBERSHIP_FILES_GQL + variables = { + "entity": artifact.entity, + "project": artifact.project, + "collection": artifact.name.split(":")[0], + "alias": artifact.version, + "fileNames": names, + } + else: + query_str = GET_ARTIFACT_FILES_GQL + variables = { + "entity": artifact.source_entity, + "project": artifact.source_project, + "name": artifact.source_name, + "type": artifact.type, + "fileNames": names, + } + + omit_fields = ( + None + if server_supports(client, pb.TOTAL_COUNT_IN_FILE_CONNECTION) + else {"totalCount"} + ) + self.QUERY = gql_compat(query_str, omit_fields=omit_fields) + super().__init__(client, variables=variables, per_page=per_page, start=start) + + @override + def _update_response(self) -> None: + from wandb.sdk.artifacts._generated import ( + GetArtifactFiles, + GetArtifactMembershipFiles, + ) + from wandb.sdk.artifacts._models.pagination import ArtifactFileConnection + + 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 = GetArtifactMembershipFiles.model_validate(data) + conn = result.project.artifact_collection.artifact_membership.files + else: + result = GetArtifactFiles.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 = ArtifactFileConnection.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] + + def _convert(self, node: FileFragment) -> File: + return File(self.client, attrs=node.model_dump(exclude_unset=True)) + + def __repr__(self) -> str: + path_str = "/".join(self.path) + try: + total = len(self) + except NotImplementedError: + # Older server versions don't correctly support totalCount + return f"" + else: + return f"" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/automations.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/automations.py new file mode 100644 index 0000000000000000000000000000000000000000..faca3b7b1a04c19bb979e22df4eca22b0648533a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/automations.py @@ -0,0 +1,70 @@ +"""W&B Public API for Automation objects.""" + +from __future__ import annotations + +from collections.abc import Iterator, Mapping +from itertools import chain +from typing import TYPE_CHECKING, Any + +from pydantic import ValidationError +from typing_extensions import override + +from wandb.apis.paginator import RelayPaginator + +if TYPE_CHECKING: + from wandb_graphql.language.ast import Document + + from wandb._pydantic import Connection + from wandb.apis.public.api import RetryingClient + from wandb.automations import Automation + from wandb.automations._generated import ProjectTriggersFields + + +class Automations(RelayPaginator["ProjectTriggersFields", "Automation"]): + """A lazy iterator of `Automation` objects. + + + """ + + QUERY: Document # Must be set per-instance + last_response: Connection[ProjectTriggersFields] | None + + def __init__( + self, + client: RetryingClient, + variables: Mapping[str, Any], + per_page: int = 50, + *, + start: str | None = None, + _query: Document, # internal use only, but required + ): + self.QUERY = _query + super().__init__(client, variables=variables, per_page=per_page, start=start) + + @override + def _update_response(self) -> None: + """Fetch the raw response data for the current page.""" + from wandb._pydantic import Connection + from wandb.automations._generated import ProjectTriggersFields + + data = self.client.execute(self.QUERY, variable_values=self.variables) + try: + conn_data = data["scope"]["projects"] + conn = Connection[ProjectTriggersFields].model_validate(conn_data) + self.last_response = conn + except (LookupError, AttributeError, ValidationError) as e: + raise ValueError("Unexpected response data") from e + + @override + def _convert(self, node: ProjectTriggersFields) -> Iterator[Automation]: + from wandb.automations import Automation + + return (Automation.model_validate(obj) for obj in node.triggers) + + @override + def convert_objects(self) -> Iterator[Automation]: + # `_convert` above yields an iterator-per-node (one project may have many + # automations), so the parent's `convert_objects` returns iterables-of- + # iterables; flatten them. The parent's contract types `_convert` as + # returning a single object, hence the type: ignore. + return chain.from_iterable(super().convert_objects()) # type: ignore[arg-type] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/const.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/const.py new file mode 100644 index 0000000000000000000000000000000000000000..e75e387177d8b2c65d468ded64f4080b5b67a5bd --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/files.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/files.py new file mode 100644 index 0000000000000000000000000000000000000000..028cd51a157a0994c1bae5ba2d678acc4360248c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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 +from collections.abc import Callable +from typing import TYPE_CHECKING, Any + +from wandb_gql import gql +from wandb_gql.client import RetryError + +import wandb +from wandb._strutils import nameof +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.const import RETRY_TIMEDELTA +from wandb.apis.public.runs import Run +from wandb.sdk.lib import retry +from wandb.util import POW_2_BYTES, download_file_from_url, no_retry_auth, to_human_size + +if TYPE_CHECKING: + from wandb_graphql.language.ast import Document + + from wandb.apis.public import Api, RetryingClient + +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) -> Document: + """Generate query dynamically based on server capabilities.""" + return gql( + f"""#graphql + 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 + 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) -> int: + """ + Returns total number of files. + + + """ + if not self.last_response: + self._load_page() + + if not self.last_response: + return 0 + + project = self.last_response.get("project") or {} + run_data = project.get("run") or {} + return run_data.get("fileCount", 0) + + @property + def more(self) -> bool: + """Returns whether there are more files to fetch. + + + """ + if not self.last_response: + return True + + project = self.last_response.get("project") or {} + run_data = project.get("run") or {} + files_data = run_data.get("files") or {} + page_info = files_data.get("pageInfo") or {} + return page_info.get("hasNextPage", False) + + @property + def cursor(self) -> str | None: + """Returns the cursor position for pagination of file results. + + + """ + if not self.last_response: + return None + + project = self.last_response.get("project") or {} + run_data = project.get("run") or {} + files_data = run_data.get("files") or {} + edges = files_data.get("edges") or [] + + if not edges: + return None + + return edges[-1].get("cursor") + + def update_variables(self) -> None: + """Updates the GraphQL query variables for pagination. + + + """ + self.variables.update({"fileLimit": self.per_page, "fileCursor": self.cursor}) + + def convert_objects(self) -> list[File]: + """Converts GraphQL edges to File objects. + + + """ + if not self.last_response: + return [] + + project = self.last_response.get("project") or {} + run_data = project.get("run") or {} + files_data = run_data.get("files") or {} + edges = files_data.get("edges") or [] + return [File(self.client, r["node"], self.run) for r in edges] + + def __repr__(self) -> str: + return f"<{nameof(type(self))} {'/'.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: RetryingClient, + attrs: dict[str, Any], + run: Run | None = None, + ): + self.client = client + self._attrs = attrs + self.run = run + self._download_decorated: Callable[..., Any] | None = None + super().__init__(dict(attrs)) + + @property + def size(self) -> int: + """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 "" + + def _build_download_wrapper(self) -> Callable[..., io.TextIOWrapper]: + import requests + + @retry.retriable( + retry_timedelta=RETRY_TIMEDELTA, + check_retry_fn=no_retry_auth, + retryable_exceptions=(RetryError, requests.RequestException), + ) + def _impl( + root: str = ".", + replace: bool = False, + exist_ok: bool = False, + api: Api | None = None, + ) -> io.TextIOWrapper: + 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) + raise ValueError( + "File already exists, pass replace=True to overwrite " + "or exist_ok=True to leave it as is and don't error." + ) + + download_file_from_url(path, self.url, api.api_key) + return open(path) + + return _impl + + @normalize_exceptions + 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 self._download_decorated is None: + self._download_decorated = self._build_download_wrapper() + return self._download_decorated(root, replace, exist_ok, api) + + @normalize_exceptions + def delete(self) -> None: + """Delete the file from the W&B server.""" + variable_values = { + "files": [self.id], + "projectId": self.run._project_internal_id, + } + + mutation = gql(""" + mutation deleteFiles($files: [ID!]!, $projectId: Int) { + deleteFiles(input: { + files: $files + projectId: $projectId + }) { + success + } + } + """) + + self.client.execute( + mutation, + variable_values=variable_values, + ) + + def __repr__(self) -> str: + classname = nameof(type(self)) + size = to_human_size(self.size, units=POW_2_BYTES) + return f"<{classname} {self.name} ({self.mimetype}) {size}>" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/history.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/history.py new file mode 100644 index 0000000000000000000000000000000000000000..0bffd04ca11af42521a4b9e7129cdd6110023d63 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/history.py @@ -0,0 +1,365 @@ +"""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 contextlib +import json +import weakref +from collections.abc import Iterator +from typing import TYPE_CHECKING, Any, TypeAlias + +from typing_extensions import Self + +from wandb.apis.normalize import normalize_exceptions +from wandb.proto import wandb_api_pb2 as pb +from wandb.sdk.mailbox.mailbox import MailboxClosedError + +if TYPE_CHECKING: + from . import runs + from .api import RetryingClient + from .service_api import ServiceApi + +_RowDict: TypeAlias = dict[str, Any] +"""Type alias for a single history row as a dict.""" + + +class BetaHistoryScan(Iterator[_RowDict]): + """Iterator for scanning complete run history. + + + """ + + def __init__( + self, + run: runs.Run, + *, + service_api: ServiceApi, + min_step: int, + max_step: int, + keys: list[str] | None = None, + page_size: int = 1_000, + use_cache: bool = True, + ): + self.run = run + self.min_step = min_step + self._stop_step = max_step + self.keys = keys + self.page_size = page_size + self._service_api = service_api + + # Tell wandb-core to initialize resources to scan the run's history. + scan_run_history_init = pb.ScanRunHistoryInit( + entity=self.run.entity, + project=self.run.project, + run_id=self.run.id, + keys=self.keys, + use_cache=use_cache, + ) + scan_run_history_init_request = pb.ReadRunHistoryRequest( + scan_run_history_init=scan_run_history_init + ) + api_request = pb.ApiRequest( + read_run_history_request=scan_run_history_init_request + ) + response: pb.ApiResponse = self._service_api.send_api_request(api_request) + + self._scan_request_id = ( + response.read_run_history_response.scan_run_history_init.request_id + ) + + self.scan_offset = 0 + self.rows: list[_RowDict] = [] + self.keys = keys + + # Add cleanup hook to clean up resources in wandb-core + # when this scan object is deleted. + # + # Using weakref.finalize ensures that references to objects needed during cleanup + # are not garbage collected before being used. + # see: https://docs.python.org/3/library/weakref.html#comparing-finalizers-with-del-methods + weakref.finalize( + self, + self.cleanup, + self._service_api, + self._scan_request_id, + ) + + @property + def max_step(self) -> int: + """The highest step that can be yielded by this scan.""" + return self._stop_step - 1 + + def __iter__(self) -> Self: + self.scan_offset = 0 + self.page_offset = self.min_step + self.rows = [] + return self + + def __next__(self) -> _RowDict: + 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._stop_step: + raise StopIteration() + # Load the next page + self._load_next() + # If no rows were returned, we've reached the end of the data + if len(self.rows) == 0: + raise StopIteration() + + def _load_next(self) -> None: + from wandb.proto import wandb_api_pb2 as pb + + max_step = min(self.page_offset + self.page_size, self._stop_step) + + read_run_history_request = pb.ReadRunHistoryRequest( + scan_run_history=pb.ScanRunHistory( + min_step=self.page_offset, + max_step=max_step, + request_id=self._scan_request_id, + ), + ) + api_request = pb.ApiRequest(read_run_history_request=read_run_history_request) + + response: pb.ApiResponse = self._service_api.send_api_request(api_request) + run_history: pb.RunHistoryResponse = ( + response.read_run_history_response.run_history + ) + self.rows = [ + self._convert_history_row_to_dict(row) for row in run_history.history_rows + ] + self.page_offset += self.page_size + self.scan_offset = 0 + + @staticmethod + def _convert_history_row_to_dict(history_row: pb.HistoryRow) -> _RowDict: + return { + item.key: json.loads(item.value_json) for item in history_row.history_items + } + + @staticmethod + def cleanup(service_api: ServiceApi, request_id: int) -> None: + scan_run_history_cleanup = pb.ScanRunHistoryCleanup( + request_id=request_id, + ) + scan_run_history_cleanup_request = pb.ReadRunHistoryRequest( + scan_run_history_cleanup=scan_run_history_cleanup + ) + + with contextlib.suppress(ConnectionResetError, MailboxClosedError): + service_api.send_api_request( + pb.ApiRequest(read_run_history_request=scan_run_history_cleanup_request) + ) + + +class HistoryScan(Iterator[_RowDict]): + """Iterator for scanning complete run history. + + + """ + + QUERY = """ + 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: RetryingClient, + run: runs.Run, + min_step: int, + max_step: int, + page_size: int = 1_000, + *, + service_api: ServiceApi, + ): + """Initialize a HistoryScan instance. + + Args: + client: Legacy GraphQL client retained for API compatibility; + history rows are fetched through `service_api`. + run: The run object whose history is to be scanned. + min_step: The minimum step to start scanning from. + max_step: The exclusive upper bound for scanned history rows. + page_size: Number of history rows to fetch per page. + Default page_size is 1000. + service_api: Interface to the wandb-core service that performs + W&B API calls for this scan. + """ + self.client = client + self.run = run + self.page_size = page_size + self.min_step = min_step + self._stop_step = max_step + self.page_offset = min_step # minStep for next page + self.scan_offset = 0 # index within current page of rows + self.rows: list[_RowDict] = [] # current page of rows + self._service_api = service_api + + @property + def max_step(self) -> int: + """The highest step that can be yielded by this scan.""" + return self._stop_step - 1 + + def __iter__(self) -> Self: + self.page_offset = self.min_step + self.scan_offset = 0 + self.rows = [] + return self + + def __next__(self) -> _RowDict: + """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._stop_step: + raise StopIteration() + self._load_next() + + next = __next__ + + @normalize_exceptions + def _load_next(self) -> None: + max_step = self.page_offset + self.page_size + if max_step > self._stop_step: + max_step = self._stop_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._service_api.execute_graphql(self.QUERY, 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[_RowDict]): + """Iterator for sampling run history data. + + + """ + + QUERY = """ + 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: RetryingClient, + run: runs.Run, + keys: list[str], + min_step: int, + max_step: int, + page_size: int = 1_000, + *, + service_api: ServiceApi, + ): + """Initialize a SampledHistoryScan instance. + + Args: + client: Legacy GraphQL client retained for API compatibility; + sampled history rows are fetched through `service_api`. + 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 exclusive upper bound for sampled history rows. + page_size: Number of sampled history rows to fetch per page. + Default page_size is 1000. + service_api: Interface to the wandb-core service that performs + W&B API calls for this scan. + """ + self.client = client + self.run = run + self.keys = keys + self.page_size = page_size + self.min_step = min_step + self._stop_step = max_step + self.page_offset = min_step # minStep for next page + self.scan_offset = 0 # index within current page of rows + self.rows: list[_RowDict] = [] # current page of rows + self._service_api = service_api + + @property + def max_step(self) -> int: + """The highest step that can be yielded by this scan.""" + return self._stop_step - 1 + + def __iter__(self) -> Self: + self.page_offset = self.min_step + self.scan_offset = 0 + self.rows = [] + return self + + def __next__(self) -> _RowDict: + """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._stop_step: + raise StopIteration() + self._load_next() + + next = __next__ + + @normalize_exceptions + def _load_next(self) -> None: + max_step = self.page_offset + self.page_size + if max_step > self._stop_step: + max_step = self._stop_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._service_api.execute_graphql(self.QUERY, variables) + res = res["project"]["run"]["sampledHistory"] + self.rows = res[0] + self.page_offset += self.page_size + self.scan_offset = 0 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/integrations.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/integrations.py new file mode 100644 index 0000000000000000000000000000000000000000..502ced07a93dbe172c98b52c1b81af707cf0abf1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/integrations.py @@ -0,0 +1,91 @@ +"""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, ClassVar + +from typing_extensions import override +from wandb_gql import gql + +from wandb.apis.paginator import RelayPaginator + +if TYPE_CHECKING: + from wandb_graphql.language.ast import Document + + from wandb._pydantic import Connection + from wandb.apis.public.api import RetryingClient + from wandb.automations import Integration, SlackIntegration, WebhookIntegration + from wandb.automations._generated import ( + SlackIntegrationFields, + WebhookIntegrationFields, + ) + + IntegrationFields = SlackIntegrationFields | WebhookIntegrationFields + + +class Integrations(RelayPaginator["IntegrationFields", "Integration"]): + """A lazy iterator of `Integration` objects. + + + """ + + QUERY: ClassVar[Document | None] = None + last_response: Connection[IntegrationFields] | None + + def __init__( + self, + client: RetryingClient, + variables: dict[str, Any], + per_page: int = 50, + start: str | None = None, + ): + if self.QUERY is None: + from wandb.automations._generated import INTEGRATIONS_BY_ENTITY_GQL + + type(self).QUERY = gql(INTEGRATIONS_BY_ENTITY_GQL) + + super().__init__(client, variables=variables, per_page=per_page, start=start) + + @override + def _update_response(self) -> None: + """Fetch and parse the response data for the current page.""" + from wandb._pydantic import Connection + from wandb.automations._generated import IntegrationsByEntity + + data = self.client.execute(self.QUERY, variable_values=self.variables) + result = IntegrationsByEntity.model_validate(data) + if not ((entity := result.entity) and (conn := entity.integrations)): + raise ValueError("Unexpected response data") + self.last_response = Connection.model_validate(conn) + + def _convert(self, node: IntegrationFields) -> Integration: + from wandb.automations.integrations import IntegrationAdapter + + return IntegrationAdapter.validate_python(node) + + +# The paginators below filter on `typename__` since the GQL response still +# includes all `Integration` types. Applying a `@skip/@include` directive +# does not change this. Restricting results to a single type requires +# a client-side filter. +class WebhookIntegrations(Integrations): + """A lazy iterator of `WebhookIntegration` objects. + + + """ + + def _convert(self, node: IntegrationFields) -> WebhookIntegration: + return node if (node.typename__ == "GenericWebhookIntegration") else None + + +class SlackIntegrations(Integrations): + """A lazy iterator of `SlackIntegration` objects. + + + """ + + def _convert(self, node: IntegrationFields) -> SlackIntegration: + return node if (node.typename__ == "SlackIntegration") else None diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/jobs.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/jobs.py new file mode 100644 index 0000000000000000000000000000000000000000..c72033729ec8085a58a332871e184f150c46af36 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/jobs.py @@ -0,0 +1,794 @@ +"""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 collections.abc import Callable, Mapping +from typing import TYPE_CHECKING, Any, Literal + +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.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 + from wandb.apis.public.service_api import ServiceApi + from wandb.sdk.launch._project_spec import LaunchProject + + +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, + *, + service_api: ServiceApi | 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._service_api = service_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) -> str: + """The name of the job.""" + return self._name + + def _set_configure_launch_project(self, func: Callable[[LaunchProject], None]): + self.configure_launch_project = func + + def _get_code_artifact(self, artifact_string): + from wandb.sdk.artifacts.artifact_state import ArtifactState + + 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, + service_api=self._service_api, + ) + 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: LaunchProject) -> None: + 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: LaunchProject) -> None: + 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) + + launch_project.set_job_source_type("repo") + launch_project.set_job_source_info( + { + "git_remote": git_info["remote"], + "git_commit": git_info["commit"], + "job_artifact": self._job_artifact.qualified_name, + } + ) + + def _configure_launch_project_artifact(self, launch_project: LaunchProject) -> None: + 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) + + launch_project.set_job_source_type("artifact") + launch_project.set_job_source_info( + { + "artifact_string": code_artifact.qualified_name, + "job_artifact": self._job_artifact.qualified_name, + } + ) + + def _configure_launch_project_container( + self, launch_project: LaunchProject + ) -> None: + 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]) -> None: + """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: + client: Legacy GraphQL client retained for API compatibility. + service_api: Interface to the wandb-core service that performs + W&B API calls for this queued run. + 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: RetryingClient, + entity: str, + project: str, + queue_name: str, + run_queue_item_id: str, + project_queue: str = LAUNCH_DEFAULT_PROJECT, + priority: int | None = None, + *, + service_api: ServiceApi, + ): + self.client = client + self._service_api = service_api + 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: public.Run | None = None + self.project_queue = project_queue + self.priority = priority + + @property + def queue_name(self) -> str: + """The name of the queue.""" + return self._queue_name + + @property + def id(self) -> str: + """The id of the queued run.""" + return self._run_queue_item_id + + @property + def project(self) -> str: + """The project associated with the queued run.""" + return self._project + + @property + def entity(self) -> str: + """The entity associated with the queued run.""" + return self._entity + + @property + def state(self) -> str: + """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[str, Any]: + 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) -> dict[str, Any]: + 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) -> public.Run: + """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: bool = False) -> None: + """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) -> public.Run: + """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, + service_api=self._service_api, + ) + 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) -> str: + return f" None: + self._name: str = name + self._client = client + self._service_api = service_api + 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: list[QueuedRun] | None = None + self._id: str | None = None + + @property + def name(self) -> str: + """The name of the queue.""" + return self._name + + @property + def entity(self) -> str: + """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) -> dict[str, Any]: + """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) -> dict[str, Any]: + """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) -> None: + """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) -> str: + return f"" + + @normalize_exceptions + def _get_metadata(self) -> None: + 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) -> None: + 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) -> None: + 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"], + service_api=self._service_api, + ) + ) + + @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. + """ + from wandb.apis.public import Api + + public_api = Api() + return public_api.create_run_queue( + name, resource, entity, prioritization_mode, config, template_variables + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/projects.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/projects.py new file mode 100644 index 0000000000000000000000000000000000000000..0da32059b8bd1334b28092e5ea4f76aba6f08259 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/projects.py @@ -0,0 +1,313 @@ +"""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 collections.abc import Mapping +from typing import TYPE_CHECKING, Any, ClassVar + +from typing_extensions import override +from wandb_gql import gql + +from wandb._strutils import nameof +from wandb.apis import public +from wandb.apis.attrs import Attrs +from wandb.apis.normalize import normalize_exceptions +from wandb.apis.paginator import RelayPaginator +from wandb.apis.public.api import RetryingClient +from wandb.apis.public.sweeps import Sweeps +from wandb.sdk.lib import ipython + +if TYPE_CHECKING: + from wandb_graphql.language.ast import Document + + from wandb._pydantic import Connection + from wandb.apis._generated import ProjectFragment + from wandb.apis.public.service_api import ServiceApi + + +class Projects(RelayPaginator["ProjectFragment", "Project"]): + """An lazy iterator of `Project` objects. + + An iterable interface to access projects created and saved by the entity. + + Args: + client: Legacy GraphQL client retained for API compatibility. + service_api: Interface to the wandb-core service that performs + W&B API calls for this collection. + 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: ClassVar[Document | None] = None + last_response: Connection[ProjectFragment] | None + + def __init__( + self, + client: RetryingClient, + entity: str, + per_page: int = 50, + *, + service_api: ServiceApi, + ) -> Projects: + """An iterable collection of `Project` objects. + + Args: + client: Legacy GraphQL client retained for API compatibility. + service_api: Interface to the wandb-core service that performs + W&B API calls for this collection. + entity: The entity which owns the projects. + per_page: The number of projects to fetch per request to the API. + """ + if self.QUERY is None: + from wandb.apis._generated import GET_PROJECTS_GQL + + type(self).QUERY = gql(GET_PROJECTS_GQL) + + self.entity = entity + self._service_api = service_api + super().__init__(client, variables={"entity": entity}, per_page=per_page) + + @override + def _update_response(self) -> None: + """Fetch and validate the response data for the current page.""" + from wandb._pydantic import Connection + from wandb.apis._generated import GetProjects, ProjectFragment + + data = self.client.execute(self.QUERY, variable_values=self.variables) + result = GetProjects.model_validate(data) + if not (conn := result.models): + raise ValueError(f"Unable to parse {nameof(type(self))!r} response data") + self.last_response = Connection[ProjectFragment].model_validate(conn) + + @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 + + def _convert(self, node: ProjectFragment) -> Project: + return Project( + self.client, + self.entity, + node.name, + node.model_dump(), + service_api=self._service_api, + ) + + def __repr__(self): + return f"" + + +class Project(Attrs): + """A project is a namespace for runs. + + Args: + client: Legacy GraphQL client retained for API compatibility. + service_api: Interface to the wandb-core service that performs + W&B API calls for this project. + name (str): The name of the project. + entity (str): The entity name that owns the project. + """ + + def __init__( + self, + client: RetryingClient, + entity: str, + project: str, + attrs: Mapping[str, Any], + *, + service_api: ServiceApi, + ) -> Project: + """A single project associated with an entity. + + Args: + client: Legacy GraphQL client retained for API compatibility. + service_api: Interface to the wandb-core service that performs + W&B API calls for this project. + entity: The entity which owns the project. + project: The name of the project to query. + attrs: The attributes of the project. + """ + super().__init__(attrs) + self._is_loaded = bool(attrs) + self.client = client + self.name = project + self.entity = entity + self._service_api = service_api + + def _load(self) -> None: + from requests import HTTPError + + from wandb.apis._generated import GET_PROJECT_GQL, GetProject + + gql_vars = {"name": self.name, "entity": self.entity} + try: + data = self.client.execute(gql(GET_PROJECT_GQL), gql_vars) + except HTTPError as e: + raise ValueError(f"Unable to fetch project ID: {gql_vars!r}") from e + + project = GetProject.model_validate(data).project + self._attrs = project.model_dump() if project else {} + self._is_loaded = True + + @property + def owner(self) -> public.User: + """Returns the project owner as a User object. + + Raises: + ValueError: when no user information is found for the project. + """ + if not self._is_loaded: + self._load() + if "user" not in self._attrs: + raise ValueError(f"No user found for project {self.name}") + return public.User(self.client, self._attrs["user"]) + + @property + def path(self) -> list[str]: + """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) -> str: + """Returns the URL of the project.""" + return self.client.app_url + "/".join(self.path + ["workspace"]) + + def to_html(self, height: int = 420, hidden: bool = False) -> str: + """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: int = 50) -> public.ArtifactTypes: + """Returns all artifact types associated with this project.""" + return public.ArtifactTypes( + self.client, self.entity, self.name, service_api=self._service_api + ) + + @normalize_exceptions + def collections( + self, + filters: Mapping[str, Any] | None = None, + order: str | None = None, + per_page: int = 50, + ) -> public.ProjectArtifactCollections: + """Returns all artifact collections associated with this project. + + Args: + filters: Optional mapping of filters to apply to the query. + order: Optional string to specify the order of the results. + If you prepend order with a + order is ascending (default). + If you prepend order with a - order is descending. + per_page: The number of artifact collections to fetch per page. + Default is 50. + """ + return public.ProjectArtifactCollections( + self.client, + self.entity, + self.name, + filters=filters, + order=order, + per_page=per_page, + service_api=self._service_api, + ) + + @normalize_exceptions + def sweeps(self, per_page: int = 50) -> Sweeps: + """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, + service_api=self._service_api, + ) + + @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"] + + @override + def __getattr__(self, name: str) -> Any: + if not self._is_loaded: + self._load() + return super().__getattr__(name) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/query_generator.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/query_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..56d37159b53671afb73510185e023d10579f2f97 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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: + # 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8ba451b425be56a42905463a35c0cbe8c16b56fe --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61b6bbbe6e913a8e101863d8ca5178c1f814db03 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/__pycache__/_freezable_list.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/__pycache__/_freezable_list.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ccb259fd67c29b7d975f3919a73c60b1bbf7c96 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/__pycache__/_freezable_list.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/__pycache__/_members.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/__pycache__/_members.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..feb1c6639300edece55da50d2f97e227d06cd0a2 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/__pycache__/_members.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/__pycache__/_utils.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/__pycache__/_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c16b668d4c12aa604fd0ca21bec324d006ffd53c Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/__pycache__/_utils.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/__pycache__/registries_search.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/__pycache__/registries_search.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91994ca0d3ac40a18f9e97a3f7b02b7e950f5a2f Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/__pycache__/registries_search.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/__pycache__/registry.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/__pycache__/registry.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d89b0f1d161e313cd2c0f298f11b14208b6705e Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/__pycache__/registry.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/_freezable_list.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/_freezable_list.py new file mode 100644 index 0000000000000000000000000000000000000000..08818b0da41d349e5ed89e9622d4db6f0ef5a8e2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/_freezable_list.py @@ -0,0 +1,169 @@ +from __future__ import annotations + +from collections.abc import Iterable, Iterator, MutableSequence, Sequence +from itertools import chain +from typing import Any, 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 `list.insert()`'s behavior when the index is out of bounds. + # - Negative out-of-bounds index: prepend (only works if 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/_members.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/_members.py new file mode 100644 index 0000000000000000000000000000000000000000..26bd4e1b3838e2645c28547d2365eb4fd2f0300d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/_members.py @@ -0,0 +1,111 @@ +"""Types and helpers for managing registry members.""" + +from __future__ import annotations + +from collections import defaultdict +from collections.abc import Iterable +from enum import Enum +from functools import singledispatchmethod +from typing import Literal, Union + +from pydantic.dataclasses import dataclass as pydantic_dataclass + +from wandb._strutils import b64decode_ascii, b64encode_ascii, nameof +from wandb.sdk.artifacts._models import ArtifactsBase + +from ..teams import Team +from ..users import User + + +class MemberKind(str, Enum): + """Identifies what kind of object a registry member is.""" + + USER = "User" + ENTITY = "Entity" + + TEAM = ENTITY # Convenience alias + + +class MemberRole(str, Enum): + """Identifies the role of a member.""" + + ADMIN = "admin" + MEMBER = "member" + VIEWER = "viewer" + RESTRICTED_VIEWER = "restricted_viewer" + + +class UserMember(ArtifactsBase, arbitrary_types_allowed=True): + kind: Literal[MemberKind.USER] = MemberKind.USER + + user: User + role: Union[MemberRole, str] # noqa: UP007 + + +class TeamMember(ArtifactsBase, arbitrary_types_allowed=True): + kind: Literal[MemberKind.ENTITY] = MemberKind.ENTITY + + team: Team + role: Union[MemberRole, str] # noqa: UP007 + + +MemberOrId = User | Team | UserMember | TeamMember | str +"""Type hint for a registry member argument that accepts a User, Team, or their ID.""" + + +def parse_member_ids(members: Iterable[MemberOrId]) -> tuple[list[str], list[str]]: + """Returns a tuple of (user_ids, team_ids) from parsing the given objects.""" + ids_by_kind: dict[MemberKind, set[str]] = defaultdict(set) + + for parsed in map(MemberId.from_obj, members): + ids_by_kind[parsed.kind].add(parsed.encode()) + + user_ids = ids_by_kind[MemberKind.USER] + team_ids = ids_by_kind[MemberKind.ENTITY] + + # Ordering shouldn't matter, but sort anyway for reproducibility and testing + return sorted(user_ids), sorted(team_ids) + + +@pydantic_dataclass +class MemberId: + kind: MemberKind + index: int + + def encode(self) -> str: + """Converts this parsed ID to a base64-encoded GraphQL ID.""" + return b64encode_ascii(f"{self.kind.value}:{self.index}") + + @singledispatchmethod + @classmethod + def from_obj(cls, obj: MemberOrId, /) -> MemberId: + """Parses `User` or `Team` ID from the argument.""" + # Fallback for unexpected types + raise TypeError( + f"Member arg must be a {nameof(User)!r}, {nameof(Team)!r}, or a user/team ID. " + f"Got: {nameof(type(obj))!r}" + ) + + @from_obj.register(User) + @from_obj.register(Team) + @classmethod + def _from_obj_with_id(cls, obj: User | Team, /) -> MemberId: + # Use the object's string (base64-encoded) GraphQL ID + return cls._from_id(obj.id) + + @from_obj.register(UserMember) + @classmethod + def _from_user_member(cls, member: UserMember, /) -> MemberId: + return cls._from_id(member.user.id) + + @from_obj.register(TeamMember) + @classmethod + def _from_team_member(cls, member: TeamMember, /) -> MemberId: + return cls._from_id(member.team.id) + + @from_obj.register(str) + @classmethod + def _from_id(cls, id_: str, /) -> MemberId: + # Parse the ID to figure out if it's a team or user ID + kind, index = b64decode_ascii(id_).split(":", maxsplit=1) + return cls(kind=kind, index=index) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/_utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a7ddce38d6767ccc7e35af065f95146b7bcd9524 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/_utils.py @@ -0,0 +1,126 @@ +from __future__ import annotations + +from collections.abc import Collection +from enum import Enum +from functools import lru_cache, partial +from typing import TYPE_CHECKING, Any + +from wandb_gql import gql + +from wandb._strutils import ensureprefix + +if TYPE_CHECKING: + from wandb.apis.public.api import RetryingClient + + +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: + # Allow instantiation from enum names too (e.g. "organization" or "restricted") + return cls.__members__.get(value) + + @classmethod + def from_gql(cls, value: str) -> Visibility: + """Convert a GraphQL `visibility` value to a Visibility enum.""" + try: + return cls(value) + except ValueError: + expected = ",".join(repr(e.value) for e in cls) + raise ValueError( + f"Invalid visibility {value!r} from backend. Expected one of: {expected}" + ) from None + + @classmethod + def from_python(cls, name: str) -> Visibility: + """Convert a visibility string to a `Visibility` enum.""" + try: + return cls(name) + except ValueError: + expected = ",".join(repr(e.name) for e in cls) + raise ValueError( + f"Invalid visibility {name!r}. Expected one of: {expected}" + ) from None + + +def prepare_artifact_types_input( + artifact_types: Collection[str] | None, +) -> list[dict[str, str]] | None: + """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. + """ + from wandb.sdk.artifacts._validators import validate_artifact_types + + if artifact_types: + return [{"name": typ} for typ in validate_artifact_types(artifact_types)] + return None + + +def ensure_registry_prefix_on_names(query: Any, in_name: bool = False) -> Any: + """Recursively the registry prefix to values under "name" keys, excluding regex ops. + + - in_name: True if we are under a "name" key (or propagating from one). + + EX: {"name": "model"} -> {"name": "wandb-registry-model"} + """ + from wandb.sdk.artifacts._validators import REGISTRY_PREFIX + + if isinstance((txt := query), str): + return ensureprefix(txt, REGISTRY_PREFIX) if in_name else txt + if isinstance((dct := query), dict): + new_dict = {} + for key, obj in dct.items(): + if key == "$regex": + # For regex operator, we skip transformation of its value. + new_dict[key] = obj + elif key == "name": + new_dict[key] = ensure_registry_prefix_on_names(obj, in_name=True) + else: + # For any other key, propagate flags as-is. + new_dict[key] = ensure_registry_prefix_on_names(obj, in_name=in_name) + return new_dict + if isinstance((seq := query), (list, tuple)): + return list(map(partial(ensure_registry_prefix_on_names, in_name=in_name), seq)) + return query + + +@lru_cache(maxsize=10) +def fetch_org_entity_from_organization( + client: RetryingClient, 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. + """ + from wandb.sdk.artifacts._generated import ( + FETCH_ORG_ENTITY_FROM_ORGANIZATION_GQL, + FetchOrgEntityFromOrganization, + ) + + gql_op = gql(FETCH_ORG_ENTITY_FROM_ORGANIZATION_GQL) + try: + data = client.execute(gql_op, variable_values={"organization": organization}) + except Exception as e: + msg = f"Error fetching org entity for organization: {organization!r}" + raise ValueError(msg) from e + + result = FetchOrgEntityFromOrganization.model_validate(data) + if ( + not (org := result.organization) + or not (org_entity := org.org_entity) + or not (org_name := org_entity.name) + ): + raise ValueError(f"Organization entity for {organization!r} not found.") + + return org_name diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/registries_search.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/registries_search.py new file mode 100644 index 0000000000000000000000000000000000000000..c95c5e924aa8b920ef2b7ac171c7eb770a87313c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/registries_search.py @@ -0,0 +1,342 @@ +"""Public API: registries search.""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any, ClassVar + +from pydantic import PositiveInt, ValidationError +from typing_extensions import override +from wandb_gql import gql + +from wandb._analytics import tracked +from wandb.apis.paginator import RelayPaginator, SizedRelayPaginator + +from ._utils import ensure_registry_prefix_on_names + +if TYPE_CHECKING: + from wandb_graphql.language.ast import Document + + from wandb.apis.public import ArtifactCollection, RetryingClient + from wandb.apis.public.registries.registry import Registry + from wandb.apis.public.service_api import ServiceApi + from wandb.sdk.artifacts._generated import ( + ArtifactMembershipFragment, + RegistryCollectionFragment, + RegistryFragment, + ) + from wandb.sdk.artifacts._models.pagination import ( + ArtifactMembershipConnection, + RegistryCollectionConnection, + RegistryConnection, + ) + from wandb.sdk.artifacts.artifact import Artifact + + +class Registries(RelayPaginator["RegistryFragment", "Registry"]): + """A lazy iterator of `Registry` objects.""" + + QUERY: ClassVar[Document | None] = None + last_response: RegistryConnection | None + + def __init__( + self, + client: RetryingClient, + organization: str, + filter: dict[str, Any] | None = None, + per_page: PositiveInt = 100, + start: str | None = None, + *, + service_api: ServiceApi | None = None, + ): + if self.QUERY is None: + from wandb.sdk.artifacts._generated import FETCH_REGISTRIES_GQL + + type(self).QUERY = gql(FETCH_REGISTRIES_GQL) + + self.client = client + self.organization = organization + self.filter = ensure_registry_prefix_on_names(filter or {}) + self._service_api = service_api + + variables = {"organization": organization, "filters": json.dumps(self.filter)} + super().__init__(client, variables=variables, per_page=per_page, start=start) + + 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, + per_page: PositiveInt = 100, + start: str | None = None, + ) -> Collections: + return Collections( + client=self.client, + organization=self.organization, + registry_filter=self.filter, + collection_filter=filter, + per_page=per_page, + start=start, + service_api=self._service_api, + ) + + @tracked + def versions( + self, + filter: dict[str, Any] | None = None, + per_page: PositiveInt = 100, + start: str | None = None, + ) -> Versions: + return Versions( + client=self.client, + organization=self.organization, + registry_filter=self.filter, + collection_filter=None, + artifact_filter=filter, + per_page=per_page, + start=start, + service_api=self._service_api, + ) + + @property + def length(self): + if self.last_response is None: + return None + return len(self.last_response.edges) + + @override + def _update_response(self) -> None: + from wandb.sdk.artifacts._generated import FetchRegistries + from wandb.sdk.artifacts._models.pagination import RegistryConnection + + 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: + conn = org_entity.projects + self.last_response = RegistryConnection.model_validate(conn) + except (LookupError, AttributeError, ValidationError) as e: + raise ValueError("Unexpected response data") from e + + def _convert(self, node: RegistryFragment) -> Registry: + from wandb.apis.public.registries.registry import Registry + from wandb.sdk.artifacts._validators import remove_registry_prefix + + return Registry( + client=self.client, + organization=self.organization, + entity=node.entity.name, + name=remove_registry_prefix(node.name), + attrs=node, + service_api=self._service_api, + ) + + +class Collections( + SizedRelayPaginator["RegistryCollectionFragment", "ArtifactCollection"] +): + """An lazy iterator of `ArtifactCollection` objects in a Registry.""" + + QUERY: ClassVar[Document | None] = None + last_response: RegistryCollectionConnection | None + + def __init__( + self, + client: RetryingClient, + organization: str, + registry_filter: dict[str, Any] | None = None, + collection_filter: dict[str, Any] | None = None, + per_page: PositiveInt = 100, + start: str | None = None, + *, + service_api: ServiceApi | None = None, + ): + if self.QUERY is None: + from wandb.sdk.artifacts._generated import REGISTRY_COLLECTIONS_GQL + + type(self).QUERY = gql(REGISTRY_COLLECTIONS_GQL) + + self.client = client + self.organization = organization + self.registry_filter = registry_filter + self.collection_filter = collection_filter or {} + self._service_api = service_api + + variables = { + "registryFilter": json.dumps(f) if (f := registry_filter) else None, + "collectionFilter": json.dumps(f) if (f := collection_filter) else None, + "organization": organization, + "perPage": per_page, + } + super().__init__(client, variables=variables, per_page=per_page, start=start) + + 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, + per_page: PositiveInt = 100, + start: str | None = None, + ) -> Versions: + return Versions( + client=self.client, + organization=self.organization, + registry_filter=self.registry_filter, + collection_filter=self.collection_filter, + artifact_filter=filter, + per_page=per_page, + start=start, + service_api=self._service_api, + ) + + @override + def _update_response(self) -> None: + from wandb.sdk.artifacts._generated import RegistryCollections + from wandb.sdk.artifacts._models.pagination import RegistryCollectionConnection + + data = self.client.execute(self.QUERY, variable_values=self.variables) + result = RegistryCollections.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: + conn = org_entity.artifact_collections + self.last_response = RegistryCollectionConnection.model_validate(conn) + except (LookupError, AttributeError, ValidationError) as e: + raise ValueError("Unexpected response data") from e + + def _convert(self, node: RegistryCollectionFragment) -> ArtifactCollection | None: + from wandb._pydantic import gql_typename + from wandb.apis.public import ArtifactCollection + from wandb.sdk.artifacts._generated import ArtifactSequenceTypeFields + + if not ( + # We don't _expect_ any registry collections to be + # ArtifactSequences, but defensively filter them out anyway. + node.project + and (node.typename__ != gql_typename(ArtifactSequenceTypeFields)) + ): + return None + return ArtifactCollection( + client=self.client, + entity=node.project.entity.name, + project=node.project.name, + name=node.name, + type=node.type.name, + organization=self.organization, + attrs=node, + service_api=self._service_api, + ) + + +class Versions(RelayPaginator["ArtifactMembershipFragment", "Artifact"]): + """An lazy iterator of `Artifact` objects in a Registry.""" + + QUERY: Document # Must be set per-instance + last_response: ArtifactMembershipConnection | None + + def __init__( + self, + client: RetryingClient, + 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: PositiveInt = 100, + start: str | None = None, + *, + service_api: ServiceApi | None = None, + ): + from wandb.sdk.artifacts._generated import REGISTRY_VERSIONS_GQL + + self.QUERY = gql(REGISTRY_VERSIONS_GQL) + + self.client = client + self.organization = organization + self.registry_filter = registry_filter + self.collection_filter = collection_filter + self.artifact_filter = artifact_filter or {} + self._service_api = service_api + + 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=variables, per_page=per_page, start=start) + + @override + 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) + + @override + def _update_response(self) -> None: + from wandb.sdk.artifacts._generated import RegistryVersions + from wandb.sdk.artifacts._models.pagination import ArtifactMembershipConnection + + data = self.client.execute(self.QUERY, variable_values=self.variables) + result = RegistryVersions.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: + conn = org_entity.artifact_memberships + self.last_response = ArtifactMembershipConnection.model_validate(conn) + except (LookupError, AttributeError, ValidationError) as e: + raise ValueError("Unexpected response data") from e + + def _convert(self, node: ArtifactMembershipFragment) -> Artifact | None: + from wandb.sdk.artifacts._validators import FullArtifactPath + from wandb.sdk.artifacts.artifact import Artifact + + if not ( + (collection := node.artifact_collection) + and (project := collection.project) + and node.artifact + and (version_idx := node.version_index) is not None + ): + return None + return Artifact._from_membership( + membership=node, + target=FullArtifactPath( + prefix=project.entity.name, + project=project.name, + name=f"{collection.name}:v{version_idx}", + ), + client=self.client, + service_api=self._service_api, + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/registry.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..dd8ca2d7ea3ca5e07ec797916542ce0997ed31f9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/registries/registry.py @@ -0,0 +1,680 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from pydantic import PositiveInt +from typing_extensions import Self, assert_never +from wandb_gql import gql + +import wandb +from wandb._analytics import tracked +from wandb._strutils import nameof +from wandb.apis.public.teams import Team +from wandb.apis.public.users import User +from wandb.proto import wandb_internal_pb2 as pb +from wandb.sdk.artifacts._models import RegistryData + +from ._freezable_list import AddOnlyArtifactTypesList +from ._members import ( + MemberId, + MemberKind, + MemberRole, + TeamMember, + UserMember, + parse_member_ids, +) +from ._utils import ( + Visibility, + fetch_org_entity_from_organization, + prepare_artifact_types_input, +) +from .registries_search import Collections, Versions + +if TYPE_CHECKING: + from wandb.apis.public.api import RetryingClient + from wandb.apis.public.service_api import ServiceApi + from wandb.sdk.artifacts._generated import RegistryFragment + + +class Registry: + """A single registry in the Registry.""" + + _saved: RegistryData + """The saved registry data as last fetched from the W&B server.""" + + _current: RegistryData + """The local, editable registry data.""" + + def __init__( + self, + client: RetryingClient, + organization: str, + entity: str, + name: str, + attrs: RegistryFragment | None = None, + *, + service_api: ServiceApi | None = None, + ): + self.client = client + self._service_api = service_api + + if attrs is None: + # FIXME: This is awkward and bypasses validation which seems shaky. + # Reconsider the init signature of `Registry` so this isn't necessary? + draft = RegistryData.model_construct( + organization=organization, entity=entity, name=name + ) + self._saved = draft + self._current = draft.model_copy(deep=True) + else: + self._update_attributes(attrs) + + def _update_attributes(self, fragment: RegistryFragment) -> None: + """Update instance attributes from a GraphQL fragment.""" + saved = RegistryData.from_fragment(fragment) + self._saved = saved + self._current = saved.model_copy(deep=True) + + @property + def id(self) -> str: + """The unique ID for this registry.""" + return self._current.id + + @property + def full_name(self) -> str: + """Full name of the registry including the `wandb-registry-` prefix.""" + return self._current.full_name + + @property + def name(self) -> str: + """Name of the registry without the `wandb-registry-` prefix.""" + return self._current.name + + @name.setter + def name(self, value: str): + self._current.name = value + + @property + def entity(self) -> str: + """Organization entity of the registry.""" + return self._current.entity + + @property + def organization(self) -> str: + """Organization name of the registry.""" + return self._current.organization + + @property + def description(self) -> str | None: + """Description of the registry.""" + return self._current.description + + @description.setter + def description(self, value: str) -> None: + """Set the description of the registry.""" + self._current.description = value + + @property + def allow_all_artifact_types(self) -> bool: + """Return whether all artifact types are allowed in the registry. + + If `True`, artifacts of any type can be added. If `False`, artifacts are + restricted to the types listed in `artifact_types`. + """ + return self._current.allow_all_artifact_types + + @allow_all_artifact_types.setter + def allow_all_artifact_types(self, value: bool) -> None: + """Set whether all artifact types are allowed in the registry.""" + self._current.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._current.artifact_types + + @property + def created_at(self) -> str: + """Timestamp of when the registry was created.""" + return self._current.created_at + + @property + def updated_at(self) -> str: + """Timestamp of when the registry was last updated.""" + return self._current.updated_at + + @property + def path(self) -> list[str]: + 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._current.visibility.name + + @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._current.visibility = value + + @tracked + def collections( + self, + filter: dict[str, Any] | None = None, + per_page: PositiveInt = 100, + start: str | None = None, + ) -> Collections: + """Returns the collections belonging to the registry.""" + return Collections( + client=self.client, + organization=self.organization, + registry_filter={"name": self.full_name}, + collection_filter=filter, + per_page=per_page, + start=start, + service_api=self._service_api, + ) + + @tracked + def versions( + self, + filter: dict[str, Any] | None = None, + per_page: PositiveInt = 100, + start: str | None = None, + ) -> Versions: + """Returns the versions belonging to the registry.""" + return Versions( + client=self.client, + organization=self.organization, + registry_filter={"name": self.full_name}, + collection_filter=None, + artifact_filter=filter, + per_page=per_page, + start=start, + service_api=self._service_api, + ) + + @classmethod + @tracked + def create( + cls, + client: RetryingClient, + organization: str, + name: str, + visibility: Literal["organization", "restricted"], + description: str | None = None, + artifact_types: list[str] | None = None, + *, + service_api: ServiceApi | None = None, + ) -> Self: + """Create a new registry. + + The registry name must be unique within the organization. + This function should be called using `api.create_registry()` + + Args: + client: Legacy GraphQL client retained for API compatibility. + service_api: Interface to the wandb-core service that performs + W&B API calls for the created registry. + 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. + """ + from wandb.sdk.artifacts._generated import ( + UPSERT_REGISTRY_GQL, + UpsertModelInput, + UpsertRegistry, + ) + from wandb.sdk.artifacts._validators import ( + REGISTRY_PREFIX, + validate_project_name, + ) + + failed_msg = ( + f"Failed to create registry {name!r} in organization {organization!r}." + ) + + org_entity = fetch_org_entity_from_organization(client, organization) + + gql_op = gql(UPSERT_REGISTRY_GQL) + gql_input = UpsertModelInput( + description=description, + entity_name=org_entity, + name=validate_project_name(f"{REGISTRY_PREFIX}{name}"), + access=Visibility.from_python(visibility).value, + allow_all_artifact_types_in_registry=not artifact_types, + artifact_types=prepare_artifact_types_input(artifact_types), + ) + gql_vars = {"input": gql_input.model_dump()} + try: + data = client.execute(gql_op, variable_values=gql_vars) + result = UpsertRegistry.model_validate(data).upsert_model + except Exception as e: + raise ValueError(failed_msg) from e + if not (result and result.inserted and (registry_project := result.project)): + raise ValueError(failed_msg) + + return cls( + client, + organization=organization, + entity=org_entity, + name=name, + attrs=registry_project, + service_api=service_api, + ) + + @tracked + def delete(self) -> None: + """Delete the registry. This is irreversible.""" + from wandb.sdk.artifacts._generated import DELETE_REGISTRY_GQL, DeleteRegistry + + failed_msg = f"Failed to delete registry {self.name!r} in organization {self.organization!r}" + + gql_op = gql(DELETE_REGISTRY_GQL) + gql_vars = {"id": self.id} + try: + data = self.client.execute(gql_op, variable_values=gql_vars) + result = DeleteRegistry.model_validate(data).delete_model + except Exception as e: + raise ValueError(failed_msg) from e + if not (result and result.success): + raise ValueError(failed_msg) + + @tracked + def load(self) -> None: + """Load registry attributes from the backend.""" + from wandb.sdk.artifacts._generated import FETCH_REGISTRY_GQL, FetchRegistry + + failed_msg = ( + f"Failed to load registry {self.name!r} in organization" + f" {self.organization!r}." + ) + + gql_op = gql(FETCH_REGISTRY_GQL) + gql_vars = {"name": self.full_name, "entity": self.entity} + try: + data = self.client.execute(gql_op, variable_values=gql_vars) + result = FetchRegistry.model_validate(data) + except Exception as e: + raise ValueError(failed_msg) from e + + if not ((entity := result.entity) and (registry_project := entity.project)): + raise ValueError(failed_msg) + + self._update_attributes(registry_project) + + @tracked + def save(self) -> None: + """Save registry attributes to the backend.""" + from wandb.sdk.artifacts._generated import ( + RENAME_REGISTRY_GQL, + UPSERT_REGISTRY_GQL, + RenameProjectInput, + RenameRegistry, + UpsertModelInput, + UpsertRegistry, + ) + from wandb.sdk.artifacts._gqlutils import server_supports + from wandb.sdk.artifacts._validators import validate_project_name + + if not server_supports( + self.client, pb.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 `artifact_types.draft` has items, the user added types that are not + # yet saved. + if ( + new_artifact_types := self.artifact_types.draft + ) and self.allow_all_artifact_types: + raise ValueError( + f"Cannot update artifact types when `allows_all_artifact_types` is {True!r}. Set it to {False!r} first." + ) + + failed_msg = f"Failed to save registry {self.name!r} in organization {self.organization!r}" + + old_project_name = validate_project_name(self._saved.full_name) + new_project_name = validate_project_name(self._current.full_name) + + upsert_op = gql(UPSERT_REGISTRY_GQL) + upsert_input = UpsertModelInput( + description=self.description, + entity_name=self.entity, + name=old_project_name, + access=self._current.visibility.value, + allow_all_artifact_types_in_registry=self.allow_all_artifact_types, + artifact_types=prepare_artifact_types_input(new_artifact_types), + ) + upsert_vars = {"input": upsert_input.model_dump()} + try: + data = self.client.execute(upsert_op, variable_values=upsert_vars) + result = UpsertRegistry.model_validate(data).upsert_model + except Exception as e: + raise ValueError(failed_msg) from e + + if result and result.inserted: + # This should only trigger if `_saved_name` was modified unexpectedly. + wandb.termlog( + f"Created registry {self.name!r} in organization {self.organization!r} on save" + ) + + if not (result and (registry_project := result.project)): + raise ValueError(failed_msg) + + self._update_attributes(registry_project) + + # Update the name of the registry if it has changed + if old_project_name != new_project_name: + rename_op = gql(RENAME_REGISTRY_GQL) + rename_input = RenameProjectInput( + entity_name=self.entity, + old_project_name=old_project_name, + new_project_name=new_project_name, + ) + rename_vars = {"input": rename_input.model_dump()} + data = self.client.execute(rename_op, variable_values=rename_vars) + result = RenameRegistry.model_validate(data).rename_project + if not (result and (registry_project := result.project)): + raise ValueError(failed_msg) + + if result.inserted: + # This should only trigger if `_saved_name` was modified unexpectedly. + wandb.termlog(f"Created new registry {self.name!r} on save") + + self._update_attributes(registry_project) + + def members(self) -> list[UserMember | TeamMember]: + """Returns the current members (users and teams) of this registry.""" + return [*self.user_members(), *self.team_members()] + + def user_members(self) -> list[UserMember]: + """Returns the current member users of this registry.""" + from wandb.sdk.artifacts._generated import ( + REGISTRY_USER_MEMBERS_GQL, + RegistryUserMembers, + ) + + gql_op = gql(REGISTRY_USER_MEMBERS_GQL) + gql_vars = {"project": self.full_name, "entity": self.entity} + data = self.client.execute(gql_op, variable_values=gql_vars) + result = RegistryUserMembers.model_validate(data) + + if not (project := result.project): + raise ValueError(f"Failed to fetch user members for registry {self.name!r}") + + return [ + UserMember( + user=User( + client=self.client, + # The `User` class requires an unstructured attribute dict. + # Exclude `.role`, which is specific to this registry membership. + attrs=m.model_dump(exclude_none=True, exclude={"role"}), + ), + role=m.role.name, + ) + for m in project.members + ] + + def team_members(self) -> list[TeamMember]: + """Returns the current member teams of this registry.""" + from wandb.sdk.artifacts._generated import ( + REGISTRY_TEAM_MEMBERS_GQL, + RegistryTeamMembers, + ) + + gql_op = gql(REGISTRY_TEAM_MEMBERS_GQL) + gql_vars = {"project": self.full_name, "entity": self.entity} + data = self.client.execute(gql_op, variable_values=gql_vars) + result = RegistryTeamMembers.model_validate(data) + + if not (project := result.project): + raise ValueError(f"Failed to fetch team members for registry {self.name!r}") + + return [ + TeamMember( + team=Team( + client=self.client, + name=m.team.name, + # The `Team` class currently requires an unstructured attribute dict. + attrs=m.team.model_dump(exclude_none=True), + ), + role=m.role.name, + ) + for m in project.team_members + ] + + def add_members( + self, *members: User | UserMember | Team | TeamMember | str + ) -> Self: + """Adds users or teams to this registry. + + Args: + members: The users or teams to add to the registry. Accepts + `User` objects, `Team` objects, or their string IDs. + + Returns: + This registry for further method chaining, if needed. + + Raises: + TypeError: If no members are passed as arguments. + ValueError: If unable to infer or parse the user or team IDs. + + Examples: + ```python + import wandb + + api = wandb.Api() + + # Fetch an existing registry + registry = api.registry(name="my-registry", organization="my-org") + + user1 = api.user(username="some-user") + user2 = api.user(username="other-user") + registry.add_members(user1, user2) + + my_team = api.team(name="my-team") + registry.add_members(my_team) + ``` + """ + from wandb.sdk.artifacts._generated import ( + CREATE_REGISTRY_MEMBERS_GQL, + CreateProjectMembersInput, + CreateRegistryMembers, + ) + + if not members: + raise TypeError( + f"Must provide at least one member to {nameof(self.add_members)!r}." + ) + user_ids, team_ids = parse_member_ids(members) + + gql_op = gql(CREATE_REGISTRY_MEMBERS_GQL) + gql_input = CreateProjectMembersInput( + user_ids=user_ids, team_ids=team_ids, project_id=self.id + ) + gql_vars = {"input": gql_input.model_dump()} + data = self.client.execute(gql_op, variable_values=gql_vars) + result = CreateRegistryMembers.model_validate(data).result + + if not (result and result.success): + raise ValueError(f"Failed to add members to registry {self.name!r}") + return self + + def remove_members( + self, *members: User | UserMember | Team | TeamMember | str + ) -> Self: + """Removes users or teams from this registry. + + Args: + members: The users or teams to remove from the registry. Accepts + `User` objects, `Team` objects, or their string IDs. + + Returns: + This registry for further method chaining, if needed. + + Raises: + TypeError: If no members are passed as arguments. + ValueError: If unable to infer or parse the user or team IDs. + + Examples: + ```python + import wandb + + api = wandb.Api() + + # Fetch an existing registry + registry = api.registry(name="my-registry", organization="my-org") + + user1 = api.user(username="some-user") + user2 = api.user(username="other-user") + registry.remove_members(user1, user2) + + old_team = api.team(name="old-team") + registry.remove_members(old_team) + ``` + """ + from wandb.sdk.artifacts._generated import ( + DELETE_REGISTRY_MEMBERS_GQL, + DeleteProjectMembersInput, + DeleteRegistryMembers, + ) + + if not members: + raise TypeError( + f"Must provide at least one member to {nameof(self.add_members)!r}." + ) + user_ids, team_ids = parse_member_ids(members) + + gql_op = gql(DELETE_REGISTRY_MEMBERS_GQL) + gql_input = DeleteProjectMembersInput( + user_ids=user_ids, team_ids=team_ids, project_id=self.id + ) + gql_vars = {"input": gql_input.model_dump()} + data = self.client.execute(gql_op, variable_values=gql_vars) + result = DeleteRegistryMembers.model_validate(data).result + + if not (result and result.success): + raise ValueError(f"Failed to remove members from registry {self.name!r}") + return self + + def update_member( + self, + member: User | UserMember | Team | TeamMember | str, + role: MemberRole | str, + ) -> Self: + """Updates the role of a member (user or team) within this registry. + + Args: + member: The user or team to update the role of. + Accepts a `User` object, `Team` object, or their string ID. + role: The new role to assign to the member. May be one of: + - "admin" + - "member" + - "viewer" + - "restricted_viewer" (if supported by the W&B server) + + Returns: + This registry for further method chaining, if needed. + + Raises: + ValueError: If unable to infer the user or team ID. + + Examples: + Make all users in the registry admins + ```python + import wandb + + api = wandb.Api() + + # Fetch an existing registry + registry = api.registry(name="my-registry", organization="my-org") + + for member in registry.user_members(): + registry.update_member(member.user, role="admin") + ``` + """ + from wandb.sdk.artifacts._generated import ( + UPDATE_TEAM_REGISTRY_ROLE_GQL, + UPDATE_USER_REGISTRY_ROLE_GQL, + UpdateProjectMemberInput, + UpdateProjectTeamMemberInput, + UpdateTeamRegistryRole, + UpdateUserRegistryRole, + ) + + id_ = MemberId.from_obj(member) + + if id_.kind is MemberKind.USER: + gql_op = gql(UPDATE_USER_REGISTRY_ROLE_GQL) + gql_input = UpdateProjectMemberInput( + user_id=id_.encode(), project_id=self.id, user_project_role=role + ) + result_cls = UpdateUserRegistryRole + elif id_.kind is MemberKind.ENTITY: + gql_op = gql(UPDATE_TEAM_REGISTRY_ROLE_GQL) + gql_input = UpdateProjectTeamMemberInput( + team_id=id_.encode(), project_id=self.id, team_project_role=role + ) + result_cls = UpdateTeamRegistryRole + else: + assert_never(id_.kind) + + gql_vars = {"input": gql_input.model_dump()} + data = self.client.execute(gql_op, variable_values=gql_vars) + result = result_cls.model_validate(data).result + + if not (result and result.success): + raise ValueError( + f"Failed to update member {member!r} role to {role!r} in registry {self.name!r}" + ) + return self diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/reports.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/reports.py new file mode 100644 index 0000000000000000000000000000000000000000..9c714a70e89f96b65bcbb229ae2ce17a93788fa3 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/reports.py @@ -0,0 +1,647 @@ +"""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 typing import TYPE_CHECKING, Any + +from wandb_gql import gql + +import wandb +from wandb._strutils import nameof +from wandb.apis import public +from wandb.apis.attrs import Attrs +from wandb.apis.paginator import SizedPaginator +from wandb.sdk.lib import ipython + +if TYPE_CHECKING: + from .api import RetryingClient + from .projects import Project + from .service_api import ServiceApi + + +class Reports(SizedPaginator["BetaReport"]): + """Reports is a lazy iterator of `BetaReport` objects. + + Args: + client: Legacy GraphQL client retained for API compatibility. + service_api: Interface to the wandb-core service that performs + W&B API calls for this collection. + 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: RetryingClient, + project: Project, + name: str | None = None, + entity: str | None = None, + per_page: int = 50, + *, + service_api: ServiceApi, + ): + self.project = project + self.name = name + self._service_api = service_api + variables = { + "project": project.name, + "entity": project.entity, + "viewName": self.name, + } + super().__init__(client, variables, per_page) + + @property + def _length(self) -> int | None: + """The number of reports in the project. + + + """ + # TODO: Add the count the backend + if not self.last_response: + return None + + return len(self.objects) + + @property + def more(self) -> bool: + """Returns whether there are more files to fetch. + + + """ + if not self.last_response: + return True + + project = self.last_response.get("project") or {} + views_data = project.get("allViews") or {} + page_info = views_data.get("pageInfo") or {} + return page_info.get("hasNextPage", False) + + @property + def cursor(self) -> str | None: + """Returns the cursor position for pagination of file results. + + + """ + if not self.last_response: + return None + + project = self.last_response.get("project") or {} + views_data = project.get("allViews") or {} + edges = views_data.get("edges") or [] + + if not edges: + return None + + return edges[-1].get("cursor") + + def update_variables(self) -> None: + """Updates the GraphQL query variables for pagination.""" + self.variables.update( + {"reportCursor": self.cursor, "reportLimit": self.per_page} + ) + + def convert_objects(self) -> list[BetaReport]: + """Converts GraphQL edges to File objects.""" + if not self.last_response: + return [] + + project = self.last_response.get("project") + if project is None: + raise ValueError( + f"Project {self.variables['project']} does not exist under entity {self.variables['entity']}" + ) + + all_views = project.get("allViews") or {} + edges = all_views.get("edges") or [] + + return [ + BetaReport( + self.client, + r["node"], + entity=self.project.entity, + project=self.project.name, + service_api=self._service_api, + ) + for r in edges + ] + + def __repr__(self) -> str: + return f"<{nameof(type(self))} {'/'.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: RetryingClient, + attrs: dict, + entity: str | None = None, + project: str | None = None, + *, + service_api: ServiceApi, + ): + self.client = client + self.project = project + self.entity = entity + self._service_api = service_api + 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) -> dict[str, Any]: + return self._attrs["spec"] + + @property + def sections(self): + """Get the panel sections (groups) from the report.""" + return self.spec["panelGroups"] + + def runs( + self, + section: dict[str, Any], + per_page: int = 50, + only_selected: bool = True, + ) -> public.Runs: + """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, + service_api=self._service_api, + ) + + @property + def id(self) -> str: + return self._attrs.get("id") + + @property + def name(self) -> str | None: + return self._attrs.get("name") + + @property + def display_name(self) -> str | None: + return self._attrs.get("displayName") + + @property + def description(self) -> str | None: + 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) -> str | None: + 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: int = 1024, hidden: bool = False) -> str: + """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:], strict=False), 1): + if mid == "." and ( + 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:], strict=False): + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/runhistory/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/runhistory/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..90eb9ae464d00bc00dc29e5158cf4704bea2e254 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/runhistory/__init__.py @@ -0,0 +1,11 @@ +__all__ = ( + "DownloadHistoryResult", + "IncompleteRunHistoryError", + "wait_for_download_with_progress", +) + +from .downloads import ( + DownloadHistoryResult, + IncompleteRunHistoryError, + wait_for_download_with_progress, +) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/runhistory/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/runhistory/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..779eba9980c26ec8c6f65a40b4ac8a04eb1cacf4 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/runhistory/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/runhistory/__pycache__/downloads.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/runhistory/__pycache__/downloads.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a5538a6aef7bd0e2ae504e5b74ec5a12b8dfe66 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/runhistory/__pycache__/downloads.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/runhistory/downloads.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/runhistory/downloads.py new file mode 100644 index 0000000000000000000000000000000000000000..172d32bb61d4817630ab4f3987de480332f5ef25 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/runhistory/downloads.py @@ -0,0 +1,138 @@ +from __future__ import annotations + +import asyncio +import pathlib +import time +from dataclasses import dataclass + +from wandb.apis.public.service_api import ServiceApi +from wandb.proto import wandb_api_pb2 as apb +from wandb.sdk.lib import asyncio_compat +from wandb.sdk.lib.printer import new_printer +from wandb.sdk.lib.progress import progress_printer +from wandb.sdk.lib.service.service_connection import WandbApiFailedError + +_POLL_WAIT_SECONDS = 0.1 + + +class IncompleteRunHistoryError(Exception): + """Raised when run history has incomplete history. + + Incomplete history occurs when some data has not been exported to + parquet files yet, typically because the run is still ongoing. + """ + + +@dataclass(frozen=True) +class DownloadHistoryResult: + """Result of downloading a run's history exports. + + Attributes: + paths: The paths to the downloaded history files. + errors: A dictionary mapping file paths to error messages for files that + failed to download. None if all downloads succeeded. + contains_live_data: Whether the run contains live data, + not yet exported to parquet files. + """ + + paths: list[pathlib.Path] + contains_live_data: bool + errors: dict[pathlib.Path, str] | None = None + + +async def wait_for_download_with_progress( + service_api: ServiceApi, + request_id: int, + contains_live_data: bool, +) -> DownloadHistoryResult: + return await _DownloadStatusWatcher( + service_api=service_api, + request_id=request_id, + contains_live_data=contains_live_data, + ).wait_with_progress() + + +class _DownloadStatusWatcher: + def __init__( + self, + service_api: ServiceApi, + request_id: int, + contains_live_data: bool, + ): + self._service_api = service_api + self.request_id = request_id + self.contains_live_data = contains_live_data + self.done_event = asyncio.Event() + self.download_result: DownloadHistoryResult | None = None + self._rate_limit_last_time: float | None = None + + async def wait_with_progress(self) -> DownloadHistoryResult: + async with asyncio_compat.open_task_group() as group: + group.start_soon(self._wait_then_mark_done()) + group.start_soon(self._show_progress_until_done()) + + if self.download_result is None: + raise WandbApiFailedError("Failed to get download status") + return self.download_result + + async def _wait_then_mark_done(self) -> None: + api_request = apb.ApiRequest( + read_run_history_request=apb.ReadRunHistoryRequest( + download_run_history=apb.DownloadRunHistory( + request_id=self.request_id, + ) + ) + ) + + handle = await self._service_api.send_api_request_async(api_request) + response = await handle.wait_async(timeout=None) + + downloaded_files = [ + pathlib.Path(file_name) + for file_name in response.read_run_history_response.download_run_history.downloaded_files + ] + errors = { + pathlib.Path(file_name): error_message + for file_name, error_message in response.read_run_history_response.download_run_history.errors.items() + } + + self.download_result = DownloadHistoryResult( + paths=downloaded_files, + contains_live_data=self.contains_live_data, + errors=errors, + ) + + self.done_event.set() + + async def _show_progress_until_done(self) -> None: + p = new_printer() + with progress_printer(p, "Downloading history...") as progress: + while not await self._rate_limit_check_done(): + status_request = apb.ApiRequest( + read_run_history_request=apb.ReadRunHistoryRequest( + download_run_history_status=apb.DownloadRunHistoryStatus( + request_id=self.request_id, + ) + ) + ) + handle = await self._service_api.send_api_request_async(status_request) + last_response = await handle.wait_async(timeout=None) + + if last_response is not None: + progress.update( + last_response.read_run_history_response.download_run_history_status.operation_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( + asyncio.sleep(_POLL_WAIT_SECONDS - time_since_last), + self.done_event.wait(), + ) + + return self.done_event.is_set() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/runs.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/runs.py new file mode 100644 index 0000000000000000000000000000000000000000..a76e88aa55048cdd93860e516bab2b6faba4ab52 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/runs.py @@ -0,0 +1,1736 @@ +"""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 pathlib +import tempfile +import time +import urllib.parse +from collections.abc import Collection, Iterator, Mapping +from typing import TYPE_CHECKING, Any, Literal + +from typing_extensions import override + +import wandb +import wandb.apis.public.runhistory as runhistory +from wandb import env, util +from wandb._strutils import nameof +from wandb.apis import public +from wandb.apis._generated import GET_AGENT_RUNS_GQL +from wandb.apis._generated.get_agent_runs import GetAgentRuns +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.proto import wandb_api_pb2 as apb +from wandb.sdk import wandb_setup +from wandb.sdk.lib import ipython, json_util +from wandb.sdk.lib.paths import LogicalPath +from wandb.sdk.lib.service.service_connection import WandbApiFailedError + +if TYPE_CHECKING: + import pandas as pd + import polars as pl + from typing_extensions import Self + + from wandb.apis.public import RetryingClient + from wandb.apis.public.service_api import ServiceApi + from wandb.old.summary import HTTPSummary + +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) -> str: + """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 f"""#graphql + query Runs($project: String!, $entity: String!, $cursor: String, $perPage: Int = 50, $order: String, $filters: JSONString) {{ + project(name: $project, entityName: $entity) {{ + internalId + runCount(filters: $filters) + readOnly + runs(filters: $filters, after: $cursor, first: $perPage, order: $order) {{ + edges {{ + node {{ + projectId + ...{fragment_name} + }} + cursor + }} + pageInfo {{ + endCursor + hasNextPage + }} + }} + }} + }} + {fragment} + """ + + +@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: Legacy GraphQL client retained for API compatibility. + service_api: Interface to the wandb-core service that performs + W&B API calls for this collection. + 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. + """ + + 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, + *, + service_api: ServiceApi, + ): + if not order: + order = "+created_at" + + self.QUERY = _create_runs_query(lazy=lazy) + + self.entity = entity + self.project = project + self._project_internal_id = None + self.filters = filters or {} + self.order = order + self._sweeps: dict[str, public.Sweep] = {} + self._include_sweeps = include_sweeps + self._lazy = lazy + self._service_api = service_api + variables = { + "project": self.project, + "entity": self.entity, + "order": self.order, + "filters": json.dumps(self.filters), + } + super().__init__(client, variables, per_page) + + @override + def _update_response(self) -> None: + self.last_response = self._service_api.execute_graphql( + self.QUERY, + self.variables, + ) + + @property + def _length(self) -> int: + """Returns the total number of runs. + + + """ + if not self.last_response: + self._load_page() + + if not self.last_response: + return 0 + + project = self.last_response.get("project") or {} + return project.get("runCount", 0) + + @property + def more(self) -> bool: + """Returns whether there are more runs to fetch. + + + """ + if not self.last_response: + return True + + project = self.last_response.get("project") or {} + runs_data = project.get("runs") or {} + page_info = runs_data.get("pageInfo") or {} + return page_info.get("hasNextPage", False) + + @property + def cursor(self): + """Returns the cursor position for pagination of runs results. + + + """ + if not self.last_response: + return None + + project = self.last_response.get("project") or {} + runs_data = project.get("runs") or {} + edges = runs_data.get("edges") or [] + + if not edges: + return None + + return edges[-1].get("cursor") + + def convert_objects(self) -> list[Run]: + """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)) + + project = self.last_response.get("project") or {} + runs_data = project.get("runs") or {} + edges = runs_data.get("edges") or [] + for run_response in edges: + run = Run( + self.client, + self.entity, + self.project, + run_response["node"]["name"], + run_response["node"], + include_sweeps=self._include_sweeps, + lazy=self._lazy, + service_api=self._service_api, + ) + 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, + service_api=self._service_api, + ) + 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", + ) -> list[dict[str, Any]] | pd.DataFrame | pl.DataFrame: + """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) -> str: + return f"<{nameof(type(self))} {self.entity}/{self.project}>" + + def upgrade_to_full(self) -> None: + """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) + + # 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 AgentRuns(SizedPaginator["Run"]): + """A lazy iterator of `Run` objects for a single sweep agent. + + + """ + + def __init__( + self, + client: RetryingClient, + entity: str, + project: str, + sweep_id: str, + agent_key: str, + *, + total_runs: int, + order: str = "+created_at", + per_page: int = 50, + service_api: ServiceApi, + ) -> None: + self.QUERY = GET_AGENT_RUNS_GQL + self.entity = entity + self.project = project + self._sweep_id = sweep_id + self._agent_key = agent_key + self.order = order + self._sweeps: dict[str, public.Sweep] = {} + self._service_api = service_api + self._total_runs = total_runs + self.per_page = per_page + + variables = { + "project": self.project, + "entity": self.entity, + "order": self.order, + "agentID": self._agent_key, + "sweep": self._sweep_id, + "after": None, + "before": None, + "first": self.per_page, + "last": None, + } + super().__init__(client, variables, per_page) + + @override + def _update_response(self) -> None: + self.last_response = self._service_api.execute_graphql( + self.QUERY, + self.variables, + ) + + @override + def update_variables(self) -> None: + """Map paginator state to GetAgentRuns variables (after/first, not cursor/perPage).""" + self.variables.update( + { + "first": self.per_page, + "after": self.cursor, + "before": None, + "last": None, + } + ) + + @property + @override + def _length(self) -> int: + return self._total_runs + + def _parsed(self) -> GetAgentRuns: + assert self.last_response is not None + return GetAgentRuns.model_validate(self.last_response) + + def _agent_runs_connection(self): + parsed = self._parsed() + if not parsed.project: + raise ValueError(f"Could not find project {self.project!r} for agent runs.") + if not parsed.project.sweep: + raise ValueError(f"Could not find sweep {self._sweep_id!r} for agent runs.") + if not parsed.project.sweep.agent: + raise ValueError( + f"Could not find agent {self._agent_key!r} for agent runs." + ) + return parsed.project.sweep.agent.runs + + @property + @override + def more(self) -> bool: + return self.last_response is None or bool( + self._agent_runs_connection().page_info.has_next_page + ) + + @property + @override + def cursor(self) -> str | None: + if not self.last_response: + return None + edges = self._agent_runs_connection().edges + return edges[-1].cursor if edges else None + + @override + def convert_objects(self) -> list[Run]: + """Convert the current GraphQL page into :class:`Run` instances for this agent.""" + objs = [] + for edge in self._agent_runs_connection().edges: + node = edge.node.model_dump(by_alias=True) + run = Run( + self.client, + self.entity, + self.project, + node["name"], + node, + include_sweeps=False, + lazy=True, + service_api=self._service_api, + ) + objs.append(run) + + return objs + + @override + def __repr__(self) -> str: + return f"<{nameof(type(self))} {self.entity}/{self.project} agent={self._agent_key!r}>" + + +class Run(Attrs): + """A single run associated with an entity and project. + + Args: + client: Legacy GraphQL client retained for API compatibility. + service_api: Interface to the wandb-core service that performs + W&B API calls for this run. + 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): History metric keys logged with `wandb.Run.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, + *, + service_api: ServiceApi, + ): + """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._is_loaded: bool = False + self._service_api = service_api + + self.load(force=not _attrs) + + @property + def state(self) -> str: + """The state of the run. Can be one of: Finished, Failed, Crashed, or Running.""" + return self._state + + @property + def entity(self) -> str: + """The entity associated with the run.""" + return self._entity + + @property + def username(self) -> str: + """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) -> str: + """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) -> str: + """The unique identifier for the run.""" + return self._attrs.get("name") + + @id.setter + def id(self, new_id: str) -> None: + """Set the unique identifier for the run.""" + self._attrs["name"] = new_id + + @property + def name(self) -> str | None: + """The name of the run.""" + return self._attrs.get("displayName") + + @name.setter + def name(self, new_name: str) -> None: + """Set the name of the run.""" + self._attrs["displayName"] = 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", + ) -> Self: + """Create a run for the given project. + + For most use cases, use `wandb.init()`. `wandb.init()` provides more robust + logic for creating and updating runs. `wandb.apis.public.Run.create` + is intended for specific scenarios such as creating runs in + a "pending" state for jobs that may be unschedulable + (for example, in a Kubernetes cluster with insufficient GPUs or high + contention). These pending runs can later be resumed and tracked by W&B. + + Runs created with this method have limited functionality. Calling + `update()` on a run created this way may not work as expected. + + Args: + api: The W&B API instance. + run_id: Optional run ID. If not provided, a random ID will be generated. + project: Optional project name. Defaults to the project in API settings + or "uncategorized". + entity: Optional entity (user or team) name. + state: Initial state of the run. Use "pending" for runs that will be + resumed later, or "running" for immediate execution. + + Returns: + A Run object representing the created run. + + Example: + Creating a pending run for later execution + + ```python + import wandb + + api = wandb.Api() + + run_name = "my-pending-run" + + run = Run.create( + api=api, + project="project", + entity="entity", + state="pending", + run_id=run_name, + ) + ``` + """ + return api._create_run( + run_id=run_id, + project=project, + entity=entity, + state=state, + ) + + def _load_with_fragment( + self, fragment: str, fragment_name: str, force: bool = False + ) -> dict[str, Any]: + """Load run data using specified GraphQL fragment.""" + query = f"""#graphql + query Run($project: String!, $entity: String!, $name: String!) {{ + project(name: $project, entityName: $entity) {{ + run(name: $name) {{ + projectId + ...{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, + service_api=self._service_api, + ) + + if not self._is_loaded or force: + # 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 + + # Always 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() + + # Only mark as loaded for lightweight fragments, not full fragments + if fragment_name == LIGHTWEIGHT_RUN_FRAGMENT_NAME: + self._is_loaded = True + + return self._attrs + + def _load_from_attrs(self) -> dict[str, Any]: + # Snapshot before mutating: only persist config/rawconfig when the response + # included a config field (lazy runs omit it until load_full_data()). + had_config_field = "config" in self._attrs + self._state = self._attrs.get("state", None) + + # Only convert fields if they exist in _attrs + if had_config_field: + 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.get( + self.client, + self.entity, + self.project, + self._attrs["sweepName"], + withRuns=False, + service_api=self._service_api, + ) + + 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 + + if had_config_field: + config_raw.update(config_user) + self._attrs["config"] = config_user + self._attrs["rawconfig"] = config_raw + + if "user" in self._attrs: + self.user = public.User(self.client, self._attrs["user"]) + + return self._attrs + + def load(self, force: bool = False) -> dict[str, Any]: + """Load run data using appropriate fragment based on lazy mode.""" + # Load any provided attrs + if self._attrs: + self._load_from_attrs() + + 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) -> None: + """Check the state of the run until it is finished.""" + query = """ + 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) -> None: + """Persist changes to the run object to the wandb backend.""" + mutation = """ + 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: bool = False) -> None: + """Delete the given run from the wandb backend. + + Args: + delete_artifacts (bool, optional): Whether to delete the artifacts + associated with the run. + """ + mutation = """ + mutation DeleteRun( + $id: ID!, + {} + ) {{ + deleteRun(input: {{ + id: $id, + {} + }}) {{ + clientMutationId + }} + }} + """.format( + "$deleteArtifacts: Boolean" if delete_artifacts else "", + "deleteArtifacts: $deleteArtifacts" if delete_artifacts else "", + ) + + self._service_api.execute_graphql( + mutation, + { + "id": self.storage_id, + "deleteArtifacts": delete_artifacts, + }, + ) + + def save(self) -> None: + """Persist changes to the run object to the W&B backend.""" + self.update() + + @normalize_exceptions + def update_state(self, state: Literal["pending"]) -> bool: + """Update the state of a run. + + Allows transitioning runs from 'failed' or 'crashed' to 'pending'. + + Args: + state: The target run state. Only `"pending"` is supported. + + Returns: + `True` if the state was successfully updated. + + Raises: + `wandb.Error`: If the requested state transition is not allowed, or the server + does not support this operation. + """ + mutation = """ + mutation UpdateRunState($input: UpdateRunStateInput!) { + updateRunState(input: $input) { + success + } + } + """ + + try: + result = self._service_api.execute_graphql( + mutation, + { + "input": { + "id": self.storage_id, + "state": state, + } + }, + ) + except Exception as e: + error_msg = str(e) + if "UpdateRunStateInput" in error_msg or "updateRunState" in error_msg: + raise wandb.Error( + "The server does not support the update_state operation. " + "Please ensure your W&B server is updated to a version that " + "supports run state transitions." + ) from e + if "invalid state transition" in error_msg.lower(): + raise wandb.Error( + f"Invalid state transition: cannot change run from '{self.state}' " + f"to '{state}'. Only runs in 'failed' or 'crashed' state can be " + "transitioned to 'pending'." + ) from e + raise + + if result.get("updateRunState", {}).get("success"): + self._attrs["state"] = state + self._state = state + return True + return False + + @property + def json_config(self) -> str: + """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: str, **kwargs: Any) -> dict[str, Any]: + """Execute a query against the cloud backend.""" + variables = {"entity": self.entity, "project": self.project, "name": self.id} + variables.update(kwargs) + return self._service_api.execute_graphql(query, variables) + + def _sampled_history( + self, + keys: list[str], + x_axis: str = "_step", + samples: int = 500, + ) -> list[dict[str, Any]]: + spec = {"keys": [x_axis] + keys, "samples": samples} + query = """ + 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: int = 500, + stream: Literal["default", "system"] = "default", + ) -> list[dict[str, Any]]: + node = "history" if stream == "default" else "events" + query = """ + 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, + ) -> public.Files: + """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: str) -> public.File: + """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: str, root: str = ".") -> public.File: + """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: int = 500, + keys: list[str] | None = None, + x_axis: str = "_step", + pandas: bool = True, + stream: Literal["default", "system"] = "default", + ) -> list[dict[str, Any]] | pd.DataFrame: + """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: list[str] | None = None, + page_size: int = 1_000, + min_step: int | None = None, + max_step: int | None = None, + ) -> Iterator[dict[str, Any]]: + """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, + service_api=self._service_api, + page_size=page_size, + min_step=min_step, + max_step=max_step, + ) + else: + return public.SampledHistoryScan( + run=self, + client=self.client, + service_api=self._service_api, + 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, + service_api=self._service_api, + ) + + @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, + service_api=self._service_api, + ) + + @normalize_exceptions + def use_artifact( + self, + artifact: wandb.Artifact, + use_as: str | None = None, + ) -> wandb.Artifact: + """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, + ) -> wandb.Artifact: + """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, + entity_name=self.entity, + project_name=self.project, + 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) -> dict[str, Any]: + """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() + + # Ensure config is always converted to dict (defensive against conversion issues) + config_value = self._attrs.get("config", {}) + # _convert_to_dict handles dict inputs (noop) and converts str/bytes/bytearray to dict + config_value = _convert_to_dict(config_value) + self._attrs["config"] = config_value + return config_value + + @property + def summary(self) -> HTTPSummary: + """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) -> dict[str, Any]: + """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() + + # Ensure systemMetrics is always converted to dict (defensive against conversion issues) + system_metrics_value = self._attrs.get("systemMetrics", {}) + # _convert_to_dict handles dict inputs (noop) and converts str/bytes/bytearray to dict + system_metrics_value = _convert_to_dict(system_metrics_value) + self._attrs["systemMetrics"] = system_metrics_value + return system_metrics_value + + @property + def summary_metrics(self) -> dict[str, Any]: + """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() + + # Ensure summaryMetrics is always converted to dict (defensive against conversion issues) + summary_metrics_value = self._attrs.get("summaryMetrics", {}) + # _convert_to_dict handles dict inputs (noop) and converts str/bytes/bytearray to dict + summary_metrics_value = _convert_to_dict(summary_metrics_value) + self._attrs["summaryMetrics"] = summary_metrics_value + return summary_metrics_value + + @property + def rawconfig(self) -> dict[str, Any]: + """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) -> str | None: + """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) -> list[str]: + """The path of the run. The path is a list containing the entity, project, and run_id.""" + return [ + urllib.parse.quote(str(self.entity), safe=""), + urllib.parse.quote(str(self.project), safe=""), + urllib.parse.quote(str(self.id), safe=""), + ] + + @property + def url(self) -> str: + """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) -> dict[str, Any] | None: + """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) -> int: # noqa: N802 + """Returns the last step logged in the run's history.""" + query = """ + 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.get("lastStep", -1) + + def to_html(self, height: int = 420, hidden: bool = False) -> str: + """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: + if ipython.in_vscode_notebook(): + import html + + return html.escape(self._string_representation()) + + return self.to_html() + + def __repr__(self) -> str: + return self._string_representation() + + def _string_representation(self) -> str: + return f"<{nameof(type(self))} {'/'.join(self.path)} ({self.state})>" + + def beta_scan_history( + self, + keys: list[str] | None = None, + page_size: int = 1_000, + min_step: int = 0, + max_step: int | None = None, + use_cache: bool = True, + ) -> public.BetaHistoryScan: + """Returns an iterable collection of all history records for a run. + + This function is still in development and may not work as expected. + It uses wandb-core to read history from a run's exported + parquet history locally. + + Args: + keys: list of metrics to read from the run's history. + if no keys are provided then all metrics will be returned. + page_size: the number of history records to read at a time. + min_step: The minimum step to start reading history from (inclusive). + max_step: The maximum step to read history up to (exclusive). + use_cache: When set to True, checks the WANDB_CACHE_DIR for a run history. + If the run history is not found in the cache, it will be downloaded from the server. + If set to False, the run history will be downloaded every time. + + Returns: + A BetaHistoryScan object, + which can be iterator over to get history records. + """ + beta_history_scan = public.BetaHistoryScan( + run=self, + service_api=self._service_api, + min_step=min_step, + max_step=max_step or self.lastHistoryStep + 1, + keys=keys, + page_size=page_size, + use_cache=use_cache, + ) + return beta_history_scan + + def download_history_exports( + self, + download_dir: pathlib.Path | str, + require_complete_history: bool = True, + ) -> runhistory.DownloadHistoryResult: + """Download any parquet history files for the run to the provided directory. + + Args: + download_dir: The directory to download the history files to. + require_complete_history: Whether to require the complete history to be downloaded. + If true, and the run contains data that has not been exported to parquet files yet, + an IncompleteRunHistoryError will be raised. + + Returns: + A DownloadHistoryResult. + + Raises: + IncompleteRunHistoryError: If require_complete_history is True + and the run contains data not yet exported to parquet files. + WandbApiFailedError: If the API request fails for reasons other than + incomplete history. + """ + init_download_request = apb.DownloadRunHistoryInit( + entity=self.entity, + project=self.project, + run_id=self.id, + download_dir=str(download_dir), + require_complete_history=require_complete_history, + ) + api_request = apb.ApiRequest( + read_run_history_request=apb.ReadRunHistoryRequest( + download_run_history_init=init_download_request, + ) + ) + + response: apb.ApiResponse + try: + response = self._service_api.send_api_request(api_request) + except WandbApiFailedError as e: + if ( + e.response is not None + and e.response.error_type == apb.ErrorType.INCOMPLETE_RUN_HISTORY_ERROR + ): + raise runhistory.IncompleteRunHistoryError() from None + else: + raise WandbApiFailedError("Failed to download history") from e + + contains_live_data = response.read_run_history_response.download_run_history_init.contains_live_data + request_id = ( + response.read_run_history_response.download_run_history_init.request_id + ) + return wandb_setup.singleton().asyncer.run( + lambda: runhistory.wait_for_download_with_progress( + self._service_api, + request_id, + contains_live_data, + ) + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/service_api.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/service_api.py new file mode 100644 index 0000000000000000000000000000000000000000..c8b8c31ed098ef73b713765e8bef6b10c8b7732c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/service_api.py @@ -0,0 +1,166 @@ +from __future__ import annotations + +import contextlib +import json +import logging +import uuid +import weakref +from collections.abc import Mapping +from typing import Any, cast + +from wandb.proto import wandb_internal_pb2 as pb +from wandb.proto.wandb_api_pb2 import ( + ApiRequest, + ApiResponse, + FeaturesRequest, + GraphQLRequest, +) +from wandb.sdk import wandb_settings, wandb_setup +from wandb.sdk.lib.service.service_connection import ( + ServiceConnection, + WandbApiFailedError, +) +from wandb.sdk.mailbox.mailbox_handle import MailboxHandle + +_logger = logging.getLogger(__name__) + + +def _cleanup(connection: ServiceConnection | None, api_id: str) -> None: + """Clean up the api resources associated with the api id.""" + if connection is not None: + with contextlib.suppress(Exception): + connection.api_cleanup_request(api_id) + + +class ServiceApi: + """A lazy initialized handle to the wandb-core service for handling API requests.""" + + def __init__( + self, + settings: wandb_settings.Settings, + ): + self._settings = settings + self._service_connection: ServiceConnection | None = None + self._api_id = str(uuid.uuid4()) + + def _get_service_connection(self) -> ServiceConnection: + """Connects to the service and initializes resources for handling API requests.""" + if self._service_connection is None: + self._service_connection = wandb_setup.singleton().ensure_service() + response = self._service_connection.api_init_request( + self._settings.to_proto(), + ) + self._api_id = response.api_id + + weakref.finalize( + self, + _cleanup, + self._service_connection, + self._api_id, + ) + + return self._service_connection + + def send_api_request( + self, + request: ApiRequest, + timeout: float | None = None, + ) -> ApiResponse: + """Send an API request to the backend service. + + Creates the backend service connection if it has not been created yet. + """ + conn = self._get_service_connection() + request.api_id = self._api_id + return conn.api_request(request, timeout=timeout) + + def execute_graphql( + self, + query: str, + variables: Mapping[str, Any] | None = None, + timeout: float | None = None, + ) -> Any: + """Execute a GraphQL operation through the wandb-core sidecar. + + The query is sent to wandb-core, which performs the network round-trip + against the W&B backend and returns the parsed `data` field of the + GraphQL response. + + Args: + query: The GraphQL document to execute. + variables: Variables for the GraphQL operation, JSON-serialized + on the wire. + timeout: Optional timeout in seconds for waiting on wandb-core. + On timeout, the request is cancelled on a best-effort basis. + + Returns: + The decoded `data` field of the GraphQL response. + + Raises: + WandbApiFailedError: The request failed for any reason, including + timeouts while waiting on wandb-core, transport errors, + non-successful HTTP status codes, and GraphQL `errors` + returned by the server. + """ + request = ApiRequest( + graphql_request=GraphQLRequest( + query=query, + variables_json=json.dumps(variables or {}), + ) + ) + response = self.send_api_request(request, timeout=timeout) + return json.loads(response.graphql_response.data_json) + + async def send_api_request_async( + self, + request: ApiRequest, + ) -> MailboxHandle[ApiResponse]: + """Send an API request to the backend service asynchronously. + + Args: + request: The Api request to send. + timeout: The timeout for the request. + """ + conn = self._get_service_connection() + request.api_id = self._api_id + return await conn.api_request_async(request) + + def feature_enabled( + self, + feature: pb.ServerFeature | str, + *, + timeout: float = 10, + ) -> bool: + """Returns whether a single server feature is enabled. + + On timeout or normal error, this logs and returns False. + + Args: + feature: The enum constant or name of the boolean feature to + check. Prefer to use the enum constants when possible, since + they have better type-checking. For unknown or incorrect names, + this returns False. + timeout: The timeout to use. Defaults to 10 seconds. + """ + if isinstance(feature, str): + try: + # NOTE: pb.ServerFeature is not an actual runtime type. + # + # All protobuf enums are represented as integers. + # It is guaranteed that the return value of Value + # is a valid enum (if it exists), hence the cast. + feature = cast(pb.ServerFeature, pb.ServerFeature.Value(feature)) + except ValueError: + # SERVER_FEATURE_UNSPECIFIED is always disabled. + return False + + req = ApiRequest(features_request=FeaturesRequest(features=[feature])) + + try: + resp = self.send_api_request(req, timeout=timeout) + except WandbApiFailedError: + # NOTE: The feature's integer value is logged here. + _logger.exception("Failed to load feature %s", feature) + return False + + return feature in resp.features_response.enabled diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/sweeps.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/sweeps.py new file mode 100644 index 0000000000000000000000000000000000000000..6a65fd05040cb5262d67b06cab7b4d5aa21973c5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/sweeps.py @@ -0,0 +1,545 @@ +"""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 collections.abc import Mapping +from typing import TYPE_CHECKING, Any, ClassVar + +from typing_extensions import override +from wandb_gql import gql +from wandb_graphql.language.ast import Document + +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.errors import Error +from wandb.sdk.lib import ipython + +if TYPE_CHECKING: + from wandb.apis._generated import GetSweeps + from wandb.apis.public.api import RetryingClient + from wandb.apis.public.runs import AgentRuns + from wandb.apis.public.service_api import ServiceApi + + +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: ClassVar[Document | None] = None + last_response: GetSweeps | None + + def __init__( + self, + client: RetryingClient, + entity: str, + project: str, + per_page: int = 50, + *, + service_api: ServiceApi, + ) -> Sweeps: + """An iterable collection of `Sweep` objects. + + Args: + client: Legacy GraphQL client retained for API compatibility. + service_api: Interface to the wandb-core service that performs + W&B API calls for this collection. + 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. + """ + if self.QUERY is None: + from wandb.apis._generated import GET_SWEEPS_GQL + + type(self).QUERY = gql(GET_SWEEPS_GQL) + + self.entity = entity + self.project = project + self._service_api = service_api + variables = {"project": self.project, "entity": self.entity} + super().__init__(client, variables, per_page) + + @override + def _update_response(self) -> None: + """Fetch and validate the response data for the current page.""" + from wandb.apis._generated import GetSweeps + + data = self.client.execute(self.QUERY, variable_values=self.variables) + self.last_response = GetSweeps.model_validate(data) + + @property + @override + def _length(self) -> int: + """The total number of sweeps in the project. + + + """ + if not self.last_response: + self._load_page() + + if not self.last_response or not self.last_response.project: + return 0 + + return self.last_response.project.total_sweeps + + @property + @override + def more(self) -> bool: + """Returns whether there are more sweeps to fetch. + + + """ + if ( + self.last_response + and self.last_response.project + and self.last_response.project.sweeps + and self.last_response.project.sweeps.page_info + ): + return self.last_response.project.sweeps.page_info.has_next_page + + return True + + @property + @override + def cursor(self) -> str | None: + """Returns the cursor for the next page of sweeps. + + + """ + if ( + self.last_response + and self.last_response.project + and self.last_response.project.sweeps + and self.last_response.project.sweeps.page_info + ): + return self.last_response.project.sweeps.page_info.end_cursor + + return None + + @override + def convert_objects(self) -> list[Sweep]: + """Converts the last GraphQL response into a list of `Sweep` objects. + + + """ + from wandb._pydantic import Connection + from wandb.apis._generated import SweepFragment + + if (rsp := self.last_response) is None or (project := rsp.project) is None: + msg = f"Could not find project {self.project!r}" + raise ValueError(msg) + + if project.total_sweeps < 1: + return [] + return [ + Sweep( + self.client, + self.entity, + self.project, + node.name, + service_api=self._service_api, + ) + for node in Connection[SweepFragment].model_validate(project.sweeps).nodes() + ] + + 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 + """ + + def __init__( + self, + client: RetryingClient, + entity: str, + project: str, + sweep_id: str, + attrs: Mapping[str, Any] | None = None, + *, + service_api: ServiceApi, + ): + # 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._service_api = service_api + self.runs = [] + + self.load(force=not attrs) + + @property + def entity(self) -> str: + """The entity associated with the sweep.""" + return self._entity + + @property + def username(self) -> str: + """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: + if not ( + sweep := self.get( + self.client, + self.entity, + self.project, + self.id, + service_api=self._service_api, + ) + ): + raise ValueError(f"Could not find sweep {self!r}") + 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, + service_api=self._service_api, + )[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(self.entity), + urllib.parse.quote_plus(self.project), + urllib.parse.quote_plus(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: Document | None = None, + *, + service_api: ServiceApi, + **kwargs, + ): + """Execute a query against the cloud backend. + + Args: + client: Legacy GraphQL client retained for API compatibility. + service_api: Interface to the wandb-core service that performs + W&B API calls for the returned sweep. + 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. + """ + from wandb.apis._generated import GET_SWEEP_GQL, GET_SWEEP_LEGACY_GQL + + if not order: + order = "+created_at" + + variables = {"entity": entity, "project": project, "name": sid, **kwargs} + if query is None: + query = gql(GET_SWEEP_GQL) + try: + data = client.execute(query, variable_values=variables) + except Exception: + # Don't handle exception, rely on legacy query + # TODO(gst): Implement updated introspection workaround + query = gql(GET_SWEEP_LEGACY_GQL) + data = client.execute(query, variable_values=variables) + + # FIXME: looks like this method allows passing arbitrary GQL queries, so for now + # we'll have to skip trying to validate the result with a generated pydantic model. + if not ( + data + and (proj_dict := data.get("project")) + and (sweep_dict := proj_dict.get("sweep")) + ): + return None + sweep = cls( + client, + entity, + project, + sid, + attrs=sweep_dict, + service_api=service_api, + ) + sweep.runs = public.Runs( + client, + entity, + project, + order=order, + per_page=10, + filters={"$and": [{"sweep": sweep.id}]}, + service_api=service_api, + ) + return sweep + + def _make_sweep_agent(self, attrs: Mapping[str, Any]) -> Agent: + """Construct `Agent` from API payload.""" + try: + return Agent( + self.client, + attrs=attrs, + entity=self.entity, + project=self.project, + sweep_id=self.id, + service_api=self._service_api, + ) + except ValueError as e: + raise Error( + "Sweep agent data from the W&B API was incomplete or invalid.", + context={"details": str(e)}, + ) from e + + def agent(self, agent_id: str) -> Agent: + """Query an agent by ID for this sweep. + + Args: + agent_id: The ID of the agent to look up. + """ + from wandb.apis._generated import GET_SWEEP_AGENT_GQL + + variables = { + "agentID": agent_id, + "sweep": self.id, + "entity": self.entity, + "project": self.project, + } + data = self.client.execute(gql(GET_SWEEP_AGENT_GQL), variable_values=variables) + return self._make_sweep_agent(data["project"]["sweep"]["agent"]) + + def agents(self) -> list[Agent]: + """Query the list of all agents for this sweep.""" + from wandb.apis._generated import GET_SWEEP_AGENTS_GQL, GetSweepAgents + + variables = { + "sweep": self.id, + "entity": self.entity, + "project": self.project, + } + data = self.client.execute(gql(GET_SWEEP_AGENTS_GQL), variable_values=variables) + parsed = GetSweepAgents.model_validate(data) + if not parsed.project or not parsed.project.sweep: + return [] + return [ + self._make_sweep_agent(edge.node.model_dump(by_alias=True)) + for edge in parsed.project.sweep.agents.edges + ] + + def to_html(self, height: int = 420, hidden: bool = False) -> str: + """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) -> str: + pathstr = "/".join(self.path) + state = self._attrs.get("state", "Unknown State") + return f"" + + +class Agent(Attrs): + def __init__( + self, + client: RetryingClient, + attrs: Mapping[str, Any], + entity: str, + project: str, + sweep_id: str, + *, + service_api: ServiceApi, + ) -> None: + super().__init__(dict(attrs or {})) + self._client = client + self._entity = entity + self._project = project + self._sweep_id = sweep_id + self._service_api = service_api + + if self._entity is None: + raise ValueError( + "Agent requires entity. " + "Use an Agent returned from sweep.agent(...) or sweep.agents()." + ) + if self._project is None: + raise ValueError( + "Agent requires project. " + "Use an Agent returned from sweep.agent(...) or sweep.agents()." + ) + if self._sweep_id is None: + raise ValueError( + "Agent requires sweep_id. " + "Use an Agent returned from sweep.agent(...) or sweep.agents()." + ) + if not (self._attrs.get("name") or self._attrs.get("id")): + if self._attrs.get("name") is None: + raise ValueError("Agent is missing name.") + if self._attrs.get("id") is None: + raise ValueError("Agent is missing id.") + raise ValueError("Agent is missing a usable name or id.") + self._agent_key: str = self._attrs.get("name") or self._attrs.get("id") + + def runs( + self, + per_page: int = 50, + ) -> AgentRuns: + """Return a paginated collection of runs executed by this agent.""" + from wandb.apis.public.runs import AgentRuns + + total_runs = int(self._attrs.get("totalRuns") or 0) + return AgentRuns( + self._client, + entity=self._entity, + project=self._project, + sweep_id=self._sweep_id, + agent_key=self._agent_key, + total_runs=total_runs, + order="+created_at", + per_page=per_page, + service_api=self._service_api, + ) + + def __repr__(self) -> str: + state = self._attrs.get("state", "Unknown State") + name = self._attrs.get("id", "Unknown") + return f"" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/teams.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/teams.py new file mode 100644 index 0000000000000000000000000000000000000000..fb2f5ab6041e5b6a917fec0ff1357078ac07762b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/teams.py @@ -0,0 +1,183 @@ +"""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 + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any + +from typing_extensions import Self +from wandb_gql import gql + +from wandb.apis.attrs import Attrs + +if TYPE_CHECKING: + from .api import Api, RetryingClient + + +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 + """ + + def __init__(self, client: RetryingClient, team: str, attrs: Mapping[str, Any]): + super().__init__(attrs) + self._client = client + self.team = team + + def delete(self): + """Remove a member from a team. + + Returns: + Boolean indicating success + """ + from requests import HTTPError + + from wandb.apis._generated import DELETE_INVITE_GQL, DeleteInvite + + try: + data = self._client.execute( + gql(DELETE_INVITE_GQL), {"id": self.id, "entity": self.team} + ) + except HTTPError: + return False + else: + result = DeleteInvite.model_validate(data).result + return (result is not None) and result.success + + 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. + """ + + def __init__( + self, + client: RetryingClient, + name: str, + attrs: Mapping[str, Any] | None = None, + ): + super().__init__(attrs or {}) + self._client = client + self.name = name + self.load() + + @classmethod + def create(cls, api: Api, team: str, admin_username: str | None = None) -> Self: + """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 + """ + from requests import HTTPError + + from wandb.apis._generated import CREATE_TEAM_GQL + + try: + api.client.execute( + gql(CREATE_TEAM_GQL), + {"teamName": team, "teamAdminUserName": admin_username}, + ) + except HTTPError: + pass + return cls(api.client, team) + + def invite(self, username_or_email: str, admin: bool = False) -> bool: + """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. + """ + from requests import HTTPError + + from wandb.apis._generated import CREATE_INVITE_GQL + + variables = { + "entity": self.name, + "admin": admin, + ("email" if ("@" in username_or_email) else "username"): username_or_email, + } + try: + self._client.execute(gql(CREATE_INVITE_GQL), variables) + except HTTPError: + return False + return True + + def create_service_account(self, description: str) -> Member | None: + """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 + """ + from requests import HTTPError + + from wandb.apis._generated import CREATE_SERVICE_ACCOUNT_GQL + + try: + self._client.execute( + gql(CREATE_SERVICE_ACCOUNT_GQL), + {"entity": self.name, "description": description}, + ) + self.load(True) + return self.members[-1] + except HTTPError: + return None + + def load(self, force: bool = False) -> dict[str, Any]: + """Return members that belong to a team. + + + """ + from wandb.apis._generated import GET_TEAM_ENTITY_GQL, GetTeamEntity + + if force or not self._attrs: + data = self._client.execute(gql(GET_TEAM_ENTITY_GQL), {"name": self.name}) + result = GetTeamEntity.model_validate(data) + self._attrs = entity.model_dump() if (entity := result.entity) else {} + self._attrs["members"] = [ + Member(self._client, self.name, member) + for member in self._attrs["members"] + ] + return self._attrs + + def __repr__(self) -> str: + return f"" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/users.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/users.py new file mode 100644 index 0000000000000000000000000000000000000000..a812ece3105c450306dd1d5a61747bbaae1949a2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/users.py @@ -0,0 +1,169 @@ +"""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 + +from collections.abc import MutableMapping +from typing import TYPE_CHECKING, Any + +from typing_extensions import Self +from wandb_gql import gql + +import wandb +from wandb.apis.attrs import Attrs + +if TYPE_CHECKING: + from .api import Api, RetryingClient + + +class User(Attrs): + """A user on a W&B instance. + + This allows managing a user's API keys and accessing information like + team memberships. The `create` class method can be used to create a new + user. + + Args: + client: The GraphQL client to use for network operations. + attrs: A subset of the User type in the GraphQL schema. + + + """ + + def __init__( + self, + client: RetryingClient, + attrs: MutableMapping[str, Any], + api_key: str | None = None, + ): + super().__init__(attrs) + self._client = client + self._api_key = api_key + self._user_api: Api | None = None + + @property + def user_api(self) -> Api | None: + """A `wandb.Api` instance using the user's credentials.""" + if self._user_api is None and self._api_key: + self._user_api = wandb.Api(api_key=self._api_key) + return self._user_api + + @classmethod + def create(cls, api: Api, email: str, admin: bool = False) -> Self: + """Create a new user. + + This is an internal method. Use the `create_user()` method of + `wandb.Api` instead. + + Args: + api: The API instance to use to create the user. + email: The email for the user. + admin: Whether this user should be a global instance admin. + + Returns: + A `User` object. + + + """ + from wandb.apis._generated import ( + CREATE_USER_FROM_ADMIN_GQL, + CreateUserFromAdmin, + ) + + gql_op = gql(CREATE_USER_FROM_ADMIN_GQL) + data = api.client.execute(gql_op, {"email": email, "admin": admin}) + user = CreateUserFromAdmin.model_validate(data).result.user + return cls(api.client, user.model_dump(), api_key=api.api_key) + + @property + def api_keys(self) -> list[str]: + """Names of the user's API keys. + + This property returns the names of the the API keys, *not* the secret + associated with the key. The name of the key cannot be used as an API + key. + + The list is empty if the user has no API keys or if API keys have not + 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[str]: + """Names of the user's teams. + + This is an empty list if the user has no team memberships or if teams + data was not 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: str) -> bool: + """Delete a user's API key. + + Only the owner of the key or an admin can delete it. + + Args: + api_key: The name of the API key to delete. Use one of + the names returned by the `api_keys` property. + + Returns: + True on success, false on failure. + """ + from requests import HTTPError + + from wandb.apis._generated import DELETE_API_KEY_GQL + + idx = self.api_keys.index(api_key) + api_key_id = self._attrs["apiKeys"]["edges"][idx]["node"]["id"] + try: + self._client.execute(gql(DELETE_API_KEY_GQL), {"id": api_key_id}) + except HTTPError: + return False + return True + + def generate_api_key(self, description: str | None = None) -> str | None: + """Generate a new API key. + + Args: + description: A description for the new API key. This can be + used to identify the purpose of the API key. + + Returns: + The generated API key (the full secret, not just the name), or + None on failure. + """ + from requests import HTTPError + + from wandb.apis._generated import GENERATE_API_KEY_GQL, GenerateApiKey + + try: + # We must make this call using credentials from the original user + gql_op = gql(GENERATE_API_KEY_GQL) + data = self._client.execute(gql_op, {"description": description}) + key_fragment = GenerateApiKey.model_validate(data).result.api_key + self._attrs["apiKeys"]["edges"].append({"node": key_fragment.model_dump()}) + except (HTTPError, AttributeError): + return None + else: + return key_fragment.name + + def __repr__(self) -> str: + if email := self._attrs.get("email"): + return f"" + if username := self._attrs.get("username"): + return f"" + if id_ := self._attrs.get("id"): + return f"" + if name := self._attrs.get("name"): + return f"" + return "" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6300710a1ccb7c01d14d83c56c814c0bd255f704 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/public/utils.py @@ -0,0 +1,236 @@ +from __future__ import annotations + +import re +from collections.abc import Iterable, Mapping +from enum import Enum +from typing import Any +from urllib.parse import urlparse + +from wandb_gql import gql +from wandb_graphql import TypeInfo +from wandb_graphql.language import ast, visitor +from wandb_graphql.validation.validation import ValidationContext + +from wandb._iterutils import one +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. + """ + from wandb.sdk.artifacts._validators import is_artifact_registry_project + + 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.""" + + 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 leave_Document(self, node: ast.Document, *_, **__) -> Any: # noqa: N802 + # After rewriting the GQL document, prune "orphan" (unused) fragment definitions. + # Note: The ValidationContext doesn't require a schema here, as we only use it to check for reachable fragments. + ctx = ValidationContext(schema=None, ast=node, type_info=TypeInfo(schema=None)) + operation_defns = { + dfn for dfn in node.definitions if isinstance(dfn, ast.OperationDefinition) + } + used_fragment_defns = { + frag + for op in operation_defns + for frag in ctx.get_recursively_referenced_fragments(op) + } + # Preserve original defintion order + allowed_defns = operation_defns | used_fragment_defns + node.definitions = [dfn for dfn in node.definitions if (dfn in allowed_defns)] + + def enter_Variable(self, node: ast.Variable, *_, **__) -> Any: # noqa: N802 + if node.name.value in self.omit_variables: + return visitor.REMOVE + + def leave_VariableDefinition(self, node: ast.VariableDefinition, *_, **__) -> Any: # noqa: N802 + # For context, consider the `$varName: String` variable definition below: + # (..., $varName: String, ...) + # + # On ENTERING, the AST looks like: + # VariableDefinition(variable=Variable(name=Name(value='varName')), ...) + # + # On LEAVING, if `$varName` was removed, the AST looks like: + # VariableDefinition(variable=REMOVE, ...) + if node.variable is visitor.REMOVE: + return visitor.REMOVE + + def leave_ObjectField(self, node: ast.ObjectField, *_, **__) -> Any: # noqa: N802 + # For context, consider `argName: $varName` in the input args below: + # input: {..., argName: $varName, ...} + # + # On ENTERING, the AST for `argName: $varName` looks like: + # ObjectField( + # name=Name(value='argName'), value=Variable(name=Name(value='varName')), + # ) + # + # On LEAVING, if `$varName` was removed, the AST looks like: + # ObjectField( + # name=Name(value='argName'), value=REMOVE, + # ) + if node.value is visitor.REMOVE: + 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 + + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/reports/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/reports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6d2b9ad9385524f2b868e498d3030de028fac546 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/reports/__init__.py @@ -0,0 +1 @@ +from .v2 import * # noqa: F403 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/reports/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/reports/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50236b0e2753f85af096a05584bfa5a37ada4ad1 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/reports/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/reports/v1/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/reports/v1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0bd41baac9f44dd1f7dc5145779d33fe95d10763 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/reports/v1/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/reports/v1/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13bb5c44d5a0e79215b99ce767da4633fd6c7031 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/reports/v1/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/reports/v2/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/reports/v2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..532129620940c7deb87ae483a08059cb792d15f4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/reports/v2/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/reports/v2/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7994e1aad64c6b5483d5eeea105fa022e0f03fe3 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/reports/v2/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/workspaces/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/workspaces/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..269a35473d08b01200c593d2c8958c85349a0749 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/workspaces/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/workspaces/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a273fb2e55eadfc8d343b75a6b002eec3a48c3f Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/apis/workspaces/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e2294c09b17fb075c882bed029d68b4667e1e39e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/__init__.py @@ -0,0 +1,50 @@ +from .actions import ActionType, DoNothing, SendNotification, SendWebhook +from .automations import Automation, NewAutomation +from .events import ( + ArtifactEvent, + EventType, + MetricChangeFilter, + MetricThresholdFilter, + MetricZScoreFilter, + OnAddArtifactAlias, + OnCreateArtifact, + OnLinkArtifact, + OnRunMetric, + OnRunState, + RunEvent, + RunStateFilter, +) +from .integrations import Integration, SlackIntegration, WebhookIntegration +from .scopes import ArtifactCollectionScope, ProjectScope, ScopeType + +__all__ = [ + # Scopes + "ScopeType", # doc:exclude + "ArtifactCollectionScope", # doc:exclude + "ProjectScope", # doc:exclude + # Events + "EventType", # doc:exclude + "OnAddArtifactAlias", + "OnCreateArtifact", + "OnLinkArtifact", + "OnRunMetric", + "OnRunState", + "ArtifactEvent", # doc:exclude + "RunEvent", # doc:exclude + "MetricThresholdFilter", + "MetricChangeFilter", + "RunStateFilter", + "MetricZScoreFilter", + # Actions + "ActionType", # doc:exclude + "SendNotification", + "SendWebhook", + "DoNothing", + # Automations + "Automation", + "NewAutomation", + # Integrations + "Integration", # doc:exclude + "SlackIntegration", # doc:exclude + "WebhookIntegration", # doc:exclude +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/_utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7132dc4aa13b896eee76548e900f27bc088dc035 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/_utils.py @@ -0,0 +1,288 @@ +from __future__ import annotations + +from collections.abc import Collection +from typing import Annotated, Any, Final, Optional, Protocol, TypedDict, Union + +from pydantic import Field +from typing_extensions import Self, Unpack + +from wandb._pydantic import GQLId, GQLInput, computed_field, model_validator, to_json + +from ._filters import MongoLikeFilter +from ._generated import ( + CreateFilterTriggerInput, + QueueJobActionInput, + TriggeredActionConfig, + UpdateFilterTriggerInput, +) +from ._validators import parse_input_action +from .actions import ( + ActionType, + DoNothing, + InputAction, + SavedAction, + SendNotification, + SendWebhook, +) +from .automations import Automation, NewAutomation +from .events import ( + EventType, + InputEvent, + RunMetricFilter, + RunStateFilter, + SavedEvent, + _WrappedSavedEventFilter, +) +from .scopes import AutomationScope, ScopeType + +INVALID_INPUT_EVENTS: Final[Collection[EventType]] = (EventType.UPDATE_ARTIFACT_ALIAS,) +"""Event types that should NOT be allowed as new values on new or edited automations. + +While we forbid new/edited automations from assigning these event types, +they're defined so that we can still parse existing automations that may use them. +""" + +INVALID_INPUT_ACTIONS: Final[Collection[ActionType]] = (ActionType.QUEUE_JOB,) +"""Action types that should NOT be allowed as new values on new or edited automations. + +While we forbid new/edited automations from assigning these action types, +they're defined so that we can still parse existing automations that may use them. +""" + +ALWAYS_SUPPORTED_EVENTS: Final[Collection[EventType]] = frozenset( + { + EventType.CREATE_ARTIFACT, + EventType.LINK_ARTIFACT, + EventType.ADD_ARTIFACT_ALIAS, + } +) +"""Event types that should be supported by all current, non-EOL server versions.""" + +ALWAYS_SUPPORTED_ACTIONS: Final[Collection[ActionType]] = frozenset( + { + ActionType.NOTIFICATION, + ActionType.GENERIC_WEBHOOK, + } +) +"""Action types that should be supported by all current, non-EOL server versions.""" + + +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): + """Prepares action configuration data 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]: + """Nests the action input under the correct key for `TriggeredActionConfig`. + + This is necessary to conform to the schemas for: + - `CreateFilterTriggerInput` + - `UpdateFilterTriggerInput` + """ + # Delegate to inner validators to convert SavedAction -> InputAction types, if needed. + obj = parse_input_action(obj) + return InputActionConfig(**{ACTION_CONFIG_KEYS[obj.action_type]: obj}).model_dump() + + +def prepare_event_filter_input( + obj: _WrappedSavedEventFilter | MongoLikeFilter | RunMetricFilter | RunStateFilter, +) -> str: + """Unnests (if needed) and serializes an `EventFilter` input 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. + if isinstance(obj, _WrappedSavedEventFilter): + return to_json(obj.filter) + return to_json(obj) + + +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(GQLInput, 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 INVALID_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 INVALID_INPUT_ACTIONS: + raise ValueError(f"{type_!r} actions cannot be assigned to automations.") + return self + + +class ValidatedUpdateInput(GQLInput, extra="ignore", frozen=True): + """Validated automation parameters, prepared for updating an existing automation. + + Accepts both InputEvent/InputAction (user-supplied for the update) and + SavedEvent/SavedAction (carried over from the existing saved automation). + This avoids the coercion bug where routing through Automation(event: SavedEvent) + silently drops InputEvent filters. + + Uses extra="ignore" (rather than "forbid") because dict(Automation) includes + fields like typename__, created_at, updated_at that are not relevant for the + update payload. + """ + + id: GQLId + + name: Optional[str] = None + description: Optional[str] = None + enabled: Optional[bool] = None + + event: Annotated[Union[InputEvent, SavedEvent], Field(exclude=True)] + action: Annotated[Union[InputAction, SavedAction], Field(exclude=True)] + scope: Annotated[AutomationScope, Field(exclude=True)] + + # -------------------------------------------------------------------------- + # Derived fields to match the input schemas + @computed_field + def scope_type(self) -> ScopeType: + return self.scope.scope_type + + @computed_field + def scope_id(self) -> GQLId: + return self.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 INVALID_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 INVALID_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 + obj_dict = {**obj.model_dump(), **kwargs} if obj else kwargs # type: ignore[typeddict-item] + vobj = ValidatedCreateInput(**obj_dict) + return CreateFilterTriggerInput.model_validate(vobj) + + +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 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 + obj_dict = dict(obj or {}) | kwargs + vobj = ValidatedUpdateInput(**obj_dict) + return UpdateFilterTriggerInput.model_validate(vobj) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/_validators.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/_validators.py new file mode 100644 index 0000000000000000000000000000000000000000..d195edc941f165f6ebb3e848e360b9554cfe8cfa --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/_validators.py @@ -0,0 +1,144 @@ +from __future__ import annotations + +from enum import Enum +from typing import Annotated, Any, TypeVar + +from pydantic import BeforeValidator, Json, PlainSerializer +from pydantic_core import PydanticUseDefault + +from wandb._pydantic import to_json + +from ._filters import And, MongoLikeFilter, Or +from ._filters.filterutils import simplify_expr + +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) + + +JsonEncoded = Annotated[Json[T], BeforeValidator(ensure_json), PlainSerializer(to_json)] +"""A Pydantic type that's always serialized to a JSON string. + +Unlike `pydantic.Json[T]`, this is more lenient on validation and instantiation. +It doesn't strictly require the incoming value to be an encoded JSON string, and +accepts values that may _already_ be deserialized from JSON (e.g. a dict). +""" + + +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"-mode field validator that coerces `None` to the field default. + + See: 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 parse_scope(v: Any) -> Any: + """Convert eligible objects (including 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.model_validate(v) + if isinstance(v, ArtifactCollection): + typ = _ArtifactSequenceScope if v.is_sequence() else _ArtifactPortfolioScope + return typ.model_validate(v) + return v + + +def parse_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() + ) + if isinstance(v, SendWebhook): + return SavedWebhookAction( + integration={"id": v.integration_id}, **v.model_dump() + ) + if isinstance(v, DoNothing): + return SavedNoOpAction(**v.model_dump()) + return v + + +def parse_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()) + if isinstance(v, SavedWebhookAction): + return SendWebhook(integration_id=v.integration.id, **v.model_dump()) + if isinstance(v, SavedNoOpAction): + return DoNothing(**v.model_dump()) + return v + + +# ---------------------------------------------------------------------------- +def wrap_run_event_run_filter(f: MongoLikeFilter) -> MongoLikeFilter: + """Wrap a run filter in an `And` operator if it's not already. + + This is a necessary constraint imposed elsewhere by backend/frontend code. + """ + return And.wrap(simplify_expr(f)) # simplify/flatten first if needed + + +def wrap_mutation_event_filter(f: MongoLikeFilter) -> MongoLikeFilter: + """Wrap filters as `{"$or": [{"$and": []}]}`. + + This awkward format is necessary because the frontend expects it. + """ + return Or.wrap(And.wrap(simplify_expr(f))) # simplify/flatten first if needed diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/actions.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/actions.py new file mode 100644 index 0000000000000000000000000000000000000000..3442b043f7280841fdb97f95e6f06209027a8833 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/actions.py @@ -0,0 +1,232 @@ +"""Actions that are triggered by W&B Automations.""" + +from __future__ import annotations + +from typing import Annotated, Any, Literal, Optional, Union + +from pydantic import BeforeValidator, Field +from typing_extensions import Self, TypeVar, get_args + +from wandb._pydantic import GQLBase, GQLId +from wandb._strutils import nameof + +from ._generated import ( + AlertSeverity, + GenericWebhookActionFields, + GenericWebhookActionInput, + NoOpActionFields, + NoOpTriggeredActionInput, + NotificationActionFields, + NotificationActionInput, + QueueJobActionFields, +) +from ._validators import ( + JsonEncoded, + LenientStrEnum, + default_if_none, + parse_input_action, + parse_saved_action, + upper_if_str, +) +from .integrations import SlackIntegration, WebhookIntegration + +T = TypeVar("T") + + +# 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 _SlackIntegrationStub(GQLBase): + typename__: Annotated[ + Literal["SlackIntegration"], + Field(alias="__typename", frozen=True, repr=False), + ] = "SlackIntegration" + id: GQLId + + +class _WebhookIntegrationStub(GQLBase): + typename__: Annotated[ + Literal["GenericWebhookIntegration"], + Field(alias="__typename", frozen=True, repr=False), + ] = "GenericWebhookIntegration" + id: GQLId + + +class SavedNotificationAction(NotificationActionFields, frozen=False): + action_type: Literal[ActionType.NOTIFICATION] = ActionType.NOTIFICATION + # Narrowed from the generated parent's broader union: saved actions + # always come back tagged with the SlackIntegration stub typename. + integration: _SlackIntegrationStub # type: ignore[assignment] + + title: Optional[str] + message: Optional[str] + severity: Optional[AlertSeverity] + + +class SavedWebhookAction(GenericWebhookActionFields, frozen=False): + action_type: Literal[ActionType.GENERIC_WEBHOOK] = ActionType.GENERIC_WEBHOOK + # Narrowed from the generated parent's broader union: saved actions + # always come back tagged with the GenericWebhookIntegration stub typename. + integration: _WebhookIntegrationStub # type: ignore[assignment] + + # 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: Optional[JsonEncoded[dict[str, Any]]] = None # type: ignore[assignment] + + +class SavedNoOpAction(NoOpActionFields, frozen=False): + action_type: Literal[ActionType.NO_OP] = ActionType.NO_OP + + no_op: Annotated[ + bool, + BeforeValidator(default_if_none), + Field(repr=False, frozen=True), + ] = 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(parse_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 preserve continuity with the 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[JsonEncoded[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[JsonEncoded[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(parse_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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/automations.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/automations.py new file mode 100644 index 0000000000000000000000000000000000000000..a8457519a407058a1d23c2050a7e9df5175a94d0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/automations.py @@ -0,0 +1,85 @@ +from __future__ import annotations + +from datetime import datetime +from typing import Annotated, Optional + +from pydantic import Field + +from wandb._pydantic import GQLId, GQLInput + +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 while allowing +# local editing. +class Automation(TriggerFields, frozen=False): + """A local instance of a saved W&B automation that supports editing.""" + + 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(GQLInput, 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/events.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/events.py new file mode 100644 index 0000000000000000000000000000000000000000..8fe0e07967d16d3033cf48629afa8fdf3262779f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/events.py @@ -0,0 +1,438 @@ +"""Events that trigger W&B Automations.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Annotated, Any, Literal, Optional, Union + +from pydantic import AfterValidator, Field +from typing_extensions import get_args + +from wandb._pydantic import GQLBase, model_validator, pydantic_isinstance +from wandb._strutils import nameof + +from ._filters import And, MongoLikeFilter +from ._filters.expressions import FilterableField +from ._filters.run_metrics import ( + MetricChangeFilter, + MetricThresholdFilter, + MetricVal, + MetricZScoreFilter, +) +from ._filters.run_states import StateFilter, StateOperand +from ._generated import FilterEventFields +from ._validators import ( + JsonEncoded, + LenientStrEnum, + ensure_json, + wrap_mutation_event_filter, + wrap_run_event_run_filter, +) +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" + RUN_STATE = "RUN_STATE" + RUN_METRIC_ZSCORE = "RUN_METRIC_ZSCORE" + + +# ------------------------------------------------------------------------------ +# 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: JsonEncoded[MongoLikeFilter] = And() + + +class _WrappedMetricThresholdFilter(GQLBase): # from: RunMetricFilter + event_type: Annotated[ + Literal[EventType.RUN_METRIC_THRESHOLD], + Field(exclude=True, repr=False), + ] = EventType.RUN_METRIC_THRESHOLD + + threshold_filter: MetricThresholdFilter + + @model_validator(mode="before") + @classmethod + def _nest_inner_filter(cls, v: Any) -> Any: + # Yeah, we've got a lot of nesting due to backend schema constraints. + if pydantic_isinstance(v, MetricThresholdFilter): + return cls(threshold_filter=v) + return v + + +class _WrappedMetricChangeFilter(GQLBase): # from: RunMetricFilter + event_type: Annotated[ + Literal[EventType.RUN_METRIC_CHANGE], + Field(exclude=True, repr=False), + ] = EventType.RUN_METRIC_CHANGE + + change_filter: MetricChangeFilter + + @model_validator(mode="before") + @classmethod + def _nest_inner_filter(cls, v: Any) -> Any: + # Yeah, we've got a lot of nesting due to backend schema constraints. + if pydantic_isinstance(v, MetricChangeFilter): + return cls(change_filter=v) + return v + + +class _WrappedMetricZScoreFilter(GQLBase): # from: RunMetricFilter + event_type: Annotated[ + Literal[EventType.RUN_METRIC_ZSCORE], + Field(exclude=True, repr=False), + ] = EventType.RUN_METRIC_ZSCORE + + zscore_filter: MetricZScoreFilter + + @model_validator(mode="before") + @classmethod + def _nest_inner_filter(cls, v: Any) -> Any: + if pydantic_isinstance(v, MetricZScoreFilter): + return cls(zscore_filter=v) + return v + + +class RunMetricFilter(GQLBase): # from: TriggeringRunMetricEvent + run: Annotated[ + JsonEncoded[MongoLikeFilter], + AfterValidator(wrap_run_event_run_filter), + Field(alias="run_filter"), + ] = And() + """Filters that must match any runs that will trigger this event.""" + + metric: Annotated[ + Union[ + _WrappedMetricThresholdFilter, + _WrappedMetricChangeFilter, + _WrappedMetricZScoreFilter, + ], + Field(alias="run_metric_filter"), + ] + """Metric condition(s) that must be satisfied for this event to trigger.""" + + # ------------------------------------------------------------------------------ + legacy_metric_filter: Annotated[ + Optional[JsonEncoded[MetricThresholdFilter]], + Field(alias="metric_filter", deprecated=True), + ] = None + """Deprecated legacy field for defining run metric threshold events. + + For new automations, use the `metric` field (JSON alias `run_metric_filter`). + """ + + @model_validator(mode="before") + @classmethod + def _nest_metric_filter(cls, v: Any) -> Any: + # If no run filter is given, automatically nest the metric filter and + # let inner validators reshape further as needed. + if pydantic_isinstance( + v, (MetricThresholdFilter, MetricChangeFilter, MetricZScoreFilter) + ): + return cls(metric=v) + return v + + +class RunStateFilter(GQLBase): # from: TriggeringRunStateEvent + """Represents a filter for triggering events based on changes in run states.""" + + run: Annotated[ + JsonEncoded[MongoLikeFilter], + AfterValidator(wrap_run_event_run_filter), + Field(alias="run_filter"), + ] = And() + """Filters that must match any runs that will trigger this event.""" + + state: Annotated[StateFilter, Field(alias="run_state_filter")] + """Run state condition(s) that must be satisfied for this event to trigger.""" + + @model_validator(mode="before") + @classmethod + def _nest_state_filter(cls, v: Any) -> Any: + # If no run filter is given, automatically nest the state filter and + # let inner validators reshape further as needed. + if pydantic_isinstance(v, StateFilter): + return cls(state=v) + return v + + +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: JsonEncoded[ # type: ignore[assignment] + Union[_WrappedSavedEventFilter, RunMetricFilter, RunStateFilter] + ] + """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` in GQL responses for saved automations. +class _BaseEventInput(GQLBase): + event_type: EventType + + scope: AutomationScope + """The scope of the event.""" + + filter: JsonEncoded[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: + """Implement `event >> action` to define an automation.""" + return self.then(other) + + +# ------------------------------------------------------------------------------ +# Events that trigger on specific mutations in the backend +class _BaseMutationEventInput(_BaseEventInput): + filter: Annotated[ + JsonEncoded[MongoLikeFilter], + AfterValidator(wrap_mutation_event_filter), + ] = And() + """Additional conditions(s), if any, that are required for this event to trigger.""" + + +class OnLinkArtifact(_BaseMutationEventInput): + """A new artifact is linked to a collection. + + Examples: + Define an event that triggers when an artifact is linked to the + collection "my-collection" with the alias "prod": + + ```python + from wandb import Api + from wandb.automations import OnLinkArtifact, ArtifactEvent + + api = Api() + collection = api.artifact_collection(name="my-collection", type_name="model") + + event = OnLinkArtifact( + scope=collection, + filter=ArtifactEvent.alias.eq("prod"), + ) + ``` + """ + + event_type: Literal[EventType.LINK_ARTIFACT] = EventType.LINK_ARTIFACT + + +class OnAddArtifactAlias(_BaseMutationEventInput): + """A new alias is assigned to an artifact. + + Examples: + Define an event that triggers whenever the alias "prod" is assigned to + any artifact in the collection "my-collection": + + ```python + from wandb import Api + from wandb.automations import OnAddArtifactAlias, ArtifactEvent + + api = Api() + collection = api.artifact_collection(name="my-collection", type_name="model") + + event = OnAddArtifactAlias( + scope=collection, + filter=ArtifactEvent.alias.eq("prod"), + ) + ``` + """ + + event_type: Literal[EventType.ADD_ARTIFACT_ALIAS] = EventType.ADD_ARTIFACT_ALIAS + + +class OnCreateArtifact(_BaseMutationEventInput): + """A new artifact is created. + + Examples: + Define an event that triggers when a new artifact is created in the + collection "my-collection": + + ```python + from wandb import Api + from wandb.automations import OnCreateArtifact + + api = Api() + collection = api.artifact_collection(name="my-collection", type_name="model") + + event = OnCreateArtifact(scope=collection) + ``` + """ + + event_type: Literal[EventType.CREATE_ARTIFACT] = EventType.CREATE_ARTIFACT + + scope: ArtifactCollectionScope + """The scope of the event: must be an artifact collection.""" + + +# ------------------------------------------------------------------------------ +# Events that trigger on run conditions +class _BaseRunEventInput(_BaseEventInput): + scope: ProjectScope + """The scope of the event: must be a project.""" + + +class OnRunMetric(_BaseRunEventInput): + """A run metric satisfies a user-defined condition. + + Examples: + Define an event that triggers for any run in project "my-project" when + the average of the last 5 values of metric "my-metric" exceeds 123.45: + + ```python + from wandb import Api + from wandb.automations import OnRunMetric, RunEvent + + api = Api() + project = api.project(name="my-project") + + event = OnRunMetric( + scope=project, + filter=RunEvent.metric("my-metric").avg(5).gt(123.45), + ) + ``` + """ + + event_type: Literal[ + EventType.RUN_METRIC_THRESHOLD, + EventType.RUN_METRIC_CHANGE, + EventType.RUN_METRIC_ZSCORE, + ] + + filter: JsonEncoded[RunMetricFilter] + """Run and/or metric condition(s) that must be satisfied for this event to trigger.""" + + @model_validator(mode="before") + @classmethod + def _infer_event_type(cls, data: Any) -> Any: + """Infer the event type from the inner filter during validation. + + This supports both "threshold" and "change" metric filters, which 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 + + +class OnRunState(_BaseRunEventInput): + """A run state changes. + + Examples: + Define an event that triggers for any run in project "my-project" when + its state changes to "finished" (i.e. succeeded) or "failed": + + ```python + from wandb import Api + from wandb.automations import OnRunState + + api = Api() + project = api.project(name="my-project") + + event = OnRunState( + scope=project, + filter=RunEvent.state.in_(["finished", "failed"]), + ) + ``` + """ + + event_type: Literal[EventType.RUN_STATE] = EventType.RUN_STATE + + filter: JsonEncoded[RunStateFilter] + """Run state condition(s) that must be satisfied for this event to trigger.""" + + +# for type annotations +InputEvent = Annotated[ + Union[ + OnLinkArtifact, + OnAddArtifactAlias, + OnCreateArtifact, + OnRunMetric, + OnRunState, + ], + 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. + + state = StateOperand() + + @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", + "MetricZScoreFilter", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/integrations.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/integrations.py new file mode 100644 index 0000000000000000000000000000000000000000..2f56f91dd4f2d0979e7727c925dbdc4e39b4cd74 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/integrations.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from typing import Annotated, Union + +from pydantic import Field, TypeAdapter + +from ._generated import SlackIntegrationFields, WebhookIntegrationFields + + +class SlackIntegration(SlackIntegrationFields): + team_name: str + """Slack workspace (not W&B team) where this integration will post messages.""" + + channel_name: str + """Slack channel where this integration will post messages.""" + + +class WebhookIntegration(WebhookIntegrationFields): + 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__"), +] + +# INTERNAL USE ONLY: For parsing integrations from paginated responses +IntegrationAdapter: TypeAdapter[Integration] = TypeAdapter(Integration) + + +__all__ = [ + "Integration", + "SlackIntegration", + "WebhookIntegration", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/scopes.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/scopes.py new file mode 100644 index 0000000000000000000000000000000000000000..ed0b607f8a0120f2a79a5984f696fafade3d43df --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/automations/scopes.py @@ -0,0 +1,77 @@ +"""Scopes in which a W&B Automation can be triggered.""" + +from __future__ import annotations + +from typing import Annotated, Literal, Union + +from pydantic import BeforeValidator, Field +from typing_extensions import TypeAlias, get_args + +from wandb._pydantic import GQLBase + +from ._generated import ( + ArtifactPortfolioScopeFields, + ArtifactSequenceScopeFields, + ProjectScopeFields, +) +from ._validators import LenientStrEnum, parse_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): + """Automation scope defined by an `ArtifactPortfolio` (e.g. a registry collection).""" + + scope_type: Literal[ScopeType.ARTIFACT_COLLECTION] = ScopeType.ARTIFACT_COLLECTION + + +# for type annotations +ArtifactCollectionScope = Annotated[ + Union[_ArtifactSequenceScope, _ArtifactPortfolioScope], + BeforeValidator(parse_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(parse_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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/cli/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/cli/beta.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/cli/beta.py new file mode 100644 index 0000000000000000000000000000000000000000..1dd94309b2792cb2367536d2b84acdadf4e9d27d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/cli/beta.py @@ -0,0 +1,315 @@ +"""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 +from typing import Any + +import click + +from wandb.analytics import get_sentry +from wandb.errors import WandbCoreNotAvailableError +from wandb.util import get_core_path + + +class DefaultCommandGroup(click.Group): + """A click Group that falls through to a default command. + + If the first argument isn't a recognized subcommand, the default + command is invoked with all arguments passed through. This allows + backward-compatible CLIs where `cmd [path]` and `cmd run [path]` + are equivalent. + """ + + def __init__(self, *args: Any, default_cmd: str = "run", **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.default_cmd = default_cmd + + def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]: + if not args or args[0].startswith("-") or args[0] not in self.commands: + args = [self.default_cmd, *args] + return super().parse_args(ctx, args) + + def format_usage(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: + formatter.write_usage(ctx.command_path, "[PATH] | COMMAND [ARGS]...") + + +@click.group() +def beta() -> None: + """Beta versions of wandb CLI commands. + + These commands may change or even completely break in any release of wandb. + """ + get_sentry().configure_scope(process_context="wandb_beta") + try: + get_core_path() + except WandbCoreNotAvailableError as e: + get_sentry().exception(f"using `wandb beta`. failed with {e}") + click.secho( + (e), + fg="red", + err=True, + ) + + +@beta.group(cls=DefaultCommandGroup, default_cmd="run", invoke_without_command=True) +@click.pass_context +def leet(ctx: click.Context) -> None: + """W&B LEET: the Lightweight Experiment Exploration Tool. + + A terminal UI for viewing your W&B runs locally. + + Examples: + wandb beta leet View latest run + wandb beta leet ./wandb View runs in directory + wandb beta leet symon View live local system metrics + """ + pass + + +@leet.command() +@click.argument("path", nargs=1, type=click.STRING, required=False) +@click.option( + "--pprof", + default="", + hidden=True, + help="Serve /debug/pprof/* on this address (e.g. 127.0.0.1:6060).", +) +@click.help_option("-h", "--help") +def run(path: str | None = None, pprof: str = "") -> None: + """Launch the LEET TUI. + + 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, pprof) + + +@leet.command() +@click.option( + "--pprof", + default="", + hidden=True, + help="Serve /debug/pprof/* on this address (e.g. 127.0.0.1:6060).", +) +@click.option( + "--interval", + default="", + metavar="DURATION", + help="Sampling interval for system metrics (e.g. 500ms, 2s, 1m).", +) +@click.help_option("-h", "--help") +def symon(pprof: str = "", interval: str = "") -> None: + """Launch the standalone system monitor.""" + from . import beta_leet + + beta_leet.launch_symon(pprof=pprof, interval=interval) + + +@leet.command() +def config() -> None: + """Edit LEET configuration.""" + from . import beta_leet + + beta_leet.launch_config() + + +@beta.command() +@click.argument("paths", type=click.Path(exists=True), nargs=-1) +@click.option( + "--live", + is_flag=True, + default=False, + help="""Sync a run while it's still being logged. + + This may hang if the process generating the run crashes uncleanly. + """, +) +@click.option( + "-e", + "--entity", + default="", + help="An entity override to use for all runs being synced.", +) +@click.option( + "-p", + "--project", + default="", + help="A project override to use for all runs being synced.", +) +@click.option( + "--id", + "run_id", + default="", + help="""A run ID override to use for all runs being synced. + + If setting this and syncing multiple files (with the same entity + and project), the files will be synced in order of start time. + This is intended to work with syncing multiple resumed fragments + of the same run. + """, +) +@click.option( + "--job-type", + default="", + help="A job type override for all runs being synced.", +) +@click.option( + "--replace-tags", + default="", + help="Rename tags using the format 'old1=new1,old2=new2'.", +) +@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. + + When syncing multiple files that are part of the same run, + the files are synced sequentially in order of start time + regardless of this setting. This happens for resumed runs + or when using the --id parameter. + """, +) +def sync( + paths: tuple[str, ...], + live: bool, + entity: str, + project: str, + run_id: str, + job_type: str, + replace_tags: str, + skip_synced: bool, + dry_run: bool, + verbose: bool, + n: int, +) -> None: + """Upload .wandb files specified by PATHS. + + This is a beta re-implementation of `wandb sync`. + It is not feature complete, not guaranteed to work, and may change + in backward-incompatible ways in any release of wandb. + + PATHS can include .wandb files, run directories containing .wandb files, + and "wandb" directories containing run directories. + + For example, to sync all runs in the current .wandb directory: + + $ wandb beta sync ./wandb + + To sync a specific run by specifying the run directory: + + $ 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], + live=live, + entity=entity, + project=project, + run_id=run_id, + job_type=job_type, + replace_tags=replace_tags, + dry_run=dry_run, + skip_synced=skip_synced, + verbose=verbose, + parallelism=n, + ) + + +@beta.group() +def core() -> None: + """Manage a shared local wandb-core service for multi-process workloads. + + wandb-core is the local backend process that handles run data, + file uploads, and system metrics collection. By default, each + process that calls `wandb.init()` starts its own backend. On a + machine running many independent workers, that duplicates work + and wastes CPU and memory. + + Use these commands to start one detached wandb-core instance and + point multiple workers on the same machine at it with the + WANDB_SERVICE environment variable. + + Typical workflow: + + $ wandb beta core start + $ export WANDB_SERVICE=printed_value + $ python -m your_launcher + $ wandb beta core stop + + For shell scripts, capture the raw WANDB_SERVICE value from stdout: + + $ export WANDB_SERVICE="$(wandb beta core start)" + + The shared service exits after 10 minutes of idleness by default. + Override this with --idle-timeout on the start command. + """ + + +try: + from .beta_sandbox import sandbox as sandbox_group +except ImportError: + pass +else: + beta.add_command(sandbox_group) + + +@core.command() +@click.option( + "--idle-timeout", + default="10m", + show_default=True, + metavar="DURATION", + help=( + "Shut down wandb-core after this much idle time with no connected " + "clients. Uses Go duration syntax, for example 30s, 10m, or 0 to " + "disable idle shutdown." + ), +) +def start(idle_timeout: str) -> None: + """Start a detached wandb-core service.""" + from . import beta_core + + beta_core.start(idle_timeout=idle_timeout) + + +@core.command() +def stop() -> None: + """Stop a detached wandb-core service. + + The service address is taken from the WANDB_SERVICE environment variable. + """ + from . import beta_core + + beta_core.stop() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/cli/beta_core.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/cli/beta_core.py new file mode 100644 index 0000000000000000000000000000000000000000..b8e9251fe91bda6492b81f05d70519d5687e91f2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/cli/beta_core.py @@ -0,0 +1,111 @@ +"""Implements `wandb beta core` helpers. + +These helpers manage a detached `wandb-core` process intended to be reused by +multiple independent Python processes on the same host. + +Discovery is explicit via the WANDB_SERVICE environment variable. +""" + +from __future__ import annotations + +import logging + +import click + +from wandb import env as wandb_env +from wandb.analytics import get_sentry +from wandb.proto import wandb_server_pb2 as spb +from wandb.sdk.lib import asyncio_manager +from wandb.sdk.lib.service import service_process, service_token +from wandb.sdk.wandb_settings import Settings + +_logger = logging.getLogger(__name__) +DEFAULT_IDLE_TIMEOUT = service_process.DEFAULT_DETACHED_IDLE_TIMEOUT + + +def start(*, idle_timeout: str) -> None: + """Start a detached wandb-core service. + + Args: + idle_timeout: How long the service should stay alive with no connected + clients before shutting down. This uses Go duration syntax, for + example ``30s`` or ``10m``. Use ``0`` to disable idle shutdown. + """ + try: + token = service_token.from_env() + except ValueError as e: + raise click.UsageError(str(e)) from None + + if token: + raise click.UsageError( + f"{wandb_env.SERVICE} is already set. Clear it or run " + "`wandb beta core stop` before starting another detached service." + ) + + proc = service_process.start_detached(Settings(), idle_timeout=idle_timeout) + token_value = proc.token.env_value + + click.secho("Started detached wandb-core service.", fg="green", err=True) + click.echo(token_value) # Print the token to stdout for programmatic use. + click.echo(f"Idle shutdown: {idle_timeout}.", err=True) + click.echo( + f"Set {wandb_env.SERVICE} to this value before starting worker processes: {token_value}", + err=True, + ) + click.echo( + "Any Python process launched with that environment variable will " + "connect to the existing service instead of spawning its own.", + err=True, + ) + + +def stop(*, exit_code: int = 0) -> None: + """Stop a detached wandb-core service addressed by WANDB_SERVICE.""" + get_sentry().configure_scope(process_context="beta-core-stop") + + try: + token = service_token.from_env() + except ValueError as e: + raise click.UsageError(str(e)) from None + + if not token: + raise click.UsageError( + f"{wandb_env.SERVICE} is not set. Set it to the detached service " + "you want to stop and rerun the command." + ) + + asyncer = asyncio_manager.AsyncioManager() + asyncer.start() + try: + client = token.connect(asyncer=asyncer) + + async def publish_teardown_and_close() -> None: + await client.publish( + spb.ServerRequest( + inform_teardown=spb.ServerInformTeardownRequest(exit_code=exit_code) + ) + ) + await client.close() + + asyncer.run(publish_teardown_and_close) + + except service_token.WandbServiceConnectionError as e: + _logger.exception("Failed to connect to wandb-core for stop") + raise click.ClickException( + f"Failed to connect to wandb-core using {wandb_env.SERVICE}: {e}" + ) from e + + except Exception as e: + get_sentry().reraise(e) + + finally: + asyncer.join() + + service_token.clear_service_in_env() + + click.secho("Sent shutdown request to wandb-core.", fg="green", err=True) + click.echo( + f"Clear {wandb_env.SERVICE} from any shells or process environments " + "that still set it.", + err=True, + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/cli/beta_leet.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/cli/beta_leet.py new file mode 100644 index 0000000000000000000000000000000000000000..2d351f62fdfc53da7993c0f9d3bba6dda9acea79 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/cli/beta_leet.py @@ -0,0 +1,140 @@ +from __future__ import annotations + +import dataclasses +import os +import pathlib +import subprocess +import sys + +import click +from typing_extensions import Never + +from wandb.analytics import get_sentry +from wandb.env import error_reporting_enabled, is_debug +from wandb.sdk import wandb_setup +from wandb.util import get_core_path + + +@dataclasses.dataclass(frozen=True) +class LaunchConfig: + """Configuration for launching LEET.""" + + wandb_dir: str + run_file: str | None = None + + +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 _find_wandb_file_in_dir(dir_path: pathlib.Path) -> pathlib.Path | None: + """Find a run-*.wandb file in the given directory. + + Returns None if not found or multiple found. + """ + wandb_files = list(dir_path.glob("run-*.wandb")) + if len(wandb_files) == 1: + return wandb_files[0] + return None + + +def _resolve_path(path: str | None) -> LaunchConfig: + """Resolve the given path into a LaunchConfig. + + Behavior: + - No path: Use default wandb_dir (workspace mode) + - .wandb file: Parent's parent as wandb_dir, file as run_file + - Run directory: Parent as wandb_dir, found .wandb as run_file + - Other directory: Treat as wandb_dir (workspace mode) + """ + if not path: + wandb_dir = wandb_setup.singleton().settings.wandb_dir + return LaunchConfig(wandb_dir=str(wandb_dir)) + + resolved = pathlib.Path(path).resolve() + + if resolved.is_file(): + if resolved.suffix == ".wandb": + run_dir = resolved.parent + wandb_dir = run_dir.parent + return LaunchConfig(wandb_dir=str(wandb_dir), run_file=str(resolved)) + else: + _fatal(f"Not a .wandb file: {resolved}") + + if resolved.is_dir(): + wandb_file = _find_wandb_file_in_dir(resolved) + if wandb_file: + wandb_dir = resolved.parent + return LaunchConfig(wandb_dir=str(wandb_dir), run_file=str(wandb_file)) + else: + return LaunchConfig(wandb_dir=str(resolved)) + + _fatal(f"Path does not exist: {resolved}") + + +def _base_args() -> list[str]: + """Build the common base arguments for wandb-core leet commands.""" + args = [get_core_path(), "leet"] + + if not error_reporting_enabled(): + args.append("--no-observability") + + if is_debug(default="False"): + args.extend(["--log-level", "-4"]) + + return args + + +def _run_core(args: list[str]) -> Never: + """Run wandb-core with the given arguments and exit with its return code.""" + try: + result = subprocess.run(args, env=os.environ, close_fds=True) + sys.exit(result.returncode) + except Exception as e: + get_sentry().reraise(e) + + +def launch(path: str | None, pprof: str) -> Never: + """Launch the LEET TUI.""" + get_sentry().configure_scope(process_context="leet") + + config = _resolve_path(path) + args = _base_args() + + if config.run_file: + args.extend(["--run-file", config.run_file]) + + if pprof: + args.extend(["--pprof", pprof]) + + args.append(config.wandb_dir) + + _run_core(args) + + +def launch_config() -> Never: + """Launch the LEET configuration editor.""" + get_sentry().configure_scope(process_context="leet-config") + + args = _base_args() + args.append("--config") + + _run_core(args) + + +def launch_symon(pprof: str = "", interval: str = "") -> Never: + """Launch the standalone system monitor.""" + get_sentry().configure_scope(process_context="leet-symon") + + args = _base_args() + args.append("--symon") + + if pprof: + args.extend(["--pprof", pprof]) + + if interval: + args.extend(["--interval", interval]) + + _run_core(args) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/cli/beta_sandbox.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/cli/beta_sandbox.py new file mode 100644 index 0000000000000000000000000000000000000000..5b28ec98428fbb310b921c3c1c77a6ebcde9aa86 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/cli/beta_sandbox.py @@ -0,0 +1,301 @@ +from __future__ import annotations + +import json +from datetime import datetime + +import click +from cwsandbox.cli.shell import _validate_cmd as _cwsandbox_validate_cmd + +from wandb.sandbox import CWSandboxError, Sandbox, SandboxStatus +from wandb.sandbox._auth import override_sandbox_entity + +_STATUS_CHOICES = [s.value for s in SandboxStatus if s != SandboxStatus.UNSPECIFIED] + + +class SandboxCommand(click.Command): + """Click command that injects sandbox entity override and error handling.""" + + def __init__(self, *args: object, **kwargs: object) -> None: + super().__init__(*args, **kwargs) + self.params = [ + click.Option( + ["-e", "--entity"], + default=None, + help="Set the W&B entity for sandbox. Default is user's default entity.", + ), + *self.params, + ] + + def invoke(self, ctx: click.Context) -> object: + entity = ctx.params.pop("entity", None) + + try: + with override_sandbox_entity(entity=entity): + return super().invoke(ctx) + except CWSandboxError as exc: + raise click.ClickException(str(exc)) from None + + +class SandboxGroup(click.Group): + """Click group for sandbox commands.""" + + command_class = SandboxCommand + + +@click.group(cls=SandboxGroup) +def sandbox() -> None: + """Manage W&B sandboxes. + + Commands use your default W&B entity unless you pass ``--entity``. + If a sandbox is not found or you get an auth error, it may have been + created under a non-default W&B entity. Retry with ``--entity ``. + + Examples: + # List all pending/running sandboxes + wandb beta sandbox ls + + # List all sandboxes + wandb beta sandbox ls -a + + # List sandbox created using non default entity + wandb beta sandbox ls --entity my-other-team + + # Run single command inside a running sandbox + wandb beta sandbox exec echo hello + + # Open interavtive shell + wandb beta sandbox sh + + # Tail log + wandb beta sandbox logs --follow + """ + + +@sandbox.command("ls") +@click.option( + "--status", + "-s", + default=None, + type=click.Choice(_STATUS_CHOICES, case_sensitive=False), + help="Filter by status.", +) +@click.option( + "--all", + "-a", + "include_stopped", + is_flag=True, + default=False, + help="Include stopped sandboxes in results.", +) +# TODO: cwsandbox is NOT returning the tags in the response object, so we can filter +# by tags, but we cannot show what tags the matched sandbox has .... +@click.option("--tag", "-t", "tags", multiple=True, help="Filter by tag (repeatable).") +@click.option( + "--output", + "-o", + "output_format", + default="table", + type=click.Choice(["table", "json"], case_sensitive=False), + help="Output format.", +) +def list_sandboxes( + status: str | None, + include_stopped: bool, + tags: tuple[str, ...], + output_format: str, +) -> None: + """List sandboxes. + + Examples: + # List all non stopped + wandb beta sandbox ls + + wandb beta sandbox ls -a + + wandb beta sandbox ls --status running + + wandb beta sandbox ls --tag foo --output json + + wandb beta sandbox ls --entity team + """ + sandboxes = Sandbox.list( + tags=list(tags) if tags else None, + status=status, + include_stopped=include_stopped, + ).result() + + if output_format == "json": + data = [ + { + "sandbox_id": sb.sandbox_id, + "status": sb.status.value if sb.status else None, + "started_at": sb.started_at.isoformat() if sb.started_at else None, + } + for sb in sandboxes + ] + click.echo(json.dumps(data, indent=2)) + return + + if not sandboxes: + click.echo("No sandboxes found.") + return + + click.echo(f"{'SANDBOX ID':<40} {'STATUS':<14} {'STARTED AT'}") + click.echo(f"{'-' * 40} {'-' * 14} {'-' * 24}") + + for sb in sandboxes: + sid = sb.sandbox_id or "-" + st = sb.status.value if sb.status else "-" + started = ( + sb.started_at.strftime("%Y-%m-%d %H:%M:%S UTC") if sb.started_at else "-" + ) + click.echo(f"{sid:<40} {st:<14} {started}") + + +@sandbox.command("sh") +@click.argument("sandbox_id") +@click.option( + "--cmd", + default="/bin/bash", + callback=_cwsandbox_validate_cmd, + help="Command to run (default: /bin/bash). Accepts full command strings.", +) +def shell( + sandbox_id: str, + cmd: str, +) -> None: + """Open an interactive shell in a sandbox. + + SANDBOX_ID is the ID of the sandbox to connect to. + + Examples: + wandb beta sandbox sh + + wandb beta sandbox sh --cmd /bin/zsh + + wandb beta sandbox sh --entity team + """ + from cwsandbox.cli.shell import shell + + callback = shell.callback + if callback is None: + raise click.ClickException("Failed to load the cwsandbox CLI command.") + + callback(sandbox_id=sandbox_id, cmd=cmd) + + +@sandbox.command( + "exec", + context_settings={"ignore_unknown_options": True}, +) +@click.argument("sandbox_id") +@click.argument("command_args", nargs=-1, required=True, type=click.UNPROCESSED) +@click.option( + "--cwd", + "-w", + default=None, + help="Working directory for the command.", +) +@click.option( + "--timeout", + "-t", + "timeout_seconds", + type=click.FloatRange(min=0, min_open=True), + default=None, + help="Timeout in seconds.", +) +def exec_in_sandbox( + sandbox_id: str, + command_args: tuple[str, ...], + cwd: str | None, + timeout_seconds: float | None, +) -> None: + """Execute a command in a sandbox. + + SANDBOX_ID is the ID of the sandbox to run the command in. + + Examples: + wandb beta sandbox exec echo hello + + wandb beta sandbox exec python -c "print('ok')" + + wandb beta sandbox exec --cwd /app python app.py + + wandb beta sandbox exec --entity team echo hello + """ + from cwsandbox.cli.exec import exec_command + + callback = exec_command.callback + if callback is None: + raise click.ClickException("Failed to load the cwsandbox exec command.") + + callback( + sandbox_id=sandbox_id, + command=command_args, + cwd=cwd, + timeout_seconds=timeout_seconds, + ) + + +@sandbox.command("logs") +@click.argument("sandbox_id") +@click.option( + "--follow", + "-f", + is_flag=True, + default=False, + help="Follow log output (like tail -f).", +) +@click.option( + "--tail", + "tail_lines", + type=click.IntRange(min=0), + default=None, + help="Number of recent lines to show.", +) +@click.option( + "--since", + "since_time", + type=click.DateTime(), + default=None, + help="Show logs since timestamp (e.g. 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS').", +) +@click.option( + "--timestamps", "-t", is_flag=True, default=False, help="Show timestamps." +) +def logs( + sandbox_id: str, + follow: bool, + tail_lines: int | None, + since_time: datetime | None, + timestamps: bool, +) -> None: + """Stream logs from a sandbox's main process. + + Streams stdout/stderr from the command used to create the sandbox. Output + from `wandb beta sandbox exec` commands is not included. + + SANDBOX_ID is the ID of the sandbox to stream logs from. + + Examples: + wandb beta sandbox logs + + wandb beta sandbox logs --tail 50 + + wandb beta sandbox logs --follow --timestamps + + wandb beta sandbox logs --entity team + """ + from cwsandbox.cli.logs import logs + + callback = logs.callback + if callback is None: + raise click.ClickException("Failed to load the cwsandbox logs command.") + + callback( + sandbox_id=sandbox_id, + follow=follow, + tail_lines=tail_lines, + since_time=since_time, + timestamps=timestamps, + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/cli/beta_sync.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/cli/beta_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..c9ac9b6afd506e12b7b26eeda64d1df6c0a5137f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/cli/beta_sync.py @@ -0,0 +1,347 @@ +"""Implements `wandb sync` using wandb-core.""" + +from __future__ import annotations + +import asyncio +import contextlib +import pathlib +import time +from collections.abc import Iterable, Iterator +from itertools import filterfalse + +import wandb +from wandb.errors import term +from wandb.proto.wandb_sync_pb2 import ServerSyncResponse +from wandb.sdk import wandb_setup +from wandb.sdk.lib import asyncio_compat, wbauth +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], + *, + live: bool, + entity: str, + project: str, + run_id: str, + job_type: str, + replace_tags: str, + dry_run: bool, + skip_synced: bool, + verbose: bool, + parallelism: int, +) -> None: + """Replay one or more .wandb files. + + Args: + live: Whether to enable 'live' mode, which indefinitely retries reading + incomplete transaction logs. + entity: The entity override for all paths, or an empty string. + project: The project override for all paths, or an empty string. + run_id: The run ID override for all paths, or an empty string. + job_type: An override for the job type for all runs, or an empty string. + replace_tags: A string in the form 'old1=new1,old2=new2' that defines + how to rename run tags. + 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. + """ + tag_replacements = _parse_replace_tags(replace_tags) + + singleton = wandb_setup.singleton() + + try: + cwd = pathlib.Path.cwd() + except OSError: + cwd = None + + ask_for_confirmation = False + if not paths: + paths = [pathlib.Path(singleton.settings.wandb_dir)] + ask_for_confirmation = True + + wandb_files = _to_unique_files( + ( + wandb_file + for path in paths + for wandb_file in _find_wandb_files(path, skip_synced=skip_synced) + ), + verbose=verbose, + ) + + if not wandb_files: + term.termlog("No runs to sync.") + return + + if dry_run: + term.termlog(f"Would sync {len(wandb_files)} run(s):") + _print_sorted_paths(wandb_files, verbose=verbose, root=cwd) + return + + term.termlog(f"Syncing {len(wandb_files)} run(s):") + _print_sorted_paths(wandb_files, verbose=verbose, root=cwd) + + if ask_for_confirmation and not term.confirm("Sync the listed runs?"): + return + + # Authenticate the session. This updates the singleton settings credentials. + if not wbauth.authenticate_session( + host=singleton.settings.base_url, + source="wandb sync", + no_offline=True, + ): + term.termlog("Not authenticated.") + return + + service = singleton.ensure_service() + printer = new_printer() + singleton.asyncer.run( + lambda: _do_sync( + wandb_files, + cwd=cwd, + live=live, + service=service, + entity=entity, + project=project, + run_id=run_id, + job_type=job_type, + tag_replacements=tag_replacements, + settings=singleton.settings, + printer=printer, + parallelism=parallelism, + ) + ) + + +def _parse_replace_tags(replace_tags: str) -> dict[str, str]: + """Parse the --replace-tags argument to wandb sync.""" + if not replace_tags: + return {} + + tag_replacements: dict[str, str] = {} + + for pair in replace_tags.split(","): + if "=" not in pair: + raise ValueError( + f"Invalid --replace-tags format: {pair}. Expected 'old=new'." + ) + + old_tag, new_tag = pair.split("=", 1) + tag_replacements[old_tag.strip()] = new_tag.strip() + + return tag_replacements + + +def _to_unique_files( + paths: Iterator[pathlib.Path], + *, + verbose: bool, +) -> set[pathlib.Path]: + """Returns paths with duplicates removed. + + Determines file equality the same way as os.path.samefile(). + """ + id_to_path: dict[tuple[int, int], pathlib.Path] = dict() + + # Sort in reverse so that the last path written to the map is + # alphabetically earliest. + for path in sorted(paths, reverse=True): + try: + stat = path.stat() + except OSError as e: + term.termerror(f"Failed to stat {path}: {e}") + continue + + id = (stat.st_ino, stat.st_dev) + + if verbose and (other_path := id_to_path.get(id)): + term.termlog(f"{path} is the same as {other_path}") + + id_to_path[id] = path + + return set(id_to_path.values()) + + +async def _do_sync( + wandb_files: set[pathlib.Path], + *, + cwd: pathlib.Path | None, + live: bool, + service: ServiceConnection, + entity: str, + project: str, + run_id: str, + job_type: str, + tag_replacements: dict[str, str], + 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, + cwd=cwd, + live=live, + entity=entity, + project=project, + run_id=run_id, + job_type=job_type, + tag_replacements=tag_replacements, + ) + 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(list(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, + *, + root: pathlib.Path | None, +) -> 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. + root: A root directory for making paths relative. + """ + # Prefer to print paths relative to the current working directory. + formatted_paths: list[str] = [] + for path in paths: + formatted_path = str(path) + + if root: + with contextlib.suppress(ValueError): + formatted_path = str(path.relative_to(root)) + + 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)): + term.termlog(f" {sorted_paths[i]}") + + if len(sorted_paths) > max_lines: + remaining = len(sorted_paths) - max_lines + term.termlog(f" +{remaining:,d} more (pass --verbose to see all)") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/cli/cli.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/cli/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..3b7180352da5a7dcaf374b3c5f9e59f282662513 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/cli/cli.py @@ -0,0 +1,3667 @@ +from __future__ import annotations + +import asyncio +import datetime +import getpass +import json +import logging +import os +import pathlib +import shlex +import shutil +import subprocess +import sys +import tempfile +import textwrap +import time +import traceback +from functools import wraps +from typing import Any + +import click +import yaml +from click.exceptions import ClickException + +import wandb +import wandb.errors +import wandb.sdk.verify.verify as wandb_verify +from wandb import Config, Error, env, util, wandb_agent +from wandb.analytics import get_sentry +from wandb.apis import InternalApi, PublicApi +from wandb.errors.links import url_registry +from wandb.old import core as old_core +from wandb.sdk import wandb_setup, wandb_sweep +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 SweepNotFoundError +from wandb.sdk.launch.sweeps import utils as sweep_utils +from wandb.sdk.launch.sweeps.scheduler import Scheduler +from wandb.sdk.lib import filesystem, settings_file +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 = old_core.wandb_dir(env.get_dir()) +if not os.path.exists(_wandb_dir) or not os.access(_wandb_dir, os.W_OK): + _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") +logger = logging.getLogger("wandb") + + +def _setup_logger() -> None: + """Set up logging to the wandb/debug-cli.user.log file.""" + logger_handler = logging.FileHandler(_wandb_log_path) + logger_handler.setLevel(logging.INFO) + logger_handler.setFormatter( + logging.Formatter( + fmt="%(asctime)s %(levelname)s %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) + ) + + # The wandb logger does not forward messages to the root handler. + logger.addHandler(logger_handler) + logging.root.addHandler(logger_handler) + + +_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: click.Context | None, + param: click.Parameter | None, + value: tuple[str, ...] | None, +) -> 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): + _setup_logger() + + if ctx.invoked_subcommand is None: + click.echo(ctx.get_help()) + + +@cli.command(context_settings=CONTEXT, 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): + """List projects for the current entity.""" + 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="""Log in to the W&B public cloud + (https://api.wandb.ai). + Mutually exclusive with --host.""", +) +@click.option( + "--host", + "--base-url", + default=None, + help="""Log in to a specific W&B server + instance by URL + (e.g. https://my-wandb.example.com). + Mutually exclusive with --cloud.""", +) +@click.option( + "--relogin", + default=None, + is_flag=True, + help="Force a new login prompt, ignoring any existing credentials.", +) +@click.option( + "--anonymously", + default=False, + hidden=True, + is_flag=True, + help="Deprecated. Has no effect and will be removed in a future version.", +) +@click.option( + "--verify/--no-verify", + default=False, + is_flag=True, + help="""Verify the API key with W&B after storing it. If verification + is successful, display the source of the credentials and the + default team.""", +) +@display_error +def login(key, host, cloud, relogin, anonymously, verify, no_offline=False): + """Authenticate your machine with W&B. + + Store an API key locally for authenticating with W&B services. + By default, credentials are stored without server-side verification. + + If no API key is provided as an argument, the command looks for + credentials in the following order: + + 1. The WANDB_API_KEY environment variable + + 2. The api_key setting in a system or workspace settings file (use + `wandb status` to see which settings file is used) + + 3. The .netrc file (~/.netrc, ~/_netrc, or the NETRC env var path) + + 4. An interactive prompt (if a TTY is available) + + For self-hosted or dedicated cloud deployments, specify the server + URL with `--host`, or set the WANDB_BASE_URL environment variable. + + For example, to log in interactively (prompts for API key): + + $ wandb login + + To log in with an explicit API key (WANDB_API_KEY_EXAMPLE): + + $ wandb login WANDB_API_KEY_EXAMPLE + + To log in and verify the API key is valid: + + $ wandb login --verify + + To log in to the W&B public cloud instead of a configured self-hosted instance: + + $ wandb login --cloud + + To log in to a self-hosted W&B instance: + + $ wandb login --host https://my-wandb-server.example.com + + To force a new login prompt even if already authenticated: + + $ wandb login --relogin + """ + # TODO: handle no_offline + if anonymously: + wandb.termwarn( + "The --anonymously parameter has no effect and will be removed" + + " in a future version.", + repeat=False, + ) + + if host and cloud: + wandb.termerror("Cannot use --host and --cloud together.") + sys.exit(1) + + if cloud: + host = "https://api.wandb.ai" + + # 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( + force=True, + host=host, + key=key, + relogin=relogin, + verify=verify, + referrer="models", + ) + + +@cli.command(context_settings=CONTEXT) +@click.option("--project", "-p", help="Set the project to upload runs to.") +@click.option("--entity", "-e", help="Set 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 existing W&B configuration + for the directory.""", +) +@click.option( + "--mode", + "-m", + help="Set the W&B mode. One of 'online', 'offline', or 'disabled'.", +) +@click.pass_context +@display_error +def init(ctx, project, entity, reset, mode): + """Initialize or update W&B configuration for the current directory. + + Set a project and entity, create local W&B settings, and + prepare the directory for experiment tracking. + + For example, set up W&B for the current directory with guided prompts + for team and project selection: + + $ wandb init + + To set the default project to "foobar" and the default entity to "team-awesome" without prompts: + + $ wandb init --project foobar --entity team-awesome + + To set the W&B mode to offline: + + $ wandb init --mode offline + + To reset existing W&B configuration for the current directory: + + $ wandb init --reset + """ + # Load settings from environment variables and other normal sources. + global_settings = wandb_setup.singleton().settings + + # non-interactive init + if reset or project or entity or mode: + system_settings = global_settings.read_system_settings() + + if reset: + system_settings.clear("entity") + system_settings.clear("project") + system_settings.clear("mode") + if entity: + system_settings.set("entity", entity) + if project: + system_settings.set("project", project) + if mode: + system_settings.set("mode", mode) + + system_settings.save() + return + + if os.path.exists(global_settings.settings_workspace): + 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}") + + system_settings = global_settings.read_system_settings() + system_settings.set("entity", entity) + system_settings.set("project", project) + system_settings.save() + + filesystem.mkdir_exists_ok(global_settings.wandb_dir) + with open(os.path.join(global_settings.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="Enable verbose output.", + hidden=True, +) +@click.option("--id", "run_id", help="Upload to an existing run ID.") +@click.option("--project", "-p", help="Set the project to upload the run to.") +@click.option("--entity", "-e", help="Set the entity to scope the project to.") +@click.option( + "--job_type", + "job_type", + help="Set the job type to group related runs.", +) +@click.option( + "--sync-tensorboard/--no-sync-tensorboard", + is_flag=True, + default=None, + help="""Sync TensorBoard tfevent files. + On by default for specific paths, + off for --sync-all.""", +) +@click.option( + "--include-globs", + help="Include only runs matching these glob patterns (comma-separated).", +) +@click.option( + "--exclude-globs", + help="Exclude runs matching these glob patterns (comma-separated).", +) +@click.option( + "--include-online/--no-include-online", + is_flag=True, + default=None, + help="Include runs created in online mode.", +) +@click.option( + "--include-offline/--no-include-offline", + is_flag=True, + default=None, + help="Include runs created in offline mode.", +) +@click.option( + "--include-synced/--no-include-synced", + is_flag=True, + default=None, + help="Include runs that are already synced.", +) +@click.option( + "--mark-synced/--no-mark-synced", + is_flag=True, + default=True, + help="Mark runs as synced after upload.", +) +@click.option( + "--sync-all", + is_flag=True, + default=False, + help="Sync all unsynced runs in the local wandb directory.", +) +@click.option( + "--clean", + is_flag=True, + default=False, + help="Delete local data for runs that are already synced.", +) +@click.option( + "--clean-old-hours", + default=24, + help="""Delete only synced runs older than this many + hours (use with --clean).""", + type=int, +) +@click.option( + "--clean-force", + is_flag=True, + default=False, + help="Skip the confirmation prompt if --clean is specified.", +) +@click.option("--ignore", hidden=True) +@click.option( + "--show", default=5, help="Set the number of runs to show in the summary." +) +@click.option( + "--append", + is_flag=True, + default=False, + help="Append data to an existing run instead of creating a new run.", +) +@click.option( + "--skip-console", + is_flag=True, + default=False, + help="Skip uploading console logs.", +) +@click.option( + "--replace-tags", + help="Rename tags during sync. Use 'old=new' pairs separated by commas.", +) +@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, +): + """Upload existing local W&B run data to the cloud. + + Sync offline or incomplete runs from the local `wandb` directory to + the W&B server. If PATH is provided, sync runs at that path. If no + path is given, search for a ./wandb directory, then a wandb/ + subdirectory. + + Run without arguments to print a summary of synced and unsynced + runs without uploading anything. + + When syncing a specific path, include TensorBoard event files + by default. When using `--sync-all`, disable TensorBoard by + default (use `--sync-tensorboard` to enable it). + + PATH is a .wandb file or a run directory that contains a .wandb file. + A typical path looks like: + + ./wandb/run-YYYYMMDD_HHMMSS-RUN_ID/run-RUN_ID.wandb + + where run-YYYYMMDD_HHMMSS-RUN_ID is the run directory and + run-RUN_ID.wandb is the .wandb file. YYYYMMDD_HHMMSS is the + timestamp of when the run was created and RUN_ID is the unique ID + of the run. + + For example, to show a summary of local runs and their sync status: + + $ wandb sync + + To sync run ID abcd1234 that is locally saved locally in + the ./wandb/run-20170617_000000-abcd1234 directory: + + $ wandb sync ./wandb/run-20170617_000000-abcd1234 + + To sync run abcd1234 by its local .wandb + filepath (./wandb/run-20170617_000000-abcd1234/run-abcd1234.wandb): + + $ wandb sync ./wandb/run-20170617_000000-abcd1234/run-abcd1234.wandb + + To sync all unsynced runs in the local wandb directory: + + $ wandb sync --sync-all + + To delete local data for runs that have already been synced: + + $ wandb sync --clean + + To delete synced runs older than 48 hours without a confirmation prompt: + + $ wandb sync --clean --clean-old-hours 48 --clean-force + """ + 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) -> dict[str, str] | None: + """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) +@click.option( + "--project", + "-p", + default=None, + help="Set the project for sweep runs. Use 'Uncategorized' if not set.", +) +@click.option( + "--entity", + "-e", + default=None, + help="""Set the entity for sweep. Use the current user's default entity + if not set.""", +) +@click.option( + "--controller", + is_flag=True, + default=False, + help="Start a local sweep controller after creating the sweep.", +) +@click.option( + "--verbose", + is_flag=True, + default=False, + help="Display verbose output.", +) +@click.option( + "--name", + default=None, + help="""Set a display name for the sweep. Use the sweep ID + if not specified.""", +) +@click.option( + "--program", + default=None, + help="Override the training program specified in the sweep config.", +) +@click.option( + "--settings", + default=None, + help="Set sweep settings.", + hidden=True, +) +@click.option( + "--update", + default=None, + help="Update an existing sweep configuration. Pass the sweep ID.", +) +@click.option( + "--stop", + is_flag=True, + default=False, + help="Stop a sweep. Let active runs finish but do not start new runs.", +) +@click.option( + "--cancel", + is_flag=True, + default=False, + help="Cancel a sweep. Kill active runs and stop starting new ones.", +) +@click.option( + "--pause", + is_flag=True, + default=False, + help="Pause a sweep. Temporarily stop starting new runs.", +) +@click.option( + "--resume", + is_flag=True, + default=False, + help="Resume a paused sweep.", +) +@click.option( + "--prior_run", + "-R", + "prior_runs", + multiple=True, + default=None, + help="""Attach an existing run to this sweep by ID. Specify multiple times + to attach multiple runs.""", +) +@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, +): + """Create, update, or manage a hyperparameter sweep. + + Provide a YAML config file to create a sweep. Define the search + strategy, parameters, and metric to optimize in the config. + Register the sweep with the W&B server and print the sweep ID + and a command to start an agent. + + Provide a sweep ID (or full path entity/project/sweep_id) with a + state flag (`--stop`, `--cancel`, `--pause`, or `--resume`) to manage + an existing sweep. + + The sweep ID is a unique identifier for the sweep, generated by + W&B when the sweep is created. You can find the sweep ID in the W&B App + or in the output of the `wandb sweep` command when you create a new sweep. + + For example, to create a sweep using the configuration defined in + sweep_config.yaml. Use the current user's default entity and project: + + $ wandb sweep sweep_config.yaml + + To create a sweep and store the results under the "team-awesome" entity + and "foobar" project: + + $ wandb sweep -p foobar -e team-awesome sweep_config.yaml + + To update sweep abcd1234 with a new configuration from sweep_config.yaml. + This is useful for changing the parameters or search strategy of an + active sweep: + + $ wandb sweep --update abcd1234 sweep_config.yaml + + To stop sweep abcd1234 under the "team-awesome" entity + and "foobar" project: + + $ wandb sweep --stop team-awesome/foobar/abcd1234 + + To cancel sweep abcd1234 in the current user's default entity and project: + + $ wandb sweep --cancel abcd1234 + + To pause sweep abcd1234 in the current user's default entity and + project. Later, resume the sweep: + + $ wandb sweep --pause abcd1234 + + $ wandb sweep --resume abcd1234 + + To create a sweep with a local controller that uses the configuration + in sweep_config.yaml: + + $ wandb sweep --controller sweep_config.yaml + + To create a new sweep and include two previously completed runs + (run ID abcd1234 and run ID efgh5678) so their results are incorporated + into the sweep's hyperparameter search: + + $ wandb sweep -R abcd1234 -R efgh5678 sweep_config.yaml + """ + 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_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: str | None = scheduler_args.get("job") + if scheduler_job: + wandb.termwarn( + "Using a scheduler job for launch sweeps is *experimental* and may change without warning" + ) + queue: str | None = 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"), + ) + 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_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, in + other words, 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() + get_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 = public_api.run_queue(entity=entity, name=queue) + 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.") + get_sentry().exception(e) + sys.exit(e) + except ExecutionError as e: + logger.exception("An error occurred.") + get_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: + get_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 + are 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() + get_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: + get_sentry().exception(e) + raise + + +@cli.command(context_settings=CONTEXT) +@click.pass_context +@click.option( + "--project", + "-p", + default=None, + help="Set the project to upload runs to.", +) +@click.option( + "--entity", + "-e", + default=None, + help="Set the entity to scope the project to.", +) +@click.option( + "--count", + default=None, + type=int, + help="""Maximum number of runs this agent will execute. Continues until + the sweep completes if not set.""", +) +@click.option( + "--forward-signals", + "-f", + is_flag=True, + default=False, + help="""Forward signals (e.g. SIGINT/SIGTERM) to child runs so they can + shut down cleanly.""", +) +@click.argument("sweep_id") +@display_error +def agent(ctx, project, entity, count, forward_signals, sweep_id): + """Start a sweep agent. + + Poll the W&B server for hyperparameter configurations from + the sweep and start a run for each configuration. + + The agent exits when the sweep completes, the sweep + is stopped, cancelled, or the `--count` limit is reached. + + Find the sweep ID within the Sweeps tab in the W&B App + or in the output of the `wandb sweep` command when you create a new sweep. + + The sweep ID can include the entity and project path + (entity/project/sweep_id) or the eight character sweep ID. + + For example, to start an agent for a sweep with a sweep ID of wbyz9876: + + $ wandb agent wbyz9876 + + To start an agent with a run limit of 10 runs for the sweep: + + $ wandb agent --count 10 wbyz9876 + + To start an agent for a sweep and save it to a project + called "sweeps-project" that belongs to the "team-awesome" entity: + + $ wandb agent -p sweeps-project -e team-awesome wbyz9876 + + To forward signals to child runs for clean shutdown: + + $ wandb agent --forward-signals wbyz9876 + """ + 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 🕵️") + try: + wandb_agent.agent( + sweep_id, + entity=entity, + project=project, + count=count, + forward_signals=forward_signals, + ) + # TODO: handle other errors with correct exit codes + except SweepNotFoundError: + wandb.termerror("Sweep was deleted or agent was not found. Stopping agent.") + sys.exit(1) + + # 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) + + get_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: + get_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() + get_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) +@click.option( + "--verbose", + is_flag=True, + default=False, + help="Display verbose output from controller.", +) +@click.argument("sweep_id") +@display_error +def controller(verbose, sweep_id): + """Start a local sweep controller for a W&B hyperparameter sweep. + + Start a local process that orchestrates the specified sweep. Read the + sweep configuration from W&B, select hyperparameter combinations based + on the configured search strategy (grid, random, Bayesian, and so on), + and dispatch runs to sweep agents. + + By default, W&B runs sweep controllers on its managed infrastructure. + Use this command to run the controller locally instead. For example, you + can use this command to debug behavior or operate in environments with + limited connectivity. + + sweep_id is printed by `wandb sweep` when you create a sweep. It + consists of a unique identifier for the sweep and may include the + entity and project path (entity/project/sweep_id). + + For example, to start a local sweep controller for a sweep with sweep ID wbyz9876: + + $ wandb controller wbyz9876 + """ + 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 inject W&B environment variables automatically. + + Pass all arguments through to `docker run` while injecting: + + - WANDB_API_KEY: Inject the current API key if logged in so the + container can authenticate with W&B. + + - WANDB_DOCKER: Inject the resolved image ID if the image can be detected + from the arguments so W&B can track which Docker image produced the run. + + Add `--runtime nvidia` automatically if `nvidia-docker` is detected + on the host and `--runtime` is not already set. + + For example, to run the Python script train.py inside the "my-image" container: + + $ wandb docker-run my-image python train.py + """ + 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 code in a Docker container with W&B configured. + + Start a Docker container, inject the WANDB_DOCKERs environment + variable, and mount the current working directory at `/app` by + default. Inject WANDB_API_KEY if logged in. Override the + container entrypoint to ensure `wandb` is installed. + + Pass additional arguments to insert them into `docker run` before + the image name. Use a default image if none is specified. + + Use `--jupyter` to install and start JupyterLab on port 8888. + Enable the NVIDIA runtime automatically if NVIDIA Docker is + available on the host. + + Requires Docker to be installed and running on the host machine. + + To inject W&B environment variables into an existing `docker run` + command without modifying the entrypoint, use `wandb docker-run`. + + For example, to run the default image and mount a dataset into the container: + + $ wandb docker -v /mnt/dataset:/app/data + + To run a default image and start JupyterLab: + + $ wandb docker -v /mnt/dataset:/app/data --jupyter + + To run a GPU-enabled image with a training command: + + $ wandb docker wandb/deepo:keras-gpu --no-tty --cmd "python train.py" + """ + 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 and 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) +@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="Environment variables to pass to wandb/local Docker image.", +) +@click.option( + "--daemon/--no-daemon", + default=True, + help="""Run the server in the background. Use --no-daemon + to run in the foreground.""", +) +@click.option( + "--upgrade", + is_flag=True, + default=False, + help="""Pull the latest wandb/local Docker image before + starting. Stop any existing container.""", + hidden=True, +) +@click.option( + "--edge", is_flag=True, default=False, help="Use the bleeding edge", hidden=True +) +@display_error +def start(ctx, port, env, daemon, upgrade, edge): + """Start a local W&B Server instance in a Docker container. + + Pull and run the wandb/local Docker image. Map the specified host + port to port 8080 in the container and mount a persistent Docker + volume named "wandb" to store data. + + Configure the "base_url" setting to point to the local server so + that subsequent W&B client calls use it. Prompt for login if no + API key is found. + + Requires Docker to be installed and running on the host machine. + + This command starts only the W&B Models UI. It is provided only + for local testing. In production, the W&B Kubernetes Operator is the recommended + way to deploy W&B Server. See + https://docs.wandb.ai/platform/hosting/self-managed/operator. + + For example, to start a local W&B server on the default port (8080): + + $ wandb server start + + To start the server on port 9090: + + $ wandb server start -p 9090 + + To start the server in the foreground: + + $ wandb server start --no-daemon + """ + 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}" + + system_settings = wandb_setup.singleton().settings.read_system_settings() + system_settings.set("base_url", host, globally=True) + + try: + system_settings.save() + except settings_file.SaveSettingsError as e: + msg = "Failed to update base_url setting" + logger.exception(msg) + wandb.termerror(f"{msg}: {e}") + + 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) +def stop(): + """Stop a running local W&B server. + + Stops the Docker container named `wandb-local` that was started + by `wandb server start`. Requires Docker to be installed. + + For example, to stop the local W&B server: + $ wandb server 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="Upload, download, and manage W&B artifacts.") +def artifact(): + pass + + +@artifact.command(context_settings=CONTEXT) +@click.argument("path") +@click.option( + "--name", + "-n", + help="""Artifact name in project/artifact_name format. Defaults to + the basename of the path.""", +) +@click.option("--description", "-d", help="A description of this artifact.") +@click.option( + "--type", + "-t", + default="dataset", + help="The type of the artifact. Defaults to 'dataset'.", +) +@click.option( + "--alias", + "-a", + default=["latest"], + multiple=True, + help="""An alias to apply to this artifact. Can be specified multiple + times. Defaults to 'latest'.""", +) +@click.option("--id", "run_id", help="Upload to an existing run with this ID.") +@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 for artifact files. Either + 'mutable' (default) or 'immutable'.""", +) +@display_error +def put( + path, + name, + description, + type, + alias, + run_id, + resume, + skip_cache, + policy, +): + """Upload an artifact to W&B. + + Upload a file, directory, or URL reference as a versioned artifact. + + The PATH can be a local file, a local directory, or a URL + (containing `://`) to log as a reference artifact. + + If `--name` is not specified, the artifact name defaults to the + basename of the path. If the project cannot be parsed from the + name, you are prompted to enter one. + + For example, to upload all files in a local directory ./data/training as a + dataset artifact in W&B: + + $ wandb artifact put --type dataset ./data/training + + To upload model.pt to the "foobar" project and assign "trained-model" as + the artifact name: + + $ wandb artifact put --name foobar/trained-model --type model ./model.pt + + To tag the artifact with both "latest" and "v2.0" so it can be + referenced by either alias: + + $ wandb artifact put --alias latest --alias v2.0 --type model ./model.pt + + To record an Amazon S3 path as a reference without downloading or re-uploading the data: + + $ wandb artifact put --type dataset s3://my-bucket/datasets/training + + To attach a human-readable description to a dataset artifact for documentation: + + $ wandb artifact put --type dataset --description "Training data, Jan 2025" ./data/training + """ + 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") + + 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) +@click.argument("path") +@click.option( + "--root", + help="""Directory to download the artifact to. Uses the default + artifact cache if not set.""", +) +@click.option( + "--type", + help="""Expected artifact type. Fails if the artifact does not match.""", +) +@display_error +def get(path, root, type): + """Download an artifact from W&B by its path. + + The PATH format is entity/project/artifact_name:version. If + the version is omitted, use the "latest" alias. + + For example, to download the latest version of an artifact called "processed-training-set" + from the "foobar" project under the "team-awesome" entity: + + $ wandb artifact get team-awesome/foobar/processed-training-set:latest + + To download a specific version (v2) of the "processed-training-set" artifact + to a local directory (./data): + + $ wandb artifact get --root ./data team-awesome/foobar/processed-training-set:v2 + """ + 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) +@click.argument("path") +@click.option("--type", "-t", help="Filter artifacts by type.") +@display_error +def ls(path, type): + """List all artifacts in a W&B project. + + Display the latest version of each artifact collection in a + project. Show the type, last updated time, size, and name. + + The PATH consists of the entity and project (entity/project) to + list artifacts from. + + For example, to list all artifacts in a project called "foobar" under + the "team-awesome" entity: + + $ wandb artifact ls team-awesome/foobar + + To list only artifacts of type "model" in the same project: + + $ wandb artifact ls --type model team-awesome/foobar + """ + 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, + ) + if (latest := next(versions, None)) is not None: + wandb.termlog( + f"{kind.type:<15s}{latest.updated_at:<15s}{util.to_human_size(latest.size):>15s} {latest.name:<20s}" + ) + else: + # Artifact collection exists but has no versions. This can happen when: + # 1. A collection was just created but no artifacts have been logged yet. + # 2. All versions within an artifact collection were deleted. + wandb.termlog( + f"{kind.type:<15s}{'N/A':<15s}{'0 B':>15s} {collection.name:<20s} (no versions)" + ) + + +@artifact.group( + help="""Manage the local artifact cache. + + Cache downloaded artifact files locally to avoid redundant downloads. + + Use subcommands to inspect and reclaim disk space used by the cache. + """ +) +def cache(): + pass + + +@cache.command(context_settings=CONTEXT) +@click.argument("target_size") +@click.option( + "--remove-temp/--no-remove-temp", + default=False, + help="Also remove temporary files from the cache.", +) +@display_error +def cleanup(target_size, remove_temp): + """Reduce the local artifact cache size. + + Remove the least recently accessed files first until the cache is + at or below the TARGET_SIZE. TARGET_SIZE accepts human-readable + formats (for example, 10GB or 500MB). + + For example, to reduce the artifact cache to 10 GB: + + $ wandb artifact cache cleanup 10GB + + To remove temporary files and reduce the artifact cache to 5 GB: + + $ wandb artifact cache cleanup --remove-temp 5GB + """ + 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) +@click.argument("run", envvar=env.RUN_ID) +@click.option( + "--project", + "-p", + envvar=env.PROJECT, + help="The project containing the run to pull files from.", +) +@click.option( + "--entity", + "-e", + default="models", + envvar=env.ENTITY, + help="""The entity that owns the project. Defaults to the value of the + WANDB_ENTITY environment variable or the default entity if not set.""", +) +@display_error +def pull(run, project, entity): + """Download files from a W&B run. + + Fetch all files associated with the specified run. Skip files that already + exist locally with the same content. Create subdirectories as needed to + mirror the structure of the files in W&B. + + Use the run ID to reference the run, and optionally specify the project + and entity if not included in the run argument. + + For example, to download files from a run with run ID "abcd1234" in the "foobar" project + and "team-awesome" entity: + + $ wandb pull -p foobar -e team-awesome abcd1234 + """ + 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) +@click.pass_context +@click.argument("run", envvar=env.RUN_ID) +@click.option( + "--no-git", + is_flag=True, + default=False, + help="Skip git restoration. Only restore config and Docker state.", +) +@click.option( + "--branch/--no-branch", + default=True, + help="Create a wandb/run_id branch or check out the commit in detached HEAD mode.", +) +@click.option( + "--project", + "-p", + envvar=env.PROJECT, + help="Specify the project to look up the run in.", +) +@click.option( + "--entity", + "-e", + envvar=env.ENTITY, + help="Specify the entity to scope the run lookup to.", +) +@display_error +def restore(ctx, run, no_git, branch, project, entity): + """Restore the code, config, or Docker environement from a previous W&B run. + + Recreate the environment of a previous run so you can reproduce it. + Requires authentication with W&B. + + Restore up to three pieces of state, depending on what the original + run recorded: + + 1. Config (always): Write the run config to wandb/config.yaml. + + 2. Git (if available): Check out the original commit on a new + wandb/run_id branch. Fetch and apply any saved diff patch. + If the original commit cannot be found, + fall back to an upstream commit if the original cannot be found. + Run this command from the same git repository as the original run. Skip + this step with `--no-git`. + + 3. Docker (if available): If the run was executed inside a Docker + container, start the same image with the original command. + + If the run has no git history and no Docker image, + restore only the config. + + Accept the run identifier in any of the following formats: + run_id, project:run_id, entity/project:run_id, or entity/project/run_id . + + For example, to restore a run with run ID in the default project + (stored as the WANDB_PROJECT environment variable) and entity + (set from WANDB_ENTITY or the authenticated user's default entity): + + $ wandb restore abcd1234 + + To restore a run from the "foobar" project and "team-awesome" entity with + run ID abcd1234: + + $ wandb restore team-awesome/foobar/abcd1234 + + To restore run abcd1234 without restoring git state. Only restore config + and Docker state: + + $ wandb restore --no-git abcd1234 + + To restore run abcd1234 in detached HEAD mode instead of creating a branch: + + $ wandb restore --no-branch abcd1234 + + To restore run abcd1234 from another team's project: + + $ wandb restore other-team/their-project:abcd1234 + """ + from wandb.old.core import wandb_dir + from wandb.sdk.lib.gitlib import GitRepo + + 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.""" + + git = GitRepo(remote=api.settings("git_remote")) + + if no_git: + commit = None + elif not 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 git.enabled: + wandb.termlog(f"Fetching origin and finding commit: {commit}") + subprocess.check_call(["git", "fetch", "--all"]) + try: + 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: + 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 git.repo.branches: + 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" + ) + git.repo.git.checkout(branch_name) + else: + wandb.termlog(f"Checking out {commit} in detached mode") + 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 = 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() +@display_error +def online(): + """Re-enable cloud syncing for W&B runs. + + Clear the offline mode setting so subsequent runs in this directory + sync data to the W&B cloud. + + Undoes a previous call to `wandb offline`. + + For example, to re-enable cloud syncing after working offline: + + $ wandb online + + To re-enable cloud syncing, then run a training script: + + $ wandb online && python train.py + """ + system_settings = wandb_setup.singleton().settings.read_system_settings() + system_settings.clear("mode") + system_settings.save() + + click.echo( + "W&B online. Running your script from this directory will now sync to the cloud." + ) + + +@cli.command() +@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. + + For example, to run a script in offline mode to log data locally without syncing + to the cloud: + + $ wandb offline && python train.py + + To run a script in offline mode: + + $ wandb offline && python train.py + + At a later time, sync all offline runs to the cloud: + + $ wandb sync --sync-all + """ + system_settings = wandb_setup.singleton().settings.read_system_settings() + system_settings.set("mode", "offline") + system_settings.save() + + 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." + ) + + +@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() +@click.option( + "--settings/--no-settings", + help="Display the current settings.", + default=True, +) +def status(settings): + """Display the current W&B configuration settings. + + Print all active W&B settings as formatted JSON, including the + base URL, API key, project, entity, and other resolved values. + + For example, to show current settings: + + $ wandb status + """ + 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() +@click.option( + "--service", + is_flag=True, + show_default=True, + default=True, + help="No effect. Accepted for backwards compatibility.", +) +def disabled(service): + """Disable W&B functionality. + + While W&B is in `disabled` mode, it does not log or sync data. + + Use `wandb enable` to restore W&B functionality. + + Use `wandb offline` to stop cloud syncing while continuning to log data + locally. + + For example, to turn off W&B so that the train.py script executes without logging or + syncing data to W&B: + + $ wandb disabled + + Next, train the model without logging or syncing to W&B: + + $ python train.py # Does not log or sync data to W&B + + Restore W&B functionality when ready to log and sync again: + + $ wandb enabled + """ + system_settings = wandb_setup.singleton().settings.read_system_settings() + system_settings.set("mode", "disabled") + system_settings.save() + + click.echo("W&B disabled.") + + +@cli.command() +@click.option( + "--service", + is_flag=True, + show_default=True, + default=True, + help="No effect. Accepted for backwards compatibility.", +) +def enabled(service): + """Re-enable W&B after it was deactivated with `wandb disabled`. + + Set the mode to `online` to restore full W&B functionality, + including cloud syncing and artifact storage. + + Does not upload data logged while W&B was set to `disabled`, but allows + new data to be logged and synced. + + To switch between online and offline modes without fully deactivating W&B, + use `wandb online` or `wandb offline` instead. + + For example, to restore W&B functionality after deactivating it with `wandb disabled`: + + $ wandb enabled + + To run a training script with W&B logging and syncing restored: + + $ python train.py # Log and sync data to W&B + """ + system_settings = wandb_setup.singleton().settings.read_system_settings() + system_settings.set("mode", "online") + system_settings.save() + + click.echo("W&B enabled.") + + +@cli.command(context_settings=CONTEXT) +@click.option( + "--host", + default=None, + help="Target a specific W&B instance URL. Default to configured base URL.", +) +def verify(host): + """Run integration checks against a self-hosted W&B instance. + + Validate that a self-hosted or dedicated cloud W&B deployment is configured + and operating correctly. Do not run this command against the public W&B + cloud at api.wandb.ai. + + Exits with `code 1` if any critical check fails. + + For example, to verify the currently configured W&B instance: + + $ wandb verify --host https://my-wandb-instance.com + + To verify a specific self-hosted instance: + + $ wandb verify --host https://my-wandb-server.example.com + """ + # 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.command( + "purge-cache", + help="""Purges cached logs, run history, and artifacts from the + local W&B cache.""", +) +@click.option( + "--age", + default="0d", + help="""Removes items older than the specified time + period (e.g., '10s', '5m', '8h', '7d', '6M', '1y').""", +) +@click.option( + "--force", + is_flag=True, + default=False, + help="Do not prompt for confirmation when deleting files.", +) +def purge_cache( + age: str, + force: bool, +): + try: + age_seconds = util.time_string_to_seconds(age) + except ValueError as e: + wandb.termerror(str(e)) + sys.exit(1) + + cache_dir = pathlib.Path(env.get_cache_dir()) + if not cache_dir.exists(): + wandb.termlog(f"Cache directory does not exist: {cache_dir}") + return + + cutoff_time = time.time() - age_seconds + purged_count = 0 + data_deleted = 0 + + files = cache_dir.glob("**/*") + for file in files: + if file.stat().st_mtime > cutoff_time or file.is_dir(): + continue + + if not force: + confirm = click.confirm( + f"Are you sure you want to delete cache file {file}?", + ) + if not confirm: + wandb.termlog(f"Skipping cache file: {file}") + continue + + data_deleted += file.stat().st_size + file.unlink(missing_ok=True) + purged_count += 1 + + wandb.termlog( + f"Deleted {purged_count} file(s) ({util.to_human_size(data_deleted)})" + ) + + +cli.add_command(beta) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/docker/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/docker/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cdd1a6df4d5252737428dc8d499b4dad604385ee --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/docker/__init__.py @@ -0,0 +1,288 @@ +from __future__ import annotations + +import json +import logging +import os +import shutil +import subprocess +from typing import Any + +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: bytes | None = None, + stderr: bytes | None = 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]) -> str | None: + """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, + ) + except FileNotFoundError: + # If docker command is not found + return False + else: + return result.returncode == 0 + + +def build( + tags: list[str], file: str, context_path: str, platform: str | None = 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: str | None) -> bool: + # the load option does not work when multiple platforms are specified: + # https://github.com/docker/buildx/issues/59 + return bool(platform is None or platform and "," not in platform) + + +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: bytes | None = None, + return_stderr: bool = False, + env: dict[str, str] | None = None, +) -> 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: int | None = subprocess.PIPE if capture_stdout else None + stderr_dest: int | None = 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: bytes | None) -> 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, str | None]: + 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) -> str | None: + """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) -> str | None: + """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) -> str | None: + """Push an image to a remote registry.""" + return shell(["push", f"{image}:{tag}"]) + + +def login(username: str, password: str, registry: str) -> str | None: + """Login to a registry.""" + return shell(["login", "--username", username, "--password", password, registry]) + + +def tag(image_name: str, tag: str) -> str | None: + """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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/docker/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/docker/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8298e9c82eb0551bab3f47ac54b7c2227d13b10c Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/docker/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/docker/__pycache__/names.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/docker/__pycache__/names.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9169ab1ffec566529753b925b389721c5e6508eb Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/docker/__pycache__/names.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/docker/names.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/docker/names.py new file mode 100644 index 0000000000000000000000000000000000000000..384d39a9e21329bcb71abfbcacdcfa9b3c78bbd2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/docker/wandb-entrypoint.sh b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/docker/wandb-entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2d4af61de2eb53973f8ee5eb6e619521d66a63a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1aa45ad8aced101f4bec07df6f1d8972dabffd34 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..508d65cc05e3abf913d0839546110da33789d9d3 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/__pycache__/errors.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/__pycache__/errors.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a6cafb338e761c8f50b5ed160917839c3e3ca03 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/__pycache__/errors.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/__pycache__/links.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/__pycache__/links.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57d68b6e7d4391790664fcc5f583b768bc408e97 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/__pycache__/links.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/__pycache__/term.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/__pycache__/term.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24e8ec1bebbf78cf8a46589c0a5deb9f0545d916 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/__pycache__/term.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/__pycache__/util.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/__pycache__/util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5848c528a992c3d4f37e5e92de1f04cd8f3dcc90 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/__pycache__/util.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/__pycache__/warnings.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/__pycache__/warnings.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d5281057a9cb321cda8a1fc473a2c3533fab4bf Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/__pycache__/warnings.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/errors.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..6130cb683a25e4469f4cf81af1f63b32f0c57d62 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/links.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/links.py new file mode 100644 index 0000000000000000000000000000000000000000..7ff87cde68e779ab1d857a347dfbf6bb6445e74e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/term.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/term.py new file mode 100644 index 0000000000000000000000000000000000000000..aca821c58e5732bebfb305a161ed84cc97bd7bd6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/term.py @@ -0,0 +1,577 @@ +"""Global functions for interacting with the terminal for wandb. + +The functions termlog, termwarn and termerror print to stderr. + +The function terminput prints to stderr and reads from stdin. + +We print to stderr because wandb does not output any messages that are useful +to pipe to another program. Using stderr allows using wandb in a program that +*does* output pipe-able text. +""" + +from __future__ import annotations + +import contextlib +import logging +import os +import re +import shutil +import sys +import threading +from collections.abc import Iterator +from typing import TYPE_CHECKING, 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 NotATerminalError(Exception): + """The output device is not sufficiently capable for the operation.""" + + +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() or _is_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 _isatty(sys.stderr) + + +def _sys_stdin_isatty() -> bool: + """Returns sys.stdin.isatty(). + + Defined here for patching in tests. + """ + return _isatty(sys.stdin) + + +def _isatty(stream: object) -> bool: + """Returns true if the stream defines isatty and returns true for it. + + This is needed because some people patch `sys.stderr` / `sys.stdin` + with incompatible objects, e.g. a Logger. + + Args: + stream: An IO object like stdin or stderr. + """ + isatty = getattr(stream, "isatty", None) + + if not isatty or not callable(isatty): + return False + + try: + return bool(isatty()) + except TypeError: # if isatty has required arguments + return False + + +def _is_term_dumb() -> bool: + """Returns whether the TERM environment variable is set to 'dumb'. + + This is a convention to indicate that the terminal doesn't support + ANSI sequences like colors, clearing the screen and positioning the cursor. + """ + return os.getenv("TERM") == "dumb" + + +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, + ) + + +def _in_jupyter() -> bool: + """Returns True if we're in a Jupyter notebook.""" + # Lazy import to avoid circular imports. + from wandb.sdk.lib import ipython + + return ipython.in_jupyter() + + +def can_use_terminput() -> bool: + """Returns True if terminput won't raise a NotATerminalError.""" + if _silent or not _show_info or _is_term_dumb(): + return False + + from wandb import util + + # TODO: Verify the databricks check is still necessary. + # Originally added to fix WB-5264. + if util._is_databricks(): + return False + + # isatty() returns false in Jupyter, but it's OK to output ANSI color + # sequences and to read from stdin. + return _in_jupyter() or (_sys_stderr_isatty() and _sys_stdin_isatty()) + + +def terminput( + prompt: str, + *, + timeout: float | None = None, + hide: bool = False, +) -> str: + """Prompt the user for input. + + Args: + prompt: The prompt to display. The prompt is printed without a newline + and the cursor is positioned after the prompt's last character. + The prompt should end with whitespace. + timeout: A timeout after which to raise a TimeoutError. + Cannot be set if hide is True. + hide: If true, does not echo the characters typed by the user. + This is useful for passwords. + + Returns: + The text typed by the user before pressing the 'return' key. + + Raises: + TimeoutError: If a timeout was specified and expired. + NotATerminalError: If the output device is not capable, like if stderr + is redirected to a file, stdin is a pipe or closed, TERM=dumb is + set, or wandb is configured in 'silent' mode. + KeyboardInterrupt: If the user pressed Ctrl+C during the prompt. + """ + prefixed_prompt = f"{LOG_STRING}: {prompt}" + return _terminput(prefixed_prompt, timeout=timeout, hide=hide) + + +def confirm(prompt: str) -> bool: + """Prompt the user with a yes/no question. + + Args: + prompt: A prompt ending with a question mark (not whitespace), + like "Are you sure?". + + Returns: + The user's choice. + """ + prompt = f"{prompt} [y/n] " + while True: + answer = terminput(prompt).strip().lower() + + if answer in ("n", "no"): + return False + if answer in ("y", "yes"): + return True + + +def _terminput( + prefixed_prompt: str, + *, + timeout: float | None = None, + hide: bool = False, +) -> str: + """Implements terminput() and can be patched by tests.""" + if not can_use_terminput(): + raise NotATerminalError + + if hide and timeout is not None: + # Only click.prompt() can hide, and only timed_input can time out. + raise NotImplementedError + + if timeout is not None: + # Lazy import to avoid circular imports. + from wandb.sdk.lib.timed_input import timed_input + + try: + return timed_input( + prefixed_prompt, + timeout=timeout, + err=True, + jupyter=_in_jupyter(), + ) + except KeyboardInterrupt: + sys.stderr.write("\n") + raise + + try: + return click.prompt( + prefixed_prompt, + prompt_suffix="", + hide_input=hide, + err=True, + ) + except click.Abort: + sys.stderr.write("\n") + raise KeyboardInterrupt from None + + +class DynamicBlock: + """A handle to a changeable text area in the terminal.""" + + def __init__(self) -> None: + self._lines_to_print: list[str] = [] + self._num_lines_printed = 0 + + def set_text(self, text: str, prefix: bool = 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: str = "", + newline: bool = True, + repeat: bool = True, + prefix: bool = True, + silent: bool = False, + level: int = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/util.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/util.py new file mode 100644 index 0000000000000000000000000000000000000000..490c03ede2914bf634e6f8f6394ef8454490cae0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/util.py @@ -0,0 +1,57 @@ +from __future__ import annotations + +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) -> Error | None: + """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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/warnings.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..f956757b378de6f5481aeb467961013ad264f3a9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/errors/warnings.py @@ -0,0 +1,2 @@ +class WandbWarning(Warning): + """Base W&B Warning.""" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/filesync/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/filesync/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/filesync/dir_watcher.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/filesync/dir_watcher.py new file mode 100644 index 0000000000000000000000000000000000000000..d16980a7fe651d6ed97bd608edc45199fab06ab2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/filesync/dir_watcher.py @@ -0,0 +1,407 @@ +from __future__ import annotations + +import abc +import fnmatch +import glob +import logging +import os +import queue +import time +from collections.abc import Mapping, MutableMapping, MutableSet +from typing import TYPE_CHECKING, Any + +from wandb import util +from wandb.sdk.lib.filesystem 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.internal.file_pusher import FilePusher + from wandb.sdk.internal.settings_static import SettingsStatic + from wandb.sdk.lib.filesystem import PolicyName +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: float | None = 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: SettingsStatic | None = None, + *args: Any, + **kwargs: Any, + ) -> None: + super().__init__(file_path, save_name, file_pusher, *args, **kwargs) + self._last_uploaded_time: float | None = 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: float | None = 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: PathStr | None = 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) -> wd_api.EventEmitter | None: + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/filesync/stats.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/filesync/stats.py new file mode 100644 index 0000000000000000000000000000000000000000..d1b556c6b29f5c2b4f55ca5254430ad9c4e23826 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/filesync/stats.py @@ -0,0 +1,101 @@ +import threading +from collections.abc import MutableMapping +from typing import NamedTuple + +from wandb.sdk.lib import filenames + + +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 filenames.is_wandb_file(save_name): + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/filesync/step_checksum.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/filesync/step_checksum.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a04915af68204f16d27535876692491262a65a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/filesync/step_checksum.py @@ -0,0 +1,144 @@ +"""Batching file prepare requests to our API.""" + +from __future__ import annotations + +import concurrent.futures +import functools +import os +import queue +import shutil +import threading +from typing import TYPE_CHECKING, NamedTuple, 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: step_upload.OnRequestFinishFn | None + + +Event = ( + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/filesync/step_prepare.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/filesync/step_prepare.py new file mode 100644 index 0000000000000000000000000000000000000000..9860753077cdfdbc4bf979bdf2359891d0122935 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/filesync/step_prepare.py @@ -0,0 +1,171 @@ +"""Batching file prepare requests to our API.""" + +from __future__ import annotations + +import queue +import threading +import time +from collections.abc import Callable, Mapping, Sequence +from typing import TYPE_CHECKING, NamedTuple + +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: str | None + upload_headers: Sequence[str] + upload_id: str | None + storage_path: str | None + multipart_upload_urls: dict[int, str] | None + + +Request = 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: queue.Queue[Request] | None = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/filesync/step_upload.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/filesync/step_upload.py new file mode 100644 index 0000000000000000000000000000000000000000..4648aab1daf8e340d741af573e39d0d5a4d1b52e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/filesync/step_upload.py @@ -0,0 +1,281 @@ +"""Batching file prepare requests to our API.""" + +from __future__ import annotations + +import concurrent.futures +import logging +import queue +import sys +import threading +from collections.abc import Callable, MutableMapping, MutableSequence, MutableSet +from typing import TYPE_CHECKING, NamedTuple + +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: str | None + md5: str | None + copied: bool + save_fn: SaveFn | None + digest: str | None + + +class RequestCommitArtifact(NamedTuple): + artifact_id: str + finalize: bool + before_commit: PreCommitFn + result_future: concurrent.futures.Future[None] + + +class RequestFinish(NamedTuple): + callback: OnRequestFinishFn | None + + +class EventJobDone(NamedTuple): + job: RequestUpload + exc: BaseException | None + + +Event = 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: SettingsStatic | None = 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: Event | None + # 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/filesync/upload_job.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/filesync/upload_job.py new file mode 100644 index 0000000000000000000000000000000000000000..c9817bec9eddbcdc4b421a957200c5ad91e92fc7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/filesync/upload_job.py @@ -0,0 +1,145 @@ +from __future__ import annotations + +import logging +import os +from typing import TYPE_CHECKING + +import wandb +from wandb.analytics import get_sentry +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: str | None, + md5: str | None, + copied: bool, + save_fn: step_upload.SaveFn | None, + digest: str | None, + ) -> 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) + get_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) + get_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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/integration/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/integration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/mpmain/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/mpmain/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/mpmain/__main__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/mpmain/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..02e8a24d9fbce482e31cde126d8407586a61b3fd --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/mpmain/__main__.py @@ -0,0 +1 @@ +# This module is initialized after multiprocessing spawn diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/mpmain/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/mpmain/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d69ad39c77df3a6dd5caa1a456d251a3dc4fcd7a Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/mpmain/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/mpmain/__pycache__/__main__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/mpmain/__pycache__/__main__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79237db0c8dca5e34f460af1d9e16d59ef3ffa5c Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/mpmain/__pycache__/__main__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/old/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/old/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/old/core.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/old/core.py new file mode 100644 index 0000000000000000000000000000000000000000..15d6d5a410a9a2d843616d09b8cfdc0571b20fc0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/old/summary.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/old/summary.py new file mode 100644 index 0000000000000000000000000000000000000000..2e5eba49534dc705846f6dd766a7c720c475d57b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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.data_types.utils import val_to_json +from wandb.sdk.lib import filenames + +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, 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c49e40ac3ce6a7ffccd97c553a013bdd97fd305b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/bar.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/bar.py new file mode 100644 index 0000000000000000000000000000000000000000..21e6496df9e46a00204b78abb4c599ca0430a3c1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/confusion_matrix.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/confusion_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..c44f00da0d752f5bdee7f00f4a22d423b21cc3b6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/confusion_matrix.py @@ -0,0 +1,186 @@ +from __future__ import annotations + +from collections.abc import Sequence +from typing import TYPE_CHECKING, 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/custom_chart.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/custom_chart.py new file mode 100644 index 0000000000000000000000000000000000000000..62cd8784cdc63b2af264cd51ae7ebb80e7bddbbc --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/histogram.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/histogram.py new file mode 100644 index 0000000000000000000000000000000000000000..b62cb1142d94cbe59101d6ded8cc6a523c05d769 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/line.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/line.py new file mode 100644 index 0000000000000000000000000000000000000000..34857a4053ac3d699f447f927b7d6d0ea8d6ca14 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/line_series.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/line_series.py new file mode 100644 index 0000000000000000000000000000000000000000..baf099be208447fc9c568cd39576cf09cfca07e8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/line_series.py @@ -0,0 +1,174 @@ +from __future__ import annotations + +from collections.abc import Iterable +from typing import TYPE_CHECKING, Any + +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, strict=False)) + for x, y in zip(xx, yy, strict=False) + ] + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/pr_curve.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/pr_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..a1a8f6fb1c0314dc1a5aeb7d27063f3ccf0eeebc --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/pr_curve.py @@ -0,0 +1,187 @@ +from __future__ import annotations + +import numbers +from collections.abc import Iterable +from typing import TYPE_CHECKING, 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/roc_curve.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/roc_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..d045d1f4f6f9639dfdb147d9dbdc78cebd40356f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/roc_curve.py @@ -0,0 +1,164 @@ +from __future__ import annotations + +import numbers +from collections.abc import Sequence +from typing import TYPE_CHECKING + +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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/scatter.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/scatter.py new file mode 100644 index 0000000000000000000000000000000000000000..40e3d8033e2d6249554e3de56904add3ef30ffbd --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..60fa11df442c675542c5e391574905e5e8487dc5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/utils.py @@ -0,0 +1,182 @@ +from collections.abc 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") + ) and not isinstance( + v, + ( + Sequence, + Iterable, + np.ndarray, + np.generic, + pd.DataFrame, + pd.Series, + list, + ), + ): + # FIXME: do this individually + 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" and 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/viz.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/plot/viz.py new file mode 100644 index 0000000000000000000000000000000000000000..ea6be2f8805891b5d0c77b557c040a4377e9f4f9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/proto/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/proto/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/proto/generate-proto.sh b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/proto/generate-proto.sh new file mode 100644 index 0000000000000000000000000000000000000000..44a8f92ccd0342653082c999ef24b3fdd96dc72f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/proto/generate-proto.sh @@ -0,0 +1,82 @@ +#!/usr/bin/env bash +# Generate Python protobuf bindings using a specific protoc version. +# +# Usage: +# wandb/proto/generate-proto.sh +# +# Example: +# wandb/proto/generate-proto.sh 27.0 wandb/proto/v5 +# +# Protoc binaries are cached in .protoc// at the repo root. + +set -euo pipefail + +if [ $# -ne 2 ]; then + echo "Usage: $0 " >&2 + exit 1 +fi + +PROTOC_VER="$1" +OUT_DIR="$2" + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" +PROTOC_CACHE="$REPO_ROOT/.protoc" +PROTOC="$PROTOC_CACHE/$PROTOC_VER/bin/protoc" + +PROTO_FILES=( + wandb_base.proto + wandb_internal.proto + wandb_settings.proto + wandb_telemetry.proto + wandb_server.proto + wandb_sync.proto + wandb_api.proto +) + +# --------------------------------------------------------------------------- +# Ensure protoc is cached +# --------------------------------------------------------------------------- + +if [ ! -x "$PROTOC" ]; then + os="$(uname -s)" + arch="$(uname -m)" + if [ "$os" = "Darwin" ]; then + if [ "$arch" = "arm64" ]; then + os_arch="osx-aarch_64" + else + os_arch="osx-x86_64" + fi + else + os_arch="linux-x86_64" + fi + + echo "[INFO] Downloading protoc $PROTOC_VER..." + fname="protoc-${PROTOC_VER}-${os_arch}.zip" + url="https://github.com/protocolbuffers/protobuf/releases/download/v${PROTOC_VER}/${fname}" + + mkdir -p "$PROTOC_CACHE/$PROTOC_VER" + curl -fsSL -o "/tmp/${fname}" "$url" + unzip -qo "/tmp/${fname}" -d "$PROTOC_CACHE/$PROTOC_VER" + rm -f "/tmp/${fname}" +fi + +# --------------------------------------------------------------------------- +# Generate +# --------------------------------------------------------------------------- + +echo "[INFO] $("$PROTOC" --version) → $OUT_DIR" + +mkdir -p "$OUT_DIR" + +"$PROTOC" \ + -I "$REPO_ROOT" \ + "--python_out=$OUT_DIR" \ + "--pyi_out=$OUT_DIR" \ + "${PROTO_FILES[@]/#/$REPO_ROOT/wandb/proto/}" + +# protoc mirrors the import path inside OUT_DIR; move files up. +if [ -d "$OUT_DIR/wandb/proto" ]; then + mv -f "$OUT_DIR/wandb/proto/"*pb2* "$OUT_DIR/" + rm -rf "$OUT_DIR/wandb" +fi diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/proto/wandb_api_pb2.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/proto/wandb_api_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..37da07793bf4ba3dd80eeaf6b6db5b88938e66a5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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 == "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 * +elif protobuf_version == "7": + from wandb.proto.v7.wandb_api_pb2 import * +else: + raise ImportError( + "Failed to import protobufs for protobuf version" + f" {google.protobuf.__version__}. `wandb` only works with major" + " versions 4, 5, 6, and 7 of the protobuf package.", + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/proto/wandb_base_pb2.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/proto/wandb_base_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..d0eaf7f56bb73910e27f682e16d19d80f350eebf --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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 == "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 * +elif protobuf_version == "7": + from wandb.proto.v7.wandb_base_pb2 import * diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/proto/wandb_internal_pb2.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/proto/wandb_internal_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..7540a0625b68883c10fbf8420198585456ad6e0c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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 == "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 * +elif protobuf_version == "7": + from wandb.proto.v7.wandb_internal_pb2 import * +else: + raise ImportError( + "Failed to import protobufs for protobuf version" + f" {google.protobuf.__version__}. `wandb` only works with major" + " versions 4, 5, 6, and 7 of the protobuf package.", + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/proto/wandb_server_pb2.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/proto/wandb_server_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..2c4116007b127e336ef1c0f77c3f1ace9ab6691e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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 == "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 * +elif protobuf_version == "7": + from wandb.proto.v7.wandb_server_pb2 import * diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/proto/wandb_settings_pb2.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/proto/wandb_settings_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..2e4a0cd2653eec30427640508b9d38d1ca4aed73 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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 == "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 * +elif protobuf_version == "7": + from wandb.proto.v7.wandb_settings_pb2 import * diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/proto/wandb_sync_pb2.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/proto/wandb_sync_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..7fc0eae891e9b009d34bf675f3377300bdf7650b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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 == "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 * +elif protobuf_version == "7": + from wandb.proto.v7.wandb_sync_pb2 import * diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/proto/wandb_telemetry_pb2.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/proto/wandb_telemetry_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..367788443acf49d32537323ad6d28608ae9f2007 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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 == "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 * +elif protobuf_version == "7": + from wandb.proto.v7.wandb_telemetry_pb2 import * diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sandbox/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sandbox/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f8c31132cd324cee8f610b9a9d5a40c72df962a4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sandbox/__init__.py @@ -0,0 +1,21 @@ +from __future__ import annotations + +try: + import cwsandbox +except ImportError as exc: + raise ImportError( + "cwsandbox is not installed. Please install it with: pip install wandb[sandbox]" + ) from exc + +from cwsandbox import * # noqa: F403 +from cwsandbox import __all__ as cwsandbox_all + +# wandb specific overrides +from ._auth import _set_wandb_auth_mode +from ._secret import Secret + +_set_wandb_auth_mode() + +_HIDDEN = {"AuthHeaders", "set_auth_mode"} + +__all__ = [name for name in cwsandbox_all if name not in _HIDDEN] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sandbox/_auth.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sandbox/_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..20ff95611dc37fdb0a7bc150d2f226108b5c71d4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sandbox/_auth.py @@ -0,0 +1,77 @@ +from __future__ import annotations + +from collections.abc import Iterator +from contextlib import contextmanager +from contextvars import ContextVar + +from cwsandbox import AuthHeaders, CWSandboxAuthenticationError, set_auth_mode + +from wandb.errors import UsageError +from wandb.sdk import wandb_setup +from wandb.sdk.lib import wbauth + +_AUTH_MODE_NAME = "wandb" +_OVERRIDE_UNSET = object() +_entity_override: ContextVar[object | str] = ContextVar( + "wandb_sandbox_entity_override", + default=_OVERRIDE_UNSET, +) + + +def _set_wandb_auth_mode() -> None: + """Install W&B as the active cwsandbox auth mode for this process. + + NOTE: This means the original cwsandbox auth using sandbox api key no longer works. + """ + set_auth_mode(_AUTH_MODE_NAME, _resolve_wandb_sdk_auth) + + +@contextmanager +def override_sandbox_entity( + entity: str | None = None, +) -> Iterator[None]: + """Temporarily override the sandbox entity for sandbox auth. + + Passing `None` means using the default resolve logic from run + and setting. Only used by the cli to set entity via --entity. + """ + if entity is None: + yield + return + + entity_token = _entity_override.set(entity) + try: + yield + finally: + _entity_override.reset(entity_token) + + +def _resolve_wandb_sdk_auth() -> AuthHeaders: + settings = wandb_setup.singleton().settings + host = wbauth.HostUrl(settings.base_url, app_url=settings.app_url) + auth = wbauth.authenticate_session(host=host, source="sandbox", no_offline=True) + if auth is None: + raise CWSandboxAuthenticationError( + "wandb.sandbox could not resolve W&B credentials for sandbox auth." + ) + if not isinstance(auth, wbauth.AuthApiKey): + raise UsageError("wandb.sandbox currently supports only W&B user API-key auth.") + + metadata: list[tuple[str, str]] = [("x-wandb-api-key", auth.api_key)] + # Both entity and project are optional. + # entity will use the default entity user set in web UI. + # project will use/create 'sandbox' project automatically. + entity = settings.entity + # entity can be set by --entity cli flag via override_sandbox_entity + entity_override = _entity_override.get() + if isinstance(entity_override, str): + entity = entity_override + if entity: + metadata.append(("x-entity-id", entity)) + if settings.project: + metadata.append(("x-project-name", settings.project)) + + return AuthHeaders( + headers={key: value for key, value in metadata}, + strategy="wandb_api_key", + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sandbox/_secret.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sandbox/_secret.py new file mode 100644 index 0000000000000000000000000000000000000000..acce727c7ca765ef8555e625b8a561198b926d2b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sandbox/_secret.py @@ -0,0 +1,14 @@ +from __future__ import annotations + +from dataclasses import dataclass + +from cwsandbox import Secret as _BaseSecret + +WANDB_SECRET_STORE = "wandb-team-secrets" + + +@dataclass(frozen=True, kw_only=True) +class Secret(_BaseSecret): + """W&B sandbox secret with a default team secret store.""" + + store: str = WANDB_SECRET_STORE diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aca29299d736832f386133698d85885bdbe36c38 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__init__.py @@ -0,0 +1,36 @@ +"""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_watch import _unwatch, _watch diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edea94e9a81d4bc34f5eb02276c95f3ca635cdbd Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_alerts.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_alerts.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfea87a52b1f6844526a10a872fc57b1a963395c Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_alerts.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_config.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2943055c0ca151d2817468003089787623a75ea Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_config.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_helper.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_helper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c3b2e65876128664f0d9670de069a1bd6a205fd Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_helper.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_init.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_init.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f4499242e2130787ff1d79e89778e1c0eb8c9be Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_init.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_login.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_login.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b994f229e338b20d5c6b31d7aab00bf50154012 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_login.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_metric.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_metric.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..292b937cc259c0604612ca8728884b7e35cf015d Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_metric.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_require.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_require.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19f7bac26687eb06a8c190e002632172f5da49f1 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_require.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_require_helpers.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_require_helpers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..518794f921f453edf9caa79f702f2aac0400559d Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_require_helpers.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_settings.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_settings.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a34d5067317fb3f1b37417094ddb581b11468016 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_settings.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_setup.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_setup.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd7414861abfed166db9e43d35b4e75f33661ce8 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_setup.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_summary.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_summary.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31785adfdfccb3f59a82cfcb11e3d2d68d2df608 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_summary.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_sweep.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_sweep.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43b528818720142827c577f7f0c1e3ebe5b7e1b8 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_sweep.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_watch.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_watch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c68a7d4d9031bdc8ce5c66a658864792c46294c5 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/__pycache__/wandb_watch.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_factories.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_factories.py new file mode 100644 index 0000000000000000000000000000000000000000..00c02027d776fcb88f86b2adb2722c0332b30107 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_factories.py @@ -0,0 +1,14 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from ._models.storage import StoragePolicyConfig +from .storage_policies import WandbStoragePolicy + +if TYPE_CHECKING: + from .storage_policy import StoragePolicy + + +def make_storage_policy(region: str | None = None) -> StoragePolicy: + """Returns the default `StoragePolicy` for the current environment.""" + return WandbStoragePolicy(config=StoragePolicyConfig.from_env(region=region)) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..88d2beda5aa42a416b780d7190fc5219005d6134 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/__init__.py @@ -0,0 +1,304 @@ +# Generated by ariadne-codegen + +__all__ = [ + "ADD_ALIASES_GQL", + "ADD_ARTIFACT_COLLECTION_TAGS_GQL", + "ARTIFACT_BY_ID_GQL", + "ARTIFACT_BY_NAME_GQL", + "ARTIFACT_COLLECTION_ALIASES_GQL", + "ARTIFACT_CREATED_BY_GQL", + "ARTIFACT_MEMBERSHIP_BY_NAME_GQL", + "ARTIFACT_TYPE_ARTIFACT_COLLECTIONS_GQL", + "ARTIFACT_TYPE_GQL", + "ARTIFACT_USED_BY_GQL", + "CREATE_REGISTRY_MEMBERS_GQL", + "DELETE_ALIASES_GQL", + "DELETE_ARTIFACT_COLLECTION_TAGS_GQL", + "DELETE_ARTIFACT_GQL", + "DELETE_ARTIFACT_PORTFOLIO_GQL", + "DELETE_ARTIFACT_SEQUENCE_GQL", + "DELETE_REGISTRY_GQL", + "DELETE_REGISTRY_MEMBERS_GQL", + "FETCH_ARTIFACT_MANIFEST_GQL", + "FETCH_LINKED_ARTIFACTS_GQL", + "FETCH_ORG_ENTITY_FROM_ORGANIZATION_GQL", + "FETCH_ORG_INFO_FROM_ENTITY_GQL", + "FETCH_REGISTRIES_GQL", + "FETCH_REGISTRY_GQL", + "GET_ARTIFACT_FILES_GQL", + "GET_ARTIFACT_FILE_URLS_GQL", + "GET_ARTIFACT_MEMBERSHIP_FILES_GQL", + "GET_ARTIFACT_MEMBERSHIP_FILE_URLS_GQL", + "LINK_ARTIFACT_GQL", + "PROJECT_ARTIFACTS_GQL", + "PROJECT_ARTIFACT_COLLECTIONS_GQL", + "PROJECT_ARTIFACT_COLLECTION_GQL", + "PROJECT_ARTIFACT_TYPES_GQL", + "PROJECT_ARTIFACT_TYPE_GQL", + "REGISTRY_COLLECTIONS_GQL", + "REGISTRY_TEAM_MEMBERS_GQL", + "REGISTRY_USER_MEMBERS_GQL", + "REGISTRY_VERSIONS_GQL", + "RENAME_REGISTRY_GQL", + "RUN_INPUT_ARTIFACTS_GQL", + "RUN_OUTPUT_ARTIFACTS_GQL", + "UNLINK_ARTIFACT_GQL", + "UPDATE_ARTIFACT_GQL", + "UPDATE_ARTIFACT_PORTFOLIO_GQL", + "UPDATE_ARTIFACT_SEQUENCE_GQL", + "UPDATE_ARTIFACT_SEQUENCE_TYPE_GQL", + "UPDATE_TEAM_REGISTRY_ROLE_GQL", + "UPDATE_USER_REGISTRY_ROLE_GQL", + "UPSERT_REGISTRY_GQL", + "DeleteArtifactSequence", + "DeleteArtifactPortfolio", + "UpdateArtifactSequence", + "UpdateArtifactPortfolio", + "UpdateArtifactSequenceType", + "AddArtifactCollectionTags", + "DeleteArtifactCollectionTags", + "ArtifactTypeArtifactCollections", + "ProjectArtifactCollections", + "ProjectArtifactCollection", + "ArtifactCollectionAliases", + "GetArtifactFiles", + "GetArtifactMembershipFiles", + "GetArtifactFileUrls", + "GetArtifactMembershipFileUrls", + "ProjectArtifactTypes", + "ProjectArtifactType", + "ProjectArtifacts", + "RunOutputArtifacts", + "RunInputArtifacts", + "FetchLinkedArtifacts", + "FetchArtifactManifest", + "ArtifactByID", + "ArtifactByName", + "ArtifactMembershipByName", + "ArtifactUsedBy", + "ArtifactCreatedBy", + "ArtifactType", + "AddAliases", + "DeleteAliases", + "UpdateArtifact", + "DeleteArtifact", + "LinkArtifact", + "UnlinkArtifact", + "FetchOrgInfoFromEntity", + "FetchOrgEntityFromOrganization", + "RegistryVersions", + "RegistryCollections", + "FetchRegistry", + "FetchRegistries", + "RenameRegistry", + "UpsertRegistry", + "DeleteRegistry", + "RegistryUserMembers", + "RegistryTeamMembers", + "CreateRegistryMembers", + "DeleteRegistryMembers", + "UpdateUserRegistryRole", + "UpdateTeamRegistryRole", + "AddAliasesInput", + "ArtifactAliasInput", + "ArtifactCollectionAliasInput", + "ArtifactTypeInput", + "CreateArtifactCollectionTagAssignmentsInput", + "CreateProjectMembersInput", + "DeleteAliasesInput", + "DeleteArtifactCollectionTagAssignmentsInput", + "DeleteArtifactInput", + "DeleteProjectMembersInput", + "LinkArtifactInput", + "MoveArtifactSequenceInput", + "ProjectIconInput", + "RateLimitsInput", + "RenameProjectInput", + "TagInput", + "UnlinkArtifactInput", + "UpdateArtifactInput", + "UpdateArtifactPortfolioInput", + "UpdateArtifactSequenceInput", + "UpdateProjectMemberInput", + "UpdateProjectTeamMemberInput", + "UpsertModelInput", + "ArtifactAliasFragment", + "ArtifactCollectionFragment", + "ArtifactFragment", + "ArtifactMembershipFragment", + "ArtifactPortfolioTypeFields", + "ArtifactSequenceTypeFields", + "ArtifactTypeFragment", + "CollectionInfoFragment", + "DeferredManifestFragment", + "FileFragment", + "FileWithUrlFragment", + "OrgInfoFragment", + "PageInfoFragment", + "ProjectInfoFragment", + "RegistryCollectionFragment", + "RegistryFragment", + "RegistryRoleFragment", + "RunInfoFragment", + "SourceCollectionInfoFragment", + "TagFragment", + "TeamFragment", + "TeamMemberFragment", + "TeamRegistryMemberFragment", + "UserRegistryMemberFragment", + "ArtifactCollectionState", + "ArtifactCollectionType", + "ArtifactState", +] +from .add_aliases import AddAliases +from .add_artifact_collection_tags import AddArtifactCollectionTags +from .artifact_by_id import ArtifactByID +from .artifact_by_name import ArtifactByName +from .artifact_collection_aliases import ArtifactCollectionAliases +from .artifact_created_by import ArtifactCreatedBy +from .artifact_membership_by_name import ArtifactMembershipByName +from .artifact_type import ArtifactType +from .artifact_type_artifact_collections import ArtifactTypeArtifactCollections +from .artifact_used_by import ArtifactUsedBy +from .create_registry_members import CreateRegistryMembers +from .delete_aliases import DeleteAliases +from .delete_artifact import DeleteArtifact +from .delete_artifact_collection_tags import DeleteArtifactCollectionTags +from .delete_artifact_portfolio import DeleteArtifactPortfolio +from .delete_artifact_sequence import DeleteArtifactSequence +from .delete_registry import DeleteRegistry +from .delete_registry_members import DeleteRegistryMembers +from .enums import ArtifactCollectionState, ArtifactCollectionType, ArtifactState +from .fetch_artifact_manifest import FetchArtifactManifest +from .fetch_linked_artifacts import FetchLinkedArtifacts +from .fetch_org_entity_from_organization import FetchOrgEntityFromOrganization +from .fetch_org_info_from_entity import FetchOrgInfoFromEntity +from .fetch_registries import FetchRegistries +from .fetch_registry import FetchRegistry +from .fragments import ( + ArtifactAliasFragment, + ArtifactCollectionFragment, + ArtifactFragment, + ArtifactMembershipFragment, + ArtifactPortfolioTypeFields, + ArtifactSequenceTypeFields, + ArtifactTypeFragment, + CollectionInfoFragment, + DeferredManifestFragment, + FileFragment, + FileWithUrlFragment, + OrgInfoFragment, + PageInfoFragment, + ProjectInfoFragment, + RegistryCollectionFragment, + RegistryFragment, + RegistryRoleFragment, + RunInfoFragment, + SourceCollectionInfoFragment, + TagFragment, + TeamFragment, + TeamMemberFragment, + TeamRegistryMemberFragment, + UserRegistryMemberFragment, +) +from .get_artifact_file_urls import GetArtifactFileUrls +from .get_artifact_files import GetArtifactFiles +from .get_artifact_membership_file_urls import GetArtifactMembershipFileUrls +from .get_artifact_membership_files import GetArtifactMembershipFiles +from .input_types import ( + AddAliasesInput, + ArtifactAliasInput, + ArtifactCollectionAliasInput, + ArtifactTypeInput, + CreateArtifactCollectionTagAssignmentsInput, + CreateProjectMembersInput, + DeleteAliasesInput, + DeleteArtifactCollectionTagAssignmentsInput, + DeleteArtifactInput, + DeleteProjectMembersInput, + LinkArtifactInput, + MoveArtifactSequenceInput, + ProjectIconInput, + RateLimitsInput, + RenameProjectInput, + TagInput, + UnlinkArtifactInput, + UpdateArtifactInput, + UpdateArtifactPortfolioInput, + UpdateArtifactSequenceInput, + UpdateProjectMemberInput, + UpdateProjectTeamMemberInput, + UpsertModelInput, +) +from .link_artifact import LinkArtifact +from .operations import ( + ADD_ALIASES_GQL, + ADD_ARTIFACT_COLLECTION_TAGS_GQL, + ARTIFACT_BY_ID_GQL, + ARTIFACT_BY_NAME_GQL, + ARTIFACT_COLLECTION_ALIASES_GQL, + ARTIFACT_CREATED_BY_GQL, + ARTIFACT_MEMBERSHIP_BY_NAME_GQL, + ARTIFACT_TYPE_ARTIFACT_COLLECTIONS_GQL, + ARTIFACT_TYPE_GQL, + ARTIFACT_USED_BY_GQL, + CREATE_REGISTRY_MEMBERS_GQL, + DELETE_ALIASES_GQL, + DELETE_ARTIFACT_COLLECTION_TAGS_GQL, + DELETE_ARTIFACT_GQL, + DELETE_ARTIFACT_PORTFOLIO_GQL, + DELETE_ARTIFACT_SEQUENCE_GQL, + DELETE_REGISTRY_GQL, + DELETE_REGISTRY_MEMBERS_GQL, + FETCH_ARTIFACT_MANIFEST_GQL, + FETCH_LINKED_ARTIFACTS_GQL, + FETCH_ORG_ENTITY_FROM_ORGANIZATION_GQL, + FETCH_ORG_INFO_FROM_ENTITY_GQL, + FETCH_REGISTRIES_GQL, + FETCH_REGISTRY_GQL, + GET_ARTIFACT_FILE_URLS_GQL, + GET_ARTIFACT_FILES_GQL, + GET_ARTIFACT_MEMBERSHIP_FILE_URLS_GQL, + GET_ARTIFACT_MEMBERSHIP_FILES_GQL, + LINK_ARTIFACT_GQL, + PROJECT_ARTIFACT_COLLECTION_GQL, + PROJECT_ARTIFACT_COLLECTIONS_GQL, + PROJECT_ARTIFACT_TYPE_GQL, + PROJECT_ARTIFACT_TYPES_GQL, + PROJECT_ARTIFACTS_GQL, + REGISTRY_COLLECTIONS_GQL, + REGISTRY_TEAM_MEMBERS_GQL, + REGISTRY_USER_MEMBERS_GQL, + REGISTRY_VERSIONS_GQL, + RENAME_REGISTRY_GQL, + RUN_INPUT_ARTIFACTS_GQL, + RUN_OUTPUT_ARTIFACTS_GQL, + UNLINK_ARTIFACT_GQL, + UPDATE_ARTIFACT_GQL, + UPDATE_ARTIFACT_PORTFOLIO_GQL, + UPDATE_ARTIFACT_SEQUENCE_GQL, + UPDATE_ARTIFACT_SEQUENCE_TYPE_GQL, + UPDATE_TEAM_REGISTRY_ROLE_GQL, + UPDATE_USER_REGISTRY_ROLE_GQL, + UPSERT_REGISTRY_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_team_members import RegistryTeamMembers +from .registry_user_members import RegistryUserMembers +from .registry_versions import RegistryVersions +from .rename_registry import RenameRegistry +from .run_input_artifacts import RunInputArtifacts +from .run_output_artifacts import RunOutputArtifacts +from .unlink_artifact import UnlinkArtifact +from .update_artifact import UpdateArtifact +from .update_artifact_portfolio import UpdateArtifactPortfolio +from .update_artifact_sequence import UpdateArtifactSequence +from .update_artifact_sequence_type import UpdateArtifactSequenceType +from .update_team_registry_role import UpdateTeamRegistryRole +from .update_user_registry_role import UpdateUserRegistryRole +from .upsert_registry import UpsertRegistry diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/add_aliases.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/add_aliases.py new file mode 100644 index 0000000000000000000000000000000000000000..4cd56f6dcf18158d6433058edf1181175db555e4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/add_aliases.py @@ -0,0 +1,19 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/artifacts/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLResult + + +class AddAliases(GQLResult): + result: Optional[AddAliasesResult] + + +class AddAliasesResult(GQLResult): + success: bool + + +AddAliases.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/add_artifact_collection_tags.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/add_artifact_collection_tags.py new file mode 100644 index 0000000000000000000000000000000000000000..f6f7a5177384e14933c59f457040980bfcdea940 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/add_artifact_collection_tags.py @@ -0,0 +1,22 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/artifacts/ + +from __future__ import annotations + +from typing import List, Optional + +from wandb._pydantic import GQLResult + +from .fragments import TagFragment + + +class AddArtifactCollectionTags(GQLResult): + result: Optional[AddArtifactCollectionTagsResult] + + +class AddArtifactCollectionTagsResult(GQLResult): + tags: List[TagFragment] + + +AddArtifactCollectionTags.model_rebuild() +AddArtifactCollectionTagsResult.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_by_id.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_by_id.py new file mode 100644 index 0000000000000000000000000000000000000000..06560324edcddc0f41e92e6282654b728b4e949a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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 GQLResult + +from .fragments import ArtifactFragment + + +class ArtifactByID(GQLResult): + artifact: Optional[ArtifactFragment] + + +ArtifactByID.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_by_name.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_by_name.py new file mode 100644 index 0000000000000000000000000000000000000000..9eda890a16997959f505511b0ea63ac29025af9b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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 GQLResult + +from .fragments import ArtifactFragment + + +class ArtifactByName(GQLResult): + project: Optional[ArtifactByNameProject] + + +class ArtifactByNameProject(GQLResult): + artifact: Optional[ArtifactFragment] + + +ArtifactByName.model_rebuild() +ArtifactByNameProject.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_collection_aliases.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_collection_aliases.py new file mode 100644 index 0000000000000000000000000000000000000000..f17038fd47e360aa26d2ffd91d49f8a11b0f2dbe --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_collection_aliases.py @@ -0,0 +1,40 @@ +# 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 GQLResult, Typename + +from .fragments import ArtifactAliasFragment, PageInfoFragment + + +class ArtifactCollectionAliases(GQLResult): + artifact_collection: Optional[ArtifactCollectionAliasesArtifactCollection] = Field( + alias="artifactCollection" + ) + + +class ArtifactCollectionAliasesArtifactCollection(GQLResult): + typename__: Typename[ + Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"] + ] + aliases: ArtifactCollectionAliasesArtifactCollectionAliases + + +class ArtifactCollectionAliasesArtifactCollectionAliases(GQLResult): + page_info: PageInfoFragment = Field(alias="pageInfo") + edges: List[ArtifactCollectionAliasesArtifactCollectionAliasesEdges] + + +class ArtifactCollectionAliasesArtifactCollectionAliasesEdges(GQLResult): + node: Optional[ArtifactAliasFragment] + + +ArtifactCollectionAliases.model_rebuild() +ArtifactCollectionAliasesArtifactCollection.model_rebuild() +ArtifactCollectionAliasesArtifactCollectionAliases.model_rebuild() +ArtifactCollectionAliasesArtifactCollectionAliasesEdges.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_created_by.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_created_by.py new file mode 100644 index 0000000000000000000000000000000000000000..c80a8576330aa314adad00e563aa26ee0c7dde9f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_created_by.py @@ -0,0 +1,33 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/artifacts/ + +from __future__ import annotations + +from typing import Annotated, Literal, Optional, Union + +from pydantic import Field + +from wandb._pydantic import GQLResult, Typename + +from .fragments import RunInfoFragment + + +class ArtifactCreatedBy(GQLResult): + artifact: Optional[ArtifactCreatedByArtifact] + + +class ArtifactCreatedByArtifact(GQLResult): + created_by: Optional[ + Annotated[ + Union[RunInfoFragment, ArtifactCreatedByArtifactCreatedByUser], + Field(discriminator="typename__"), + ] + ] = Field(alias="createdBy") + + +class ArtifactCreatedByArtifactCreatedByUser(GQLResult): + typename__: Typename[Literal["User"]] + + +ArtifactCreatedBy.model_rebuild() +ArtifactCreatedByArtifact.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_membership_by_name.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_membership_by_name.py new file mode 100644 index 0000000000000000000000000000000000000000..a5316ba51312e609306c9a157d2c179e7f8fbdd2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_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 GQLResult + +from .fragments import ArtifactMembershipFragment + + +class ArtifactMembershipByName(GQLResult): + project: Optional[ArtifactMembershipByNameProject] + + +class ArtifactMembershipByNameProject(GQLResult): + artifact_collection_membership: Optional[ArtifactMembershipFragment] = Field( + alias="artifactCollectionMembership" + ) + + +ArtifactMembershipByName.model_rebuild() +ArtifactMembershipByNameProject.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_type.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_type.py new file mode 100644 index 0000000000000000000000000000000000000000..94bd303c5e30f506c07dc3f8fb9289e9fb833d41 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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 GQLResult + + +class ArtifactType(GQLResult): + project: Optional[ArtifactTypeProject] + + +class ArtifactTypeProject(GQLResult): + artifact: Optional[ArtifactTypeProjectArtifact] + + +class ArtifactTypeProjectArtifact(GQLResult): + artifact_type: ArtifactTypeProjectArtifactArtifactType = Field(alias="artifactType") + + +class ArtifactTypeProjectArtifactArtifactType(GQLResult): + name: str + + +ArtifactType.model_rebuild() +ArtifactTypeProject.model_rebuild() +ArtifactTypeProjectArtifact.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_type_artifact_collections.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_type_artifact_collections.py new file mode 100644 index 0000000000000000000000000000000000000000..bc8526623da49291427710c7221f658535d38479 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_type_artifact_collections.py @@ -0,0 +1,49 @@ +# 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 GQLResult + +from .fragments import ArtifactCollectionFragment, PageInfoFragment + + +class ArtifactTypeArtifactCollections(GQLResult): + project: Optional[ArtifactTypeArtifactCollectionsProject] + + +class ArtifactTypeArtifactCollectionsProject(GQLResult): + artifact_type: Optional[ArtifactTypeArtifactCollectionsProjectArtifactType] = Field( + alias="artifactType" + ) + + +class ArtifactTypeArtifactCollectionsProjectArtifactType(GQLResult): + artifact_collections: Optional[ + ArtifactTypeArtifactCollectionsProjectArtifactTypeArtifactCollections + ] = Field(alias="artifactCollections") + + +class ArtifactTypeArtifactCollectionsProjectArtifactTypeArtifactCollections(GQLResult): + total_count: int = Field(alias="totalCount") + page_info: PageInfoFragment = Field(alias="pageInfo") + edges: List[ + ArtifactTypeArtifactCollectionsProjectArtifactTypeArtifactCollectionsEdges + ] + + +class ArtifactTypeArtifactCollectionsProjectArtifactTypeArtifactCollectionsEdges( + GQLResult +): + node: Optional[ArtifactCollectionFragment] + + +ArtifactTypeArtifactCollections.model_rebuild() +ArtifactTypeArtifactCollectionsProject.model_rebuild() +ArtifactTypeArtifactCollectionsProjectArtifactType.model_rebuild() +ArtifactTypeArtifactCollectionsProjectArtifactTypeArtifactCollections.model_rebuild() +ArtifactTypeArtifactCollectionsProjectArtifactTypeArtifactCollectionsEdges.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_used_by.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_used_by.py new file mode 100644 index 0000000000000000000000000000000000000000..15102b9ffa4b31007b5d5a98e893a5f3cac3e650 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/artifact_used_by.py @@ -0,0 +1,34 @@ +# 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 GQLResult + +from .fragments import RunInfoFragment + + +class ArtifactUsedBy(GQLResult): + artifact: Optional[ArtifactUsedByArtifact] + + +class ArtifactUsedByArtifact(GQLResult): + used_by: ArtifactUsedByArtifactUsedBy = Field(alias="usedBy") + + +class ArtifactUsedByArtifactUsedBy(GQLResult): + edges: List[ArtifactUsedByArtifactUsedByEdges] + + +class ArtifactUsedByArtifactUsedByEdges(GQLResult): + node: RunInfoFragment + + +ArtifactUsedBy.model_rebuild() +ArtifactUsedByArtifact.model_rebuild() +ArtifactUsedByArtifactUsedBy.model_rebuild() +ArtifactUsedByArtifactUsedByEdges.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/create_registry_members.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/create_registry_members.py new file mode 100644 index 0000000000000000000000000000000000000000..ea5dec8f778d309fc59f1e22f4af751890c8ef93 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/create_registry_members.py @@ -0,0 +1,19 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/artifacts/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLResult + + +class CreateRegistryMembers(GQLResult): + result: Optional[CreateRegistryMembersResult] + + +class CreateRegistryMembersResult(GQLResult): + success: bool + + +CreateRegistryMembers.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_aliases.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_aliases.py new file mode 100644 index 0000000000000000000000000000000000000000..a11c25db4fd19dc65de9bcf0c8bd60627e65ad41 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_aliases.py @@ -0,0 +1,19 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/artifacts/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLResult + + +class DeleteAliases(GQLResult): + result: Optional[DeleteAliasesResult] + + +class DeleteAliasesResult(GQLResult): + success: bool + + +DeleteAliases.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact.py new file mode 100644 index 0000000000000000000000000000000000000000..f2be29cc181eb7a8078206ba6653b1acaf6225ac --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact.py @@ -0,0 +1,24 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/artifacts/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLId, GQLResult + + +class DeleteArtifact(GQLResult): + result: Optional[DeleteArtifactResult] + + +class DeleteArtifactResult(GQLResult): + artifact: DeleteArtifactResultArtifact + + +class DeleteArtifactResultArtifact(GQLResult): + id: GQLId + + +DeleteArtifact.model_rebuild() +DeleteArtifactResult.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact_collection_tags.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact_collection_tags.py new file mode 100644 index 0000000000000000000000000000000000000000..1c9e6462fb72c42d49cd0827947304abc5dafdca --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact_collection_tags.py @@ -0,0 +1,19 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/artifacts/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLResult + + +class DeleteArtifactCollectionTags(GQLResult): + result: Optional[DeleteArtifactCollectionTagsResult] + + +class DeleteArtifactCollectionTagsResult(GQLResult): + success: bool + + +DeleteArtifactCollectionTags.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact_portfolio.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact_portfolio.py new file mode 100644 index 0000000000000000000000000000000000000000..74dd1d024a0cfa38cc3ef2c44d274c0614dedd4c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact_portfolio.py @@ -0,0 +1,33 @@ +# 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 GQLResult, Typename + +from .enums import ArtifactCollectionState + + +class DeleteArtifactPortfolio(GQLResult): + result: Optional[DeleteArtifactPortfolioResult] + + +class DeleteArtifactPortfolioResult(GQLResult): + artifact_collection: DeleteArtifactPortfolioResultArtifactCollection = Field( + alias="artifactCollection" + ) + + +class DeleteArtifactPortfolioResultArtifactCollection(GQLResult): + typename__: Typename[ + Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"] + ] + state: ArtifactCollectionState + + +DeleteArtifactPortfolio.model_rebuild() +DeleteArtifactPortfolioResult.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact_sequence.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact_sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..3f1166cf8c047c17c4654e052d87f173ac3fe35d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_artifact_sequence.py @@ -0,0 +1,33 @@ +# 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 GQLResult, Typename + +from .enums import ArtifactCollectionState + + +class DeleteArtifactSequence(GQLResult): + result: Optional[DeleteArtifactSequenceResult] + + +class DeleteArtifactSequenceResult(GQLResult): + artifact_collection: DeleteArtifactSequenceResultArtifactCollection = Field( + alias="artifactCollection" + ) + + +class DeleteArtifactSequenceResultArtifactCollection(GQLResult): + typename__: Typename[ + Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"] + ] + state: ArtifactCollectionState + + +DeleteArtifactSequence.model_rebuild() +DeleteArtifactSequenceResult.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_registry.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..679e61f0be859d80a595bcb474b99f147e28447c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_registry.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 GQLResult + + +class DeleteRegistry(GQLResult): + delete_model: Optional[DeleteRegistryDeleteModel] = Field(alias="deleteModel") + + +class DeleteRegistryDeleteModel(GQLResult): + success: Optional[bool] + + +DeleteRegistry.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_registry_members.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_registry_members.py new file mode 100644 index 0000000000000000000000000000000000000000..05ca21157f4f310d31acb8064c993fe1bfcf5313 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/delete_registry_members.py @@ -0,0 +1,19 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/artifacts/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLResult + + +class DeleteRegistryMembers(GQLResult): + result: Optional[DeleteRegistryMembersResult] + + +class DeleteRegistryMembersResult(GQLResult): + success: bool + + +DeleteRegistryMembers.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/enums.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..6c50a5822ab917ebb2e580d3c5d64b39813bd820 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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 ArtifactCollectionState(str, Enum): + DELETED = "DELETED" + READY = "READY" + + +class ArtifactCollectionType(str, Enum): + PORTFOLIO = "PORTFOLIO" + SEQUENCE = "SEQUENCE" + + +class ArtifactState(str, Enum): + COMMITTED = "COMMITTED" + DELETED = "DELETED" + PENDING = "PENDING" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_artifact_manifest.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_artifact_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..f3b98e48527b4cd35ee6114bd7d5acbc50c5bb93 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_artifact_manifest.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 GQLResult + +from .fragments import DeferredManifestFragment + + +class FetchArtifactManifest(GQLResult): + artifact: Optional[FetchArtifactManifestArtifact] + + +class FetchArtifactManifestArtifact(GQLResult): + current_manifest: Optional[DeferredManifestFragment] = Field( + alias="currentManifest" + ) + + +FetchArtifactManifest.model_rebuild() +FetchArtifactManifestArtifact.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_linked_artifacts.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_linked_artifacts.py new file mode 100644 index 0000000000000000000000000000000000000000..2d150d028206f22ef4c6f5135f2894c563f8adad --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_linked_artifacts.py @@ -0,0 +1,45 @@ +# 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 GQLResult + +from .fragments import ArtifactAliasFragment, CollectionInfoFragment + + +class FetchLinkedArtifacts(GQLResult): + artifact: Optional[FetchLinkedArtifactsArtifact] + + +class FetchLinkedArtifactsArtifact(GQLResult): + artifact_memberships: FetchLinkedArtifactsArtifactArtifactMemberships = Field( + alias="artifactMemberships" + ) + + +class FetchLinkedArtifactsArtifactArtifactMemberships(GQLResult): + edges: List[FetchLinkedArtifactsArtifactArtifactMembershipsEdges] + + +class FetchLinkedArtifactsArtifactArtifactMembershipsEdges(GQLResult): + node: Optional[FetchLinkedArtifactsArtifactArtifactMembershipsEdgesNode] + + +class FetchLinkedArtifactsArtifactArtifactMembershipsEdgesNode(GQLResult): + version_index: Optional[int] = Field(alias="versionIndex") + aliases: List[ArtifactAliasFragment] + artifact_collection: Optional[CollectionInfoFragment] = Field( + alias="artifactCollection" + ) + + +FetchLinkedArtifacts.model_rebuild() +FetchLinkedArtifactsArtifact.model_rebuild() +FetchLinkedArtifactsArtifactArtifactMemberships.model_rebuild() +FetchLinkedArtifactsArtifactArtifactMembershipsEdges.model_rebuild() +FetchLinkedArtifactsArtifactArtifactMembershipsEdgesNode.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_org_entity_from_organization.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_org_entity_from_organization.py new file mode 100644 index 0000000000000000000000000000000000000000..08490b033f277d7000471cd2b0e55debe59ba01c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_org_entity_from_organization.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 GQLResult + + +class FetchOrgEntityFromOrganization(GQLResult): + organization: Optional[FetchOrgEntityFromOrganizationOrganization] + + +class FetchOrgEntityFromOrganizationOrganization(GQLResult): + org_entity: Optional[FetchOrgEntityFromOrganizationOrganizationOrgEntity] = Field( + alias="orgEntity" + ) + + +class FetchOrgEntityFromOrganizationOrganizationOrgEntity(GQLResult): + name: str + + +FetchOrgEntityFromOrganization.model_rebuild() +FetchOrgEntityFromOrganizationOrganization.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_org_info_from_entity.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_org_info_from_entity.py new file mode 100644 index 0000000000000000000000000000000000000000..3b00f6399307fd82c559cd4f8d3cd517164a0421 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_org_info_from_entity.py @@ -0,0 +1,28 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/artifacts/ + +from __future__ import annotations + +from typing import List, Optional + +from wandb._pydantic import GQLResult + +from .fragments import OrgInfoFragment + + +class FetchOrgInfoFromEntity(GQLResult): + entity: Optional[FetchOrgInfoFromEntityEntity] + + +class FetchOrgInfoFromEntityEntity(GQLResult): + organization: Optional[OrgInfoFragment] + user: Optional[FetchOrgInfoFromEntityEntityUser] + + +class FetchOrgInfoFromEntityEntityUser(GQLResult): + organizations: List[OrgInfoFragment] + + +FetchOrgInfoFromEntity.model_rebuild() +FetchOrgInfoFromEntityEntity.model_rebuild() +FetchOrgInfoFromEntityEntityUser.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_registries.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_registries.py new file mode 100644 index 0000000000000000000000000000000000000000..b8c3e1c9377692f850071d412d52cb4a9e1fe155 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_registries.py @@ -0,0 +1,42 @@ +# 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 GQLResult + +from .fragments import PageInfoFragment, RegistryFragment + + +class FetchRegistries(GQLResult): + organization: Optional[FetchRegistriesOrganization] + + +class FetchRegistriesOrganization(GQLResult): + org_entity: Optional[FetchRegistriesOrganizationOrgEntity] = Field( + alias="orgEntity" + ) + + +class FetchRegistriesOrganizationOrgEntity(GQLResult): + projects: Optional[FetchRegistriesOrganizationOrgEntityProjects] + + +class FetchRegistriesOrganizationOrgEntityProjects(GQLResult): + page_info: PageInfoFragment = Field(alias="pageInfo") + edges: List[FetchRegistriesOrganizationOrgEntityProjectsEdges] + + +class FetchRegistriesOrganizationOrgEntityProjectsEdges(GQLResult): + node: Optional[RegistryFragment] + + +FetchRegistries.model_rebuild() +FetchRegistriesOrganization.model_rebuild() +FetchRegistriesOrganizationOrgEntity.model_rebuild() +FetchRegistriesOrganizationOrgEntityProjects.model_rebuild() +FetchRegistriesOrganizationOrgEntityProjectsEdges.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_registry.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..1bf736adf54bfcbd80cd5d50f41eafc5819bf27a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/fetch_registry.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 GQLResult + +from .fragments import RegistryFragment + + +class FetchRegistry(GQLResult): + entity: Optional[FetchRegistryEntity] + + +class FetchRegistryEntity(GQLResult): + project: Optional[RegistryFragment] + + +FetchRegistry.model_rebuild() +FetchRegistryEntity.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/fragments.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/fragments.py new file mode 100644 index 0000000000000000000000000000000000000000..5b8fafe523c82228db57dbbe4273d863fa866242 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/fragments.py @@ -0,0 +1,348 @@ +# 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 GQLId, GQLResult, Typename + +from .enums import ArtifactState + + +class ArtifactAliasFragment(GQLResult): + typename__: Typename[Literal["ArtifactAlias"]] = "ArtifactAlias" + id: GQLId + alias: str + + +class ProjectInfoFragment(GQLResult): + name: str + entity: ProjectInfoFragmentEntity + + +class ProjectInfoFragmentEntity(GQLResult): + name: str + + +class TagFragment(GQLResult): + typename__: Typename[Literal["Tag"]] = "Tag" + id: GQLId + name: str + + +class ArtifactCollectionFragment(GQLResult): + typename__: Typename[Literal["ArtifactPortfolio", "ArtifactSequence"]] + id: GQLId + name: str + description: Optional[str] + created_at: str = Field(alias="createdAt") + updated_at: Optional[str] = Field(alias="updatedAt") + project: Optional[ProjectInfoFragment] + type: ArtifactCollectionFragmentType + tags: ArtifactCollectionFragmentTags + + +class ArtifactCollectionFragmentType(GQLResult): + name: str + + +class ArtifactCollectionFragmentTags(GQLResult): + edges: List[ArtifactCollectionFragmentTagsEdges] + + +class ArtifactCollectionFragmentTagsEdges(GQLResult): + node: TagFragment + + +class CollectionInfoFragment(GQLResult): + typename__: Typename[Literal["ArtifactPortfolio", "ArtifactSequence"]] + name: str + project: Optional[ProjectInfoFragment] + + +class SourceCollectionInfoFragment(GQLResult): + typename__: Typename[Literal["ArtifactSequence"]] = "ArtifactSequence" + name: str + project: Optional[ProjectInfoFragment] + + +class ArtifactFragment(GQLResult): + typename__: Typename[Literal["Artifact"]] = "Artifact" + id: GQLId + artifact_sequence: SourceCollectionInfoFragment = Field(alias="artifactSequence") + version_index: Optional[int] = Field(alias="versionIndex") + artifact_type: ArtifactFragmentArtifactType = Field(alias="artifactType") + description: Optional[str] + metadata: Optional[str] + ttl_duration_seconds: int = Field(alias="ttlDurationSeconds") + ttl_is_inherited: bool = Field(alias="ttlIsInherited") + tags: List[TagFragment] + history_step: Optional[int] = Field(alias="historyStep") + state: ArtifactState + size: int + digest: str + commit_hash: Optional[str] = Field(alias="commitHash") + file_count: int = Field(alias="fileCount") + created_at: str = Field(alias="createdAt") + updated_at: Optional[str] = Field(alias="updatedAt") + aliases: Optional[List[ArtifactFragmentAliases]] = None + + +class ArtifactFragmentArtifactType(GQLResult): + name: str + + +class ArtifactFragmentAliases(ArtifactAliasFragment): + artifact_collection: Optional[CollectionInfoFragment] = Field( + alias="artifactCollection" + ) + + +class ArtifactMembershipFragment(GQLResult): + typename__: Typename[Literal["ArtifactCollectionMembership"]] = ( + "ArtifactCollectionMembership" + ) + id: GQLId + version_index: Optional[int] = Field(alias="versionIndex") + aliases: List[ArtifactAliasFragment] + artifact_collection: Optional[CollectionInfoFragment] = Field( + alias="artifactCollection" + ) + artifact: Optional[ArtifactFragment] + + +class ArtifactPortfolioTypeFields(GQLResult): + typename__: Typename[Literal["ArtifactPortfolio"]] = "ArtifactPortfolio" + id: GQLId + name: str + + +class ArtifactSequenceTypeFields(GQLResult): + typename__: Typename[Literal["ArtifactSequence"]] = "ArtifactSequence" + id: GQLId + name: str + + +class ArtifactTypeFragment(GQLResult): + typename__: Typename[Literal["ArtifactType"]] = "ArtifactType" + id: GQLId + name: str + description: Optional[str] + created_at: str = Field(alias="createdAt") + + +class DeferredManifestFragment(GQLResult): + file: DeferredManifestFragmentFile + + +class DeferredManifestFragmentFile(GQLResult): + direct_url: str = Field(alias="directUrl") + + +class FileFragment(GQLResult): + typename__: Typename[Literal["File"]] = "File" + id: GQLId + name: str + url: Optional[str] + size_bytes: int = Field(alias="sizeBytes") + storage_path: Optional[str] = Field(alias="storagePath") + 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 FileWithUrlFragment(GQLResult): + typename__: Typename[Literal["File"]] = "File" + name: str + direct_url: str = Field(alias="directUrl") + + +class OrgInfoFragment(GQLResult): + name: str + org_entity: Optional[OrgInfoFragmentOrgEntity] = Field(alias="orgEntity") + + +class OrgInfoFragmentOrgEntity(GQLResult): + name: str + + +class PageInfoFragment(GQLResult): + typename__: Typename[Literal["PageInfo"]] = "PageInfo" + end_cursor: Optional[str] = Field(alias="endCursor") + has_next_page: bool = Field(alias="hasNextPage") + + +class RegistryCollectionFragment(GQLResult): + typename__: Typename[Literal["ArtifactPortfolio", "ArtifactSequence"]] + id: GQLId + name: str + description: Optional[str] + created_at: str = Field(alias="createdAt") + updated_at: Optional[str] = Field(alias="updatedAt") + project: Optional[ProjectInfoFragment] + type: RegistryCollectionFragmentType + tags: RegistryCollectionFragmentTags + + +class RegistryCollectionFragmentType(GQLResult): + name: str + + +class RegistryCollectionFragmentTags(GQLResult): + edges: List[RegistryCollectionFragmentTagsEdges] + + +class RegistryCollectionFragmentTagsEdges(GQLResult): + node: TagFragment + + +class RegistryFragment(GQLResult): + typename__: Typename[Literal["Project"]] = "Project" + id: GQLId + name: str + entity: RegistryFragmentEntity + description: Optional[str] + created_at: str = Field(alias="createdAt") + updated_at: Optional[str] = Field(alias="updatedAt") + access: Optional[str] + allow_all_artifact_types: bool = Field(alias="allowAllArtifactTypes") + artifact_types: RegistryFragmentArtifactTypes = Field(alias="artifactTypes") + + +class RegistryFragmentEntity(GQLResult): + name: str + organization: Optional[RegistryFragmentEntityOrganization] + + +class RegistryFragmentEntityOrganization(GQLResult): + name: str + + +class RegistryFragmentArtifactTypes(GQLResult): + edges: List[RegistryFragmentArtifactTypesEdges] + + +class RegistryFragmentArtifactTypesEdges(GQLResult): + node: Optional[RegistryFragmentArtifactTypesEdgesNode] + + +class RegistryFragmentArtifactTypesEdgesNode(GQLResult): + name: str + + +class RegistryRoleFragment(GQLResult): + name: str + + +class RunInfoFragment(GQLResult): + typename__: Typename[Literal["Run"]] = "Run" + id: GQLId + name: str + project: Optional[ProjectInfoFragment] + + +class TeamMemberFragment(GQLResult): + typename__: Typename[Literal["Member"]] = "Member" + id: Optional[str] + role: Optional[str] + pending: Optional[bool] + email: Optional[str] + username: Optional[str] + name: str + photo_url: Optional[str] = Field(alias="photoUrl") + account_type: Optional[str] = Field(alias="accountType") + api_key: Optional[str] = Field(alias="apiKey") + + +class TeamFragment(GQLResult): + typename__: Typename[Literal["Entity"]] = "Entity" + id: GQLId + name: str + available: Optional[bool] + photo_url: Optional[str] = Field(alias="photoUrl") + read_only: Optional[bool] = Field(alias="readOnly") + read_only_admin: bool = Field(alias="readOnlyAdmin") + is_team: bool = Field(alias="isTeam") + private_only: bool = Field(alias="privateOnly") + storage_bytes: int = Field(alias="storageBytes") + code_saving_enabled: bool = Field(alias="codeSavingEnabled") + default_access: str = Field(alias="defaultAccess") + is_paid: Optional[bool] = Field(alias="isPaid") + members: List[TeamMemberFragment] + + +class TeamRegistryMemberFragment(GQLResult): + team: TeamFragment + role: RegistryRoleFragment + + +class UserRegistryMemberFragment(GQLResult): + id: GQLId + name: Optional[str] + username: Optional[str] + email: Optional[str] + role: RegistryRoleFragment + + +ArtifactAliasFragment.model_rebuild() +ProjectInfoFragment.model_rebuild() +ProjectInfoFragmentEntity.model_rebuild() +TagFragment.model_rebuild() +ArtifactCollectionFragment.model_rebuild() +ProjectInfoFragment.model_rebuild() +ArtifactCollectionFragmentType.model_rebuild() +ArtifactCollectionFragmentTags.model_rebuild() +ArtifactCollectionFragmentTagsEdges.model_rebuild() +TagFragment.model_rebuild() +CollectionInfoFragment.model_rebuild() +ProjectInfoFragment.model_rebuild() +SourceCollectionInfoFragment.model_rebuild() +ProjectInfoFragment.model_rebuild() +ArtifactFragment.model_rebuild() +SourceCollectionInfoFragment.model_rebuild() +ArtifactFragmentArtifactType.model_rebuild() +TagFragment.model_rebuild() +ArtifactFragmentAliases.model_rebuild() +CollectionInfoFragment.model_rebuild() +ArtifactMembershipFragment.model_rebuild() +ArtifactAliasFragment.model_rebuild() +CollectionInfoFragment.model_rebuild() +ArtifactFragment.model_rebuild() +ArtifactPortfolioTypeFields.model_rebuild() +ArtifactSequenceTypeFields.model_rebuild() +ArtifactTypeFragment.model_rebuild() +DeferredManifestFragment.model_rebuild() +DeferredManifestFragmentFile.model_rebuild() +FileFragment.model_rebuild() +FileWithUrlFragment.model_rebuild() +OrgInfoFragment.model_rebuild() +OrgInfoFragmentOrgEntity.model_rebuild() +PageInfoFragment.model_rebuild() +RegistryCollectionFragment.model_rebuild() +ProjectInfoFragment.model_rebuild() +RegistryCollectionFragmentType.model_rebuild() +RegistryCollectionFragmentTags.model_rebuild() +RegistryCollectionFragmentTagsEdges.model_rebuild() +TagFragment.model_rebuild() +RegistryFragment.model_rebuild() +RegistryFragmentEntity.model_rebuild() +RegistryFragmentEntityOrganization.model_rebuild() +RegistryFragmentArtifactTypes.model_rebuild() +RegistryFragmentArtifactTypesEdges.model_rebuild() +RegistryFragmentArtifactTypesEdgesNode.model_rebuild() +RegistryRoleFragment.model_rebuild() +RunInfoFragment.model_rebuild() +ProjectInfoFragment.model_rebuild() +TeamMemberFragment.model_rebuild() +TeamFragment.model_rebuild() +TeamMemberFragment.model_rebuild() +TeamRegistryMemberFragment.model_rebuild() +TeamFragment.model_rebuild() +RegistryRoleFragment.model_rebuild() +UserRegistryMemberFragment.model_rebuild() +RegistryRoleFragment.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/get_artifact_file_urls.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/get_artifact_file_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..0eef2fbc207b1ef9dfb400dd699a3ba4a24ac2db --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/get_artifact_file_urls.py @@ -0,0 +1,35 @@ +# 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 GQLResult + +from .fragments import FileWithUrlFragment, PageInfoFragment + + +class GetArtifactFileUrls(GQLResult): + artifact: Optional[GetArtifactFileUrlsArtifact] + + +class GetArtifactFileUrlsArtifact(GQLResult): + files: Optional[GetArtifactFileUrlsArtifactFiles] + + +class GetArtifactFileUrlsArtifactFiles(GQLResult): + page_info: PageInfoFragment = Field(alias="pageInfo") + edges: List[GetArtifactFileUrlsArtifactFilesEdges] + + +class GetArtifactFileUrlsArtifactFilesEdges(GQLResult): + node: Optional[FileWithUrlFragment] + + +GetArtifactFileUrls.model_rebuild() +GetArtifactFileUrlsArtifact.model_rebuild() +GetArtifactFileUrlsArtifactFiles.model_rebuild() +GetArtifactFileUrlsArtifactFilesEdges.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/get_artifact_files.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/get_artifact_files.py new file mode 100644 index 0000000000000000000000000000000000000000..d21fc54bfac8be7c867b8aa3a3fb1bf638fad817 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/get_artifact_files.py @@ -0,0 +1,48 @@ +# 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 GQLResult + +from .fragments import FileFragment, PageInfoFragment + + +class GetArtifactFiles(GQLResult): + project: Optional[GetArtifactFilesProject] + + +class GetArtifactFilesProject(GQLResult): + artifact_type: Optional[GetArtifactFilesProjectArtifactType] = Field( + alias="artifactType" + ) + + +class GetArtifactFilesProjectArtifactType(GQLResult): + artifact: Optional[GetArtifactFilesProjectArtifactTypeArtifact] + + +class GetArtifactFilesProjectArtifactTypeArtifact(GQLResult): + files: Optional[GetArtifactFilesProjectArtifactTypeArtifactFiles] + + +class GetArtifactFilesProjectArtifactTypeArtifactFiles(GQLResult): + total_count: Optional[int] = Field(alias="totalCount", default=None) + page_info: PageInfoFragment = Field(alias="pageInfo") + edges: List[GetArtifactFilesProjectArtifactTypeArtifactFilesEdges] + + +class GetArtifactFilesProjectArtifactTypeArtifactFilesEdges(GQLResult): + node: Optional[FileFragment] + + +GetArtifactFiles.model_rebuild() +GetArtifactFilesProject.model_rebuild() +GetArtifactFilesProjectArtifactType.model_rebuild() +GetArtifactFilesProjectArtifactTypeArtifact.model_rebuild() +GetArtifactFilesProjectArtifactTypeArtifactFiles.model_rebuild() +GetArtifactFilesProjectArtifactTypeArtifactFilesEdges.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/get_artifact_membership_file_urls.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/get_artifact_membership_file_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..5c1b1f5a3f3d670ad83753ae51bac0d6ef8c3d9e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/get_artifact_membership_file_urls.py @@ -0,0 +1,62 @@ +# 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 GQLResult, Typename + +from .fragments import FileWithUrlFragment, PageInfoFragment + + +class GetArtifactMembershipFileUrls(GQLResult): + project: Optional[GetArtifactMembershipFileUrlsProject] + + +class GetArtifactMembershipFileUrlsProject(GQLResult): + artifact_collection: Optional[ + GetArtifactMembershipFileUrlsProjectArtifactCollection + ] = Field(alias="artifactCollection") + + +class GetArtifactMembershipFileUrlsProjectArtifactCollection(GQLResult): + typename__: Typename[ + Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"] + ] + artifact_membership: Optional[ + GetArtifactMembershipFileUrlsProjectArtifactCollectionArtifactMembership + ] = Field(alias="artifactMembership") + + +class GetArtifactMembershipFileUrlsProjectArtifactCollectionArtifactMembership( + GQLResult +): + files: Optional[ + GetArtifactMembershipFileUrlsProjectArtifactCollectionArtifactMembershipFiles + ] + + +class GetArtifactMembershipFileUrlsProjectArtifactCollectionArtifactMembershipFiles( + GQLResult +): + page_info: PageInfoFragment = Field(alias="pageInfo") + edges: List[ + GetArtifactMembershipFileUrlsProjectArtifactCollectionArtifactMembershipFilesEdges + ] + + +class GetArtifactMembershipFileUrlsProjectArtifactCollectionArtifactMembershipFilesEdges( + GQLResult +): + node: Optional[FileWithUrlFragment] + + +GetArtifactMembershipFileUrls.model_rebuild() +GetArtifactMembershipFileUrlsProject.model_rebuild() +GetArtifactMembershipFileUrlsProjectArtifactCollection.model_rebuild() +GetArtifactMembershipFileUrlsProjectArtifactCollectionArtifactMembership.model_rebuild() +GetArtifactMembershipFileUrlsProjectArtifactCollectionArtifactMembershipFiles.model_rebuild() +GetArtifactMembershipFileUrlsProjectArtifactCollectionArtifactMembershipFilesEdges.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/get_artifact_membership_files.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/get_artifact_membership_files.py new file mode 100644 index 0000000000000000000000000000000000000000..232619a43f4a9cfa8756ce8f635f959e54252474 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/get_artifact_membership_files.py @@ -0,0 +1,61 @@ +# 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 GQLResult, Typename + +from .fragments import FileFragment, PageInfoFragment + + +class GetArtifactMembershipFiles(GQLResult): + project: Optional[GetArtifactMembershipFilesProject] + + +class GetArtifactMembershipFilesProject(GQLResult): + artifact_collection: Optional[ + GetArtifactMembershipFilesProjectArtifactCollection + ] = Field(alias="artifactCollection") + + +class GetArtifactMembershipFilesProjectArtifactCollection(GQLResult): + typename__: Typename[ + Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"] + ] + artifact_membership: Optional[ + GetArtifactMembershipFilesProjectArtifactCollectionArtifactMembership + ] = Field(alias="artifactMembership") + + +class GetArtifactMembershipFilesProjectArtifactCollectionArtifactMembership(GQLResult): + files: Optional[ + GetArtifactMembershipFilesProjectArtifactCollectionArtifactMembershipFiles + ] + + +class GetArtifactMembershipFilesProjectArtifactCollectionArtifactMembershipFiles( + GQLResult +): + total_count: Optional[int] = Field(alias="totalCount", default=None) + page_info: PageInfoFragment = Field(alias="pageInfo") + edges: List[ + GetArtifactMembershipFilesProjectArtifactCollectionArtifactMembershipFilesEdges + ] + + +class GetArtifactMembershipFilesProjectArtifactCollectionArtifactMembershipFilesEdges( + GQLResult +): + node: Optional[FileFragment] + + +GetArtifactMembershipFiles.model_rebuild() +GetArtifactMembershipFilesProject.model_rebuild() +GetArtifactMembershipFilesProjectArtifactCollection.model_rebuild() +GetArtifactMembershipFilesProjectArtifactCollectionArtifactMembership.model_rebuild() +GetArtifactMembershipFilesProjectArtifactCollectionArtifactMembershipFiles.model_rebuild() +GetArtifactMembershipFilesProjectArtifactCollectionArtifactMembershipFilesEdges.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/input_types.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/input_types.py new file mode 100644 index 0000000000000000000000000000000000000000..dfa16e670c225579a9567515c04b09772df63c02 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/input_types.py @@ -0,0 +1,221 @@ +# Generated by ariadne-codegen +# Source: core/api/graphql/schemas/schema-latest.graphql + +from __future__ import annotations + +from typing import List, Optional + +from pydantic import Field + +from wandb._pydantic import GQLId, GQLInput + + +class AddAliasesInput(GQLInput): + aliases: List[ArtifactCollectionAliasInput] + artifact_id: GQLId = Field(alias="artifactID") + client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None) + + +class ArtifactAliasInput(GQLInput): + alias: str = Field(max_length=128) + artifact_collection_name: str = Field(alias="artifactCollectionName") + + +class ArtifactCollectionAliasInput(GQLInput): + alias: str = Field(max_length=128) + artifact_collection_name: str = Field(alias="artifactCollectionName") + entity_name: str = Field(alias="entityName") + project_name: str = Field(alias="projectName") + + +class ArtifactTypeInput(GQLInput): + description: Optional[str] = None + name: str = Field(max_length=128, pattern="^[-\\w]+([ ]*[-.\\w]+)*$") + + +class CreateArtifactCollectionTagAssignmentsInput(GQLInput): + artifact_collection_name: str = Field(alias="artifactCollectionName") + client_mutation_id: Optional[str] = Field(alias="clientMutationID", default=None) + entity_name: str = Field(alias="entityName") + project_name: str = Field(alias="projectName") + tags: List[TagInput] = Field(max_length=20) + + +class CreateProjectMembersInput(GQLInput): + project_id: GQLId = Field(alias="projectId") + team_ids: Optional[List[GQLId]] = Field(alias="teamIds", default=None) + user_ids: Optional[List[GQLId]] = Field(alias="userIds", default=None) + + +class DeleteAliasesInput(GQLInput): + aliases: List[ArtifactCollectionAliasInput] + artifact_id: GQLId = Field(alias="artifactID") + client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None) + + +class DeleteArtifactCollectionTagAssignmentsInput(GQLInput): + artifact_collection_name: str = Field(alias="artifactCollectionName") + client_mutation_id: Optional[str] = Field(alias="clientMutationID", default=None) + entity_name: str = Field(alias="entityName") + project_name: str = Field(alias="projectName") + tags: List[TagInput] = Field(max_length=20) + + +class DeleteArtifactInput(GQLInput): + artifact_id: GQLId = Field(alias="artifactID") + client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None) + delete_aliases: Optional[bool] = Field(alias="deleteAliases", default=False) + + +class DeleteProjectMembersInput(GQLInput): + project_id: GQLId = Field(alias="projectId") + team_ids: Optional[List[GQLId]] = Field(alias="teamIds", default=None) + user_ids: Optional[List[GQLId]] = Field(alias="userIds", default=None) + + +class LinkArtifactInput(GQLInput): + aliases: Optional[List[ArtifactAliasInput]] = None + 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 + ) + client_id: Optional[GQLId] = Field(alias="clientID", default=None) + client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None) + entity_name: Optional[str] = Field(alias="entityName", default=None) + project_name: Optional[str] = Field(alias="projectName", default=None) + + +class MoveArtifactSequenceInput(GQLInput): + artifact_sequence_id: GQLId = Field(alias="artifactSequenceID") + client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None) + destination_artifact_type_name: str = Field(alias="destinationArtifactTypeName") + + +class ProjectIconInput(GQLInput): + color: str + name: str + + +class RateLimitsInput(GQLInput): + create_artifacts: Optional[int] = Field(alias="createArtifacts", default=None) + create_artifacts_time_window: Optional[int] = Field( + alias="createArtifactsTimeWindow", default=None + ) + filestream_count: Optional[float] = Field(alias="filestreamCount", default=None) + filestream_per_run_count: Optional[float] = Field( + alias="filestreamPerRunCount", default=None + ) + filestream_size: Optional[int] = Field(alias="filestreamSize", default=None) + graphql: Optional[int] = None + run_update_count: Optional[float] = Field(alias="runUpdateCount", default=None) + sdk_graphql: Optional[int] = Field(alias="sdkGraphql", default=None) + sdk_graphql_query_seconds: Optional[float] = Field( + alias="sdkGraphqlQuerySeconds", default=None + ) + + +class RenameProjectInput(GQLInput): + client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None) + entity_name: str = Field(alias="entityName") + new_project_name: str = Field(alias="newProjectName") + old_project_name: str = Field(alias="oldProjectName") + + +class TagInput(GQLInput): + attributes: Optional[str] = None + tag_category_name: Optional[str] = Field( + alias="tagCategoryName", + default=None, + max_length=128, + pattern="^[-\\w]+([ ]+[-\\w]+)*$", + ) + tag_name: str = Field( + alias="tagName", max_length=128, pattern="^[-\\w]+([ ]+[-\\w]+)*$" + ) + + +class UnlinkArtifactInput(GQLInput): + artifact_id: GQLId = Field(alias="artifactID") + artifact_portfolio_id: GQLId = Field(alias="artifactPortfolioID") + client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None) + + +class UpdateArtifactInput(GQLInput): + aliases: Optional[List[ArtifactAliasInput]] = None + artifact_id: GQLId = Field(alias="artifactID") + client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None) + description: Optional[str] = None + labels: Optional[str] = None + metadata: Optional[str] = None + tags_to_add: Optional[List[TagInput]] = Field(alias="tagsToAdd", default=None) + tags_to_delete: Optional[List[TagInput]] = Field(alias="tagsToDelete", default=None) + ttl_duration_seconds: Optional[int] = Field( + alias="ttlDurationSeconds", default=None + ) + + +class UpdateArtifactPortfolioInput(GQLInput): + artifact_portfolio_id: GQLId = Field(alias="artifactPortfolioID") + client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None) + description: Optional[str] = None + name: Optional[str] = Field(default=None, max_length=128) + + +class UpdateArtifactSequenceInput(GQLInput): + artifact_sequence_id: GQLId = Field(alias="artifactSequenceID") + client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None) + description: Optional[str] = None + name: Optional[str] = Field(default=None, max_length=128) + + +class UpdateProjectMemberInput(GQLInput): + client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None) + project_id: GQLId = Field(alias="projectId") + user_id: GQLId = Field(alias="userId") + user_project_role: str = Field(alias="userProjectRole") + + +class UpdateProjectTeamMemberInput(GQLInput): + client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None) + project_id: GQLId = Field(alias="projectId") + team_id: GQLId = Field(alias="teamId") + team_project_role: str = Field(alias="teamProjectRole") + + +class UpsertModelInput(GQLInput): + access: Optional[str] = None + allow_all_artifact_types_in_registry: Optional[bool] = Field( + alias="allowAllArtifactTypesInRegistry", default=None + ) + artifact_types: Optional[List[ArtifactTypeInput]] = Field( + alias="artifactTypes", default=None + ) + client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None) + description: Optional[str] = None + docker_image: Optional[str] = Field( + alias="dockerImage", default=None, max_length=512 + ) + entity_name: Optional[str] = Field(alias="entityName", default=None) + framework: Optional[str] = None + icon: Optional[ProjectIconInput] = None + id: Optional[str] = None + is_benchmark: Optional[bool] = Field(alias="isBenchmark", default=None) + is_published: Optional[bool] = Field(alias="isPublished", default=None) + linked_benchmark: Optional[GQLId] = Field(alias="linkedBenchmark", default=None) + name: Optional[str] = Field(default=None, max_length=128) + owner: Optional[GQLId] = None + rate_limits: Optional[RateLimitsInput] = Field(alias="rateLimits", default=None) + repo: Optional[str] = Field(default=None, max_length=256) + views: Optional[str] = None + + +AddAliasesInput.model_rebuild() +CreateArtifactCollectionTagAssignmentsInput.model_rebuild() +DeleteAliasesInput.model_rebuild() +DeleteArtifactCollectionTagAssignmentsInput.model_rebuild() +LinkArtifactInput.model_rebuild() +UpdateArtifactInput.model_rebuild() +UpsertModelInput.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/link_artifact.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/link_artifact.py new file mode 100644 index 0000000000000000000000000000000000000000..a5b06d0ccf171a9ae7491807c6f0dd4ddb6f8c86 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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 GQLResult + +from .fragments import ArtifactMembershipFragment + + +class LinkArtifact(GQLResult): + result: Optional[LinkArtifactResult] + + +class LinkArtifactResult(GQLResult): + version_index: Optional[int] = Field(alias="versionIndex") + artifact_membership: Optional[ArtifactMembershipFragment] = Field( + alias="artifactMembership", default=None + ) + + +LinkArtifact.model_rebuild() +LinkArtifactResult.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/operations.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/operations.py new file mode 100644 index 0000000000000000000000000000000000000000..d10fef8ea829ec7458b17adf67375edd58ed7638 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/operations.py @@ -0,0 +1,2001 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/artifacts/ + +__all__ = [ + "ADD_ALIASES_GQL", + "ADD_ARTIFACT_COLLECTION_TAGS_GQL", + "ARTIFACT_BY_ID_GQL", + "ARTIFACT_BY_NAME_GQL", + "ARTIFACT_COLLECTION_ALIASES_GQL", + "ARTIFACT_CREATED_BY_GQL", + "ARTIFACT_MEMBERSHIP_BY_NAME_GQL", + "ARTIFACT_TYPE_ARTIFACT_COLLECTIONS_GQL", + "ARTIFACT_TYPE_GQL", + "ARTIFACT_USED_BY_GQL", + "CREATE_REGISTRY_MEMBERS_GQL", + "DELETE_ALIASES_GQL", + "DELETE_ARTIFACT_COLLECTION_TAGS_GQL", + "DELETE_ARTIFACT_GQL", + "DELETE_ARTIFACT_PORTFOLIO_GQL", + "DELETE_ARTIFACT_SEQUENCE_GQL", + "DELETE_REGISTRY_GQL", + "DELETE_REGISTRY_MEMBERS_GQL", + "FETCH_ARTIFACT_MANIFEST_GQL", + "FETCH_LINKED_ARTIFACTS_GQL", + "FETCH_ORG_ENTITY_FROM_ORGANIZATION_GQL", + "FETCH_ORG_INFO_FROM_ENTITY_GQL", + "FETCH_REGISTRIES_GQL", + "FETCH_REGISTRY_GQL", + "GET_ARTIFACT_FILES_GQL", + "GET_ARTIFACT_FILE_URLS_GQL", + "GET_ARTIFACT_MEMBERSHIP_FILES_GQL", + "GET_ARTIFACT_MEMBERSHIP_FILE_URLS_GQL", + "LINK_ARTIFACT_GQL", + "PROJECT_ARTIFACTS_GQL", + "PROJECT_ARTIFACT_COLLECTIONS_GQL", + "PROJECT_ARTIFACT_COLLECTION_GQL", + "PROJECT_ARTIFACT_TYPES_GQL", + "PROJECT_ARTIFACT_TYPE_GQL", + "REGISTRY_COLLECTIONS_GQL", + "REGISTRY_TEAM_MEMBERS_GQL", + "REGISTRY_USER_MEMBERS_GQL", + "REGISTRY_VERSIONS_GQL", + "RENAME_REGISTRY_GQL", + "RUN_INPUT_ARTIFACTS_GQL", + "RUN_OUTPUT_ARTIFACTS_GQL", + "UNLINK_ARTIFACT_GQL", + "UPDATE_ARTIFACT_GQL", + "UPDATE_ARTIFACT_PORTFOLIO_GQL", + "UPDATE_ARTIFACT_SEQUENCE_GQL", + "UPDATE_ARTIFACT_SEQUENCE_TYPE_GQL", + "UPDATE_TEAM_REGISTRY_ROLE_GQL", + "UPDATE_USER_REGISTRY_ROLE_GQL", + "UPSERT_REGISTRY_GQL", +] + +DELETE_ARTIFACT_SEQUENCE_GQL = """ +mutation DeleteArtifactSequence($id: ID!) { + result: deleteArtifactSequence(input: {artifactSequenceID: $id}) { + artifactCollection { + __typename + state + } + } +} +""" + +DELETE_ARTIFACT_PORTFOLIO_GQL = """ +mutation DeleteArtifactPortfolio($id: ID!) { + result: deleteArtifactPortfolio(input: {artifactPortfolioID: $id}) { + artifactCollection { + __typename + state + } + } +} +""" + +UPDATE_ARTIFACT_SEQUENCE_GQL = """ +mutation UpdateArtifactSequence($input: UpdateArtifactSequenceInput!) { + result: updateArtifactSequence(input: $input) { + artifactCollection { + __typename + ...ArtifactCollectionFragment + } + } +} + +fragment ArtifactCollectionFragment on ArtifactCollection { + __typename + id + name + description + createdAt + updatedAt + project { + ...ProjectInfoFragment + } + type: defaultArtifactType { + name + } + tags { + edges { + node { + ...TagFragment + } + } + } +} + +fragment ProjectInfoFragment on Project { + name + entity { + name + } +} + +fragment TagFragment on Tag { + __typename + id + name +} +""" + +UPDATE_ARTIFACT_PORTFOLIO_GQL = """ +mutation UpdateArtifactPortfolio($input: UpdateArtifactPortfolioInput!) { + result: updateArtifactPortfolio(input: $input) { + artifactCollection { + __typename + ...ArtifactCollectionFragment + } + } +} + +fragment ArtifactCollectionFragment on ArtifactCollection { + __typename + id + name + description + createdAt + updatedAt + project { + ...ProjectInfoFragment + } + type: defaultArtifactType { + name + } + tags { + edges { + node { + ...TagFragment + } + } + } +} + +fragment ProjectInfoFragment on Project { + name + entity { + name + } +} + +fragment TagFragment on Tag { + __typename + id + name +} +""" + +UPDATE_ARTIFACT_SEQUENCE_TYPE_GQL = """ +mutation UpdateArtifactSequenceType($input: MoveArtifactSequenceInput!) { + result: moveArtifactSequence(input: $input) { + artifactCollection { + __typename + ...ArtifactCollectionFragment + } + } +} + +fragment ArtifactCollectionFragment on ArtifactCollection { + __typename + id + name + description + createdAt + updatedAt + project { + ...ProjectInfoFragment + } + type: defaultArtifactType { + name + } + tags { + edges { + node { + ...TagFragment + } + } + } +} + +fragment ProjectInfoFragment on Project { + name + entity { + name + } +} + +fragment TagFragment on Tag { + __typename + id + name +} +""" + +ADD_ARTIFACT_COLLECTION_TAGS_GQL = """ +mutation AddArtifactCollectionTags($input: CreateArtifactCollectionTagAssignmentsInput!) { + result: createArtifactCollectionTagAssignments(input: $input) { + tags { + ...TagFragment + } + } +} + +fragment TagFragment on Tag { + __typename + id + name +} +""" + +DELETE_ARTIFACT_COLLECTION_TAGS_GQL = """ +mutation DeleteArtifactCollectionTags($input: DeleteArtifactCollectionTagAssignmentsInput!) { + result: deleteArtifactCollectionTagAssignments(input: $input) { + success + } +} +""" + +ARTIFACT_TYPE_ARTIFACT_COLLECTIONS_GQL = """ +query ArtifactTypeArtifactCollections($entity: String!, $project: String!, $type: String!, $cursor: String, $perPage: Int, $filters: JSONString, $order: String) { + project(entityName: $entity, name: $project) { + artifactType(name: $type) { + artifactCollections( + after: $cursor + first: $perPage + filters: $filters + order: $order + ) { + totalCount + pageInfo { + ...PageInfoFragment + } + edges { + node { + __typename + ...ArtifactCollectionFragment + } + } + } + } + } +} + +fragment ArtifactCollectionFragment on ArtifactCollection { + __typename + id + name + description + createdAt + updatedAt + project { + ...ProjectInfoFragment + } + type: defaultArtifactType { + name + } + tags { + edges { + node { + ...TagFragment + } + } + } +} + +fragment PageInfoFragment on PageInfo { + __typename + endCursor + hasNextPage +} + +fragment ProjectInfoFragment on Project { + name + entity { + name + } +} + +fragment TagFragment on Tag { + __typename + id + name +} +""" + +PROJECT_ARTIFACT_COLLECTIONS_GQL = """ +query ProjectArtifactCollections($entity: String!, $project: String!, $cursor: String, $perPage: Int, $filters: JSONString, $order: String) { + project(entityName: $entity, name: $project) { + artifactCollections( + after: $cursor + first: $perPage + filters: $filters + order: $order + ) { + totalCount @include(if: true) + pageInfo { + ...PageInfoFragment + } + edges { + node { + __typename + ...ArtifactCollectionFragment + } + } + } + } +} + +fragment ArtifactCollectionFragment on ArtifactCollection { + __typename + id + name + description + createdAt + updatedAt + project { + ...ProjectInfoFragment + } + type: defaultArtifactType { + name + } + tags { + edges { + node { + ...TagFragment + } + } + } +} + +fragment PageInfoFragment on PageInfo { + __typename + endCursor + hasNextPage +} + +fragment ProjectInfoFragment on Project { + name + entity { + name + } +} + +fragment TagFragment on Tag { + __typename + id + name +} +""" + +PROJECT_ARTIFACT_COLLECTION_GQL = """ +query ProjectArtifactCollection($entity: String!, $project: String!, $type: String!, $name: String!) { + project(entityName: $entity, name: $project) { + artifactType(name: $type) { + artifactCollection(name: $name) { + __typename + ...ArtifactCollectionFragment + } + } + } +} + +fragment ArtifactCollectionFragment on ArtifactCollection { + __typename + id + name + description + createdAt + updatedAt + project { + ...ProjectInfoFragment + } + type: defaultArtifactType { + name + } + tags { + edges { + node { + ...TagFragment + } + } + } +} + +fragment ProjectInfoFragment on Project { + name + entity { + name + } +} + +fragment TagFragment on Tag { + __typename + id + name +} +""" + +ARTIFACT_COLLECTION_ALIASES_GQL = """ +query ArtifactCollectionAliases($id: ID!, $cursor: String, $perPage: Int = 1000) { + artifactCollection(id: $id) { + __typename + aliases(after: $cursor, first: $perPage) { + pageInfo { + ...PageInfoFragment + } + edges { + node { + ...ArtifactAliasFragment + } + } + } + } +} + +fragment ArtifactAliasFragment on ArtifactAlias { + __typename + id + alias +} + +fragment PageInfoFragment on PageInfo { + __typename + endCursor + hasNextPage +} +""" + +GET_ARTIFACT_FILES_GQL = """ +query GetArtifactFiles($entity: String!, $project: String!, $type: String!, $name: String!, $fileNames: [String!], $cursor: String, $perPage: Int = 50) { + project(name: $project, entityName: $entity) { + artifactType(name: $type) { + artifact(name: $name) { + files(names: $fileNames, after: $cursor, first: $perPage) { + totalCount @include(if: true) + pageInfo { + ...PageInfoFragment + } + edges { + node { + ...FileFragment + } + } + } + } + } + } +} + +fragment FileFragment on File { + __typename + id + name: displayName + url + sizeBytes + storagePath + mimetype + updatedAt + digest + md5 + directUrl +} + +fragment PageInfoFragment on PageInfo { + __typename + endCursor + hasNextPage +} +""" + +GET_ARTIFACT_MEMBERSHIP_FILES_GQL = """ +query GetArtifactMembershipFiles($entity: String!, $project: String!, $collection: String!, $alias: String!, $fileNames: [String!], $cursor: String, $perPage: Int = 50) { + project(name: $project, entityName: $entity) { + artifactCollection(name: $collection) { + __typename + artifactMembership(aliasName: $alias) { + files(names: $fileNames, after: $cursor, first: $perPage) { + totalCount @include(if: true) + pageInfo { + ...PageInfoFragment + } + edges { + node { + ...FileFragment + } + } + } + } + } + } +} + +fragment FileFragment on File { + __typename + id + name: displayName + url + sizeBytes + storagePath + mimetype + updatedAt + digest + md5 + directUrl +} + +fragment PageInfoFragment on PageInfo { + __typename + endCursor + hasNextPage +} +""" + +GET_ARTIFACT_FILE_URLS_GQL = """ +query GetArtifactFileUrls($id: ID!, $cursor: String, $perPage: Int) { + artifact(id: $id) { + files(after: $cursor, first: $perPage) { + pageInfo { + ...PageInfoFragment + } + edges { + node { + ...FileWithUrlFragment + } + } + } + } +} + +fragment FileWithUrlFragment on File { + __typename + name + directUrl +} + +fragment PageInfoFragment on PageInfo { + __typename + endCursor + hasNextPage +} +""" + +GET_ARTIFACT_MEMBERSHIP_FILE_URLS_GQL = """ +query GetArtifactMembershipFileUrls($entity: String!, $project: String!, $collection: String!, $alias: String!, $cursor: String, $perPage: Int) { + project(name: $project, entityName: $entity) { + artifactCollection(name: $collection) { + __typename + artifactMembership(aliasName: $alias) { + files(after: $cursor, first: $perPage) { + pageInfo { + ...PageInfoFragment + } + edges { + node { + ...FileWithUrlFragment + } + } + } + } + } + } +} + +fragment FileWithUrlFragment on File { + __typename + name + directUrl +} + +fragment PageInfoFragment on PageInfo { + __typename + endCursor + hasNextPage +} +""" + +PROJECT_ARTIFACT_TYPES_GQL = """ +query ProjectArtifactTypes($entity: String!, $project: String!, $cursor: String, $perPage: Int) { + project(name: $project, entityName: $entity) { + artifactTypes(after: $cursor, first: $perPage) { + edges { + node { + ...ArtifactTypeFragment + } + } + pageInfo { + ...PageInfoFragment + } + } + } +} + +fragment ArtifactTypeFragment on ArtifactType { + __typename + id + name + description + createdAt +} + +fragment PageInfoFragment on PageInfo { + __typename + endCursor + hasNextPage +} +""" + +PROJECT_ARTIFACT_TYPE_GQL = """ +query ProjectArtifactType($entity: String!, $project: String!, $type: String!) { + project(entityName: $entity, name: $project) { + artifactType(name: $type) { + ...ArtifactTypeFragment + } + } +} + +fragment ArtifactTypeFragment on ArtifactType { + __typename + id + name + description + createdAt +} +""" + +PROJECT_ARTIFACTS_GQL = """ +query ProjectArtifacts($entity: String!, $project: String!, $type: String!, $collection: String!, $cursor: String, $perPage: Int = 50, $order: String, $filters: JSONString, $includeAliases: Boolean = true) { + project(entityName: $entity, name: $project) { + artifactType(name: $type) { + artifactCollection(name: $collection) { + __typename + artifacts(after: $cursor, first: $perPage, order: $order, filters: $filters) { + totalCount + pageInfo { + ...PageInfoFragment + } + edges { + version + node { + ...ArtifactFragment + } + } + } + } + } + } +} + +fragment ArtifactAliasFragment on ArtifactAlias { + __typename + id + alias +} + +fragment ArtifactFragment on Artifact { + __typename + id + artifactSequence { + ...SourceCollectionInfoFragment + } + versionIndex + artifactType { + name + } + description + metadata + ttlDurationSeconds + ttlIsInherited + tags { + ...TagFragment + } + historyStep + state + size + digest + commitHash + fileCount + createdAt + updatedAt + aliases @include(if: $includeAliases) { + artifactCollection { + ...CollectionInfoFragment + } + ...ArtifactAliasFragment + } +} + +fragment CollectionInfoFragment on ArtifactCollection { + __typename + name + project { + ...ProjectInfoFragment + } +} + +fragment PageInfoFragment on PageInfo { + __typename + endCursor + hasNextPage +} + +fragment ProjectInfoFragment on Project { + name + entity { + name + } +} + +fragment SourceCollectionInfoFragment on ArtifactSequence { + __typename + name + project { + ...ProjectInfoFragment + } +} + +fragment TagFragment on Tag { + __typename + id + name +} +""" + +RUN_OUTPUT_ARTIFACTS_GQL = """ +query RunOutputArtifacts($entity: String!, $project: String!, $run: String!, $cursor: String, $perPage: Int, $includeAliases: Boolean = true) { + project(entityName: $entity, name: $project) { + run(name: $run) { + artifacts: outputArtifacts(after: $cursor, first: $perPage) { + totalCount + pageInfo { + ...PageInfoFragment + } + edges { + node { + ...ArtifactFragment + } + } + } + } + } +} + +fragment ArtifactAliasFragment on ArtifactAlias { + __typename + id + alias +} + +fragment ArtifactFragment on Artifact { + __typename + id + artifactSequence { + ...SourceCollectionInfoFragment + } + versionIndex + artifactType { + name + } + description + metadata + ttlDurationSeconds + ttlIsInherited + tags { + ...TagFragment + } + historyStep + state + size + digest + commitHash + fileCount + createdAt + updatedAt + aliases @include(if: $includeAliases) { + artifactCollection { + ...CollectionInfoFragment + } + ...ArtifactAliasFragment + } +} + +fragment CollectionInfoFragment on ArtifactCollection { + __typename + name + project { + ...ProjectInfoFragment + } +} + +fragment PageInfoFragment on PageInfo { + __typename + endCursor + hasNextPage +} + +fragment ProjectInfoFragment on Project { + name + entity { + name + } +} + +fragment SourceCollectionInfoFragment on ArtifactSequence { + __typename + name + project { + ...ProjectInfoFragment + } +} + +fragment TagFragment on Tag { + __typename + id + name +} +""" + +RUN_INPUT_ARTIFACTS_GQL = """ +query RunInputArtifacts($entity: String!, $project: String!, $run: String!, $cursor: String, $perPage: Int, $includeAliases: Boolean = true) { + project(entityName: $entity, name: $project) { + run(name: $run) { + artifacts: inputArtifacts(after: $cursor, first: $perPage) { + totalCount + pageInfo { + ...PageInfoFragment + } + edges { + node { + ...ArtifactFragment + } + } + } + } + } +} + +fragment ArtifactAliasFragment on ArtifactAlias { + __typename + id + alias +} + +fragment ArtifactFragment on Artifact { + __typename + id + artifactSequence { + ...SourceCollectionInfoFragment + } + versionIndex + artifactType { + name + } + description + metadata + ttlDurationSeconds + ttlIsInherited + tags { + ...TagFragment + } + historyStep + state + size + digest + commitHash + fileCount + createdAt + updatedAt + aliases @include(if: $includeAliases) { + artifactCollection { + ...CollectionInfoFragment + } + ...ArtifactAliasFragment + } +} + +fragment CollectionInfoFragment on ArtifactCollection { + __typename + name + project { + ...ProjectInfoFragment + } +} + +fragment PageInfoFragment on PageInfo { + __typename + endCursor + hasNextPage +} + +fragment ProjectInfoFragment on Project { + name + entity { + name + } +} + +fragment SourceCollectionInfoFragment on ArtifactSequence { + __typename + name + project { + ...ProjectInfoFragment + } +} + +fragment TagFragment on Tag { + __typename + id + name +} +""" + +FETCH_LINKED_ARTIFACTS_GQL = """ +query FetchLinkedArtifacts($artifactID: ID!) { + artifact(id: $artifactID) { + artifactMemberships { + edges { + node { + versionIndex + aliases { + ...ArtifactAliasFragment + } + artifactCollection { + __typename + ...CollectionInfoFragment + } + } + } + } + } +} + +fragment ArtifactAliasFragment on ArtifactAlias { + __typename + id + alias +} + +fragment CollectionInfoFragment on ArtifactCollection { + __typename + name + project { + ...ProjectInfoFragment + } +} + +fragment ProjectInfoFragment on Project { + name + entity { + name + } +} +""" + +FETCH_ARTIFACT_MANIFEST_GQL = """ +query FetchArtifactManifest($id: ID!) { + artifact(id: $id) { + currentManifest { + ...DeferredManifestFragment + } + } +} + +fragment DeferredManifestFragment on ArtifactManifest { + file { + directUrl + } +} +""" + +ARTIFACT_BY_ID_GQL = """ +query ArtifactByID($id: ID!, $includeAliases: Boolean = true) { + artifact(id: $id) { + ...ArtifactFragment + } +} + +fragment ArtifactAliasFragment on ArtifactAlias { + __typename + id + alias +} + +fragment ArtifactFragment on Artifact { + __typename + id + artifactSequence { + ...SourceCollectionInfoFragment + } + versionIndex + artifactType { + name + } + description + metadata + ttlDurationSeconds + ttlIsInherited + tags { + ...TagFragment + } + historyStep + state + size + digest + commitHash + fileCount + createdAt + updatedAt + aliases @include(if: $includeAliases) { + artifactCollection { + ...CollectionInfoFragment + } + ...ArtifactAliasFragment + } +} + +fragment CollectionInfoFragment on ArtifactCollection { + __typename + name + project { + ...ProjectInfoFragment + } +} + +fragment ProjectInfoFragment on Project { + name + entity { + name + } +} + +fragment SourceCollectionInfoFragment on ArtifactSequence { + __typename + name + project { + ...ProjectInfoFragment + } +} + +fragment TagFragment on Tag { + __typename + id + name +} +""" + +ARTIFACT_BY_NAME_GQL = """ +query ArtifactByName($entity: String!, $project: String!, $name: String!, $enableTracking: Boolean, $includeAliases: Boolean = true) { + project(name: $project, entityName: $entity) { + artifact(name: $name, enableTracking: $enableTracking) { + ...ArtifactFragment + } + } +} + +fragment ArtifactAliasFragment on ArtifactAlias { + __typename + id + alias +} + +fragment ArtifactFragment on Artifact { + __typename + id + artifactSequence { + ...SourceCollectionInfoFragment + } + versionIndex + artifactType { + name + } + description + metadata + ttlDurationSeconds + ttlIsInherited + tags { + ...TagFragment + } + historyStep + state + size + digest + commitHash + fileCount + createdAt + updatedAt + aliases @include(if: $includeAliases) { + artifactCollection { + ...CollectionInfoFragment + } + ...ArtifactAliasFragment + } +} + +fragment CollectionInfoFragment on ArtifactCollection { + __typename + name + project { + ...ProjectInfoFragment + } +} + +fragment ProjectInfoFragment on Project { + name + entity { + name + } +} + +fragment SourceCollectionInfoFragment on ArtifactSequence { + __typename + name + project { + ...ProjectInfoFragment + } +} + +fragment TagFragment on Tag { + __typename + id + name +} +""" + +ARTIFACT_MEMBERSHIP_BY_NAME_GQL = """ +query ArtifactMembershipByName($entity: String!, $project: String!, $name: String!, $includeAliases: Boolean = false) { + project(name: $project, entityName: $entity) { + artifactCollectionMembership(name: $name) { + ...ArtifactMembershipFragment + } + } +} + +fragment ArtifactAliasFragment on ArtifactAlias { + __typename + id + alias +} + +fragment ArtifactFragment on Artifact { + __typename + id + artifactSequence { + ...SourceCollectionInfoFragment + } + versionIndex + artifactType { + name + } + description + metadata + ttlDurationSeconds + ttlIsInherited + tags { + ...TagFragment + } + historyStep + state + size + digest + commitHash + fileCount + createdAt + updatedAt + aliases @include(if: $includeAliases) { + artifactCollection { + ...CollectionInfoFragment + } + ...ArtifactAliasFragment + } +} + +fragment ArtifactMembershipFragment on ArtifactCollectionMembership { + __typename + id + versionIndex + aliases { + ...ArtifactAliasFragment + } + artifactCollection { + ...CollectionInfoFragment + } + artifact { + ...ArtifactFragment + } +} + +fragment CollectionInfoFragment on ArtifactCollection { + __typename + name + project { + ...ProjectInfoFragment + } +} + +fragment ProjectInfoFragment on Project { + name + entity { + name + } +} + +fragment SourceCollectionInfoFragment on ArtifactSequence { + __typename + name + project { + ...ProjectInfoFragment + } +} + +fragment TagFragment on Tag { + __typename + id + name +} +""" + +ARTIFACT_USED_BY_GQL = """ +query ArtifactUsedBy($id: ID!) { + artifact(id: $id) { + usedBy { + edges { + node { + ...RunInfoFragment + } + } + } + } +} + +fragment ProjectInfoFragment on Project { + name + entity { + name + } +} + +fragment RunInfoFragment on Run { + __typename + id + name + project { + ...ProjectInfoFragment + } +} +""" + +ARTIFACT_CREATED_BY_GQL = """ +query ArtifactCreatedBy($id: ID!) { + artifact(id: $id) { + createdBy { + __typename + ... on Run { + ...RunInfoFragment + } + } + } +} + +fragment ProjectInfoFragment on Project { + name + entity { + name + } +} + +fragment RunInfoFragment on Run { + __typename + id + name + project { + ...ProjectInfoFragment + } +} +""" + +ARTIFACT_TYPE_GQL = """ +query ArtifactType($entity: String, $project: String, $name: String!) { + project(name: $project, entityName: $entity) { + artifact(name: $name) { + artifactType { + name + } + } + } +} +""" + +ADD_ALIASES_GQL = """ +mutation AddAliases($input: AddAliasesInput!) { + result: addAliases(input: $input) { + success + } +} +""" + +DELETE_ALIASES_GQL = """ +mutation DeleteAliases($input: DeleteAliasesInput!) { + result: deleteAliases(input: $input) { + success + } +} +""" + +UPDATE_ARTIFACT_GQL = """ +mutation UpdateArtifact($input: UpdateArtifactInput!, $includeAliases: Boolean = true) { + result: updateArtifact(input: $input) { + artifact { + ...ArtifactFragment + } + } +} + +fragment ArtifactAliasFragment on ArtifactAlias { + __typename + id + alias +} + +fragment ArtifactFragment on Artifact { + __typename + id + artifactSequence { + ...SourceCollectionInfoFragment + } + versionIndex + artifactType { + name + } + description + metadata + ttlDurationSeconds + ttlIsInherited + tags { + ...TagFragment + } + historyStep + state + size + digest + commitHash + fileCount + createdAt + updatedAt + aliases @include(if: $includeAliases) { + artifactCollection { + ...CollectionInfoFragment + } + ...ArtifactAliasFragment + } +} + +fragment CollectionInfoFragment on ArtifactCollection { + __typename + name + project { + ...ProjectInfoFragment + } +} + +fragment ProjectInfoFragment on Project { + name + entity { + name + } +} + +fragment SourceCollectionInfoFragment on ArtifactSequence { + __typename + name + project { + ...ProjectInfoFragment + } +} + +fragment TagFragment on Tag { + __typename + id + name +} +""" + +DELETE_ARTIFACT_GQL = """ +mutation DeleteArtifact($input: DeleteArtifactInput!) { + result: deleteArtifact(input: $input) { + artifact { + id + } + } +} +""" + +LINK_ARTIFACT_GQL = """ +mutation LinkArtifact($input: LinkArtifactInput!, $includeAliases: Boolean = true) { + result: linkArtifact(input: $input) { + versionIndex + artifactMembership @include(if: true) { + ...ArtifactMembershipFragment + } + } +} + +fragment ArtifactAliasFragment on ArtifactAlias { + __typename + id + alias +} + +fragment ArtifactFragment on Artifact { + __typename + id + artifactSequence { + ...SourceCollectionInfoFragment + } + versionIndex + artifactType { + name + } + description + metadata + ttlDurationSeconds + ttlIsInherited + tags { + ...TagFragment + } + historyStep + state + size + digest + commitHash + fileCount + createdAt + updatedAt + aliases @include(if: $includeAliases) { + artifactCollection { + ...CollectionInfoFragment + } + ...ArtifactAliasFragment + } +} + +fragment ArtifactMembershipFragment on ArtifactCollectionMembership { + __typename + id + versionIndex + aliases { + ...ArtifactAliasFragment + } + artifactCollection { + ...CollectionInfoFragment + } + artifact { + ...ArtifactFragment + } +} + +fragment CollectionInfoFragment on ArtifactCollection { + __typename + name + project { + ...ProjectInfoFragment + } +} + +fragment ProjectInfoFragment on Project { + name + entity { + name + } +} + +fragment SourceCollectionInfoFragment on ArtifactSequence { + __typename + name + project { + ...ProjectInfoFragment + } +} + +fragment TagFragment on Tag { + __typename + id + name +} +""" + +UNLINK_ARTIFACT_GQL = """ +mutation UnlinkArtifact($input: UnlinkArtifactInput!) { + result: unlinkArtifact(input: $input) { + success + } +} +""" + +FETCH_ORG_INFO_FROM_ENTITY_GQL = """ +query FetchOrgInfoFromEntity($entity: String!) { + entity(name: $entity) { + organization { + ...OrgInfoFragment + } + user { + organizations { + ...OrgInfoFragment + } + } + } +} + +fragment OrgInfoFragment on Organization { + name + orgEntity { + name + } +} +""" + +FETCH_ORG_ENTITY_FROM_ORGANIZATION_GQL = """ +query FetchOrgEntityFromOrganization($organization: String!) { + organization(name: $organization) { + orgEntity { + name + } + } +} +""" + +REGISTRY_VERSIONS_GQL = """ +query RegistryVersions($organization: String!, $registryFilter: JSONString, $collectionFilter: JSONString, $artifactFilter: JSONString, $cursor: String, $perPage: Int, $includeAliases: Boolean = false) { + organization(name: $organization) { + orgEntity { + name + artifactMemberships( + projectFilters: $registryFilter + collectionFilters: $collectionFilter + filters: $artifactFilter + after: $cursor + first: $perPage + ) { + pageInfo { + ...PageInfoFragment + } + edges { + node { + ...ArtifactMembershipFragment + } + } + } + } + } +} + +fragment ArtifactAliasFragment on ArtifactAlias { + __typename + id + alias +} + +fragment ArtifactFragment on Artifact { + __typename + id + artifactSequence { + ...SourceCollectionInfoFragment + } + versionIndex + artifactType { + name + } + description + metadata + ttlDurationSeconds + ttlIsInherited + tags { + ...TagFragment + } + historyStep + state + size + digest + commitHash + fileCount + createdAt + updatedAt + aliases @include(if: $includeAliases) { + artifactCollection { + ...CollectionInfoFragment + } + ...ArtifactAliasFragment + } +} + +fragment ArtifactMembershipFragment on ArtifactCollectionMembership { + __typename + id + versionIndex + aliases { + ...ArtifactAliasFragment + } + artifactCollection { + ...CollectionInfoFragment + } + artifact { + ...ArtifactFragment + } +} + +fragment CollectionInfoFragment on ArtifactCollection { + __typename + name + project { + ...ProjectInfoFragment + } +} + +fragment PageInfoFragment on PageInfo { + __typename + endCursor + hasNextPage +} + +fragment ProjectInfoFragment on Project { + name + entity { + name + } +} + +fragment SourceCollectionInfoFragment on ArtifactSequence { + __typename + name + project { + ...ProjectInfoFragment + } +} + +fragment TagFragment on Tag { + __typename + id + name +} +""" + +REGISTRY_COLLECTIONS_GQL = """ +query RegistryCollections($organization: String!, $registryFilter: JSONString, $collectionFilter: JSONString, $collectionTypes: [ArtifactCollectionType!] = [PORTFOLIO], $cursor: String, $perPage: Int) { + organization(name: $organization) { + orgEntity { + name + artifactCollections( + projectFilters: $registryFilter + filters: $collectionFilter + collectionTypes: $collectionTypes + after: $cursor + first: $perPage + ) { + totalCount + pageInfo { + ...PageInfoFragment + } + edges { + node { + __typename + ...RegistryCollectionFragment + } + } + } + } + } +} + +fragment PageInfoFragment on PageInfo { + __typename + endCursor + hasNextPage +} + +fragment ProjectInfoFragment on Project { + name + entity { + name + } +} + +fragment RegistryCollectionFragment on ArtifactCollection { + __typename + id + name + description + createdAt + updatedAt + project { + ...ProjectInfoFragment + } + type: defaultArtifactType { + name + } + tags { + edges { + node { + ...TagFragment + } + } + } +} + +fragment TagFragment on Tag { + __typename + id + name +} +""" + +FETCH_REGISTRY_GQL = """ +query FetchRegistry($name: String, $entity: String) { + entity(name: $entity) { + project(name: $name) { + ...RegistryFragment + } + } +} + +fragment RegistryFragment on Project { + __typename + id + name + entity { + name + organization { + name + } + } + description + createdAt + updatedAt + access + allowAllArtifactTypes: allowAllArtifactTypesInRegistry + artifactTypes(includeAll: true) { + edges { + node { + name + } + } + } +} +""" + +FETCH_REGISTRIES_GQL = """ +query FetchRegistries($organization: String!, $filters: JSONString, $cursor: String, $perPage: Int) { + organization(name: $organization) { + orgEntity { + projects(filters: $filters, after: $cursor, first: $perPage) { + pageInfo { + ...PageInfoFragment + } + edges { + node { + ...RegistryFragment + } + } + } + } + } +} + +fragment PageInfoFragment on PageInfo { + __typename + endCursor + hasNextPage +} + +fragment RegistryFragment on Project { + __typename + id + name + entity { + name + organization { + name + } + } + description + createdAt + updatedAt + access + allowAllArtifactTypes: allowAllArtifactTypesInRegistry + artifactTypes(includeAll: true) { + edges { + node { + name + } + } + } +} +""" + +RENAME_REGISTRY_GQL = """ +mutation RenameRegistry($input: RenameProjectInput!) { + renameProject(input: $input) { + inserted + project { + ...RegistryFragment + } + } +} + +fragment RegistryFragment on Project { + __typename + id + name + entity { + name + organization { + name + } + } + description + createdAt + updatedAt + access + allowAllArtifactTypes: allowAllArtifactTypesInRegistry + artifactTypes(includeAll: true) { + edges { + node { + name + } + } + } +} +""" + +UPSERT_REGISTRY_GQL = """ +mutation UpsertRegistry($input: UpsertModelInput!) { + upsertModel(input: $input) { + inserted + project { + ...RegistryFragment + } + } +} + +fragment RegistryFragment on Project { + __typename + id + name + entity { + name + organization { + name + } + } + description + createdAt + updatedAt + access + allowAllArtifactTypes: allowAllArtifactTypesInRegistry + artifactTypes(includeAll: true) { + edges { + node { + name + } + } + } +} +""" + +DELETE_REGISTRY_GQL = """ +mutation DeleteRegistry($id: String!) { + deleteModel(input: {id: $id}) { + success + } +} +""" + +REGISTRY_USER_MEMBERS_GQL = """ +query RegistryUserMembers($project: String!, $entity: String!) { + project(name: $project, entityName: $entity) { + members { + ...UserRegistryMemberFragment + } + } +} + +fragment RegistryRoleFragment on Role { + name +} + +fragment UserRegistryMemberFragment on ProjectMember { + id + name + username + email + role { + ...RegistryRoleFragment + } +} +""" + +REGISTRY_TEAM_MEMBERS_GQL = """ +query RegistryTeamMembers($project: String!, $entity: String!) { + project(name: $project, entityName: $entity) { + teamMembers { + ...TeamRegistryMemberFragment + } + } +} + +fragment RegistryRoleFragment on Role { + name +} + +fragment TeamFragment on Entity { + __typename + id + name + available + photoUrl + readOnly + readOnlyAdmin + isTeam + privateOnly + storageBytes + codeSavingEnabled + defaultAccess + isPaid + members { + ...TeamMemberFragment + } +} + +fragment TeamMemberFragment on Member { + __typename + id + role + pending + email + username + name + photoUrl + accountType + apiKey +} + +fragment TeamRegistryMemberFragment on ProjectTeamMember { + team { + ...TeamFragment + } + role { + ...RegistryRoleFragment + } +} +""" + +CREATE_REGISTRY_MEMBERS_GQL = """ +mutation CreateRegistryMembers($input: CreateProjectMembersInput!) { + result: createProjectMembers(input: $input) { + success + } +} +""" + +DELETE_REGISTRY_MEMBERS_GQL = """ +mutation DeleteRegistryMembers($input: DeleteProjectMembersInput!) { + result: deleteProjectMembers(input: $input) { + success + } +} +""" + +UPDATE_USER_REGISTRY_ROLE_GQL = """ +mutation UpdateUserRegistryRole($input: UpdateProjectMemberInput!) { + result: updateProjectMember(input: $input) { + success + } +} +""" + +UPDATE_TEAM_REGISTRY_ROLE_GQL = """ +mutation UpdateTeamRegistryRole($input: UpdateProjectTeamMemberInput!) { + result: updateProjectTeamMember(input: $input) { + success + } +} +""" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_collection.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_collection.py new file mode 100644 index 0000000000000000000000000000000000000000..56026db741a09d8f47f108782c7017b1d2102faf --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_collection.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 GQLResult + +from .fragments import ArtifactCollectionFragment + + +class ProjectArtifactCollection(GQLResult): + project: Optional[ProjectArtifactCollectionProject] + + +class ProjectArtifactCollectionProject(GQLResult): + artifact_type: Optional[ProjectArtifactCollectionProjectArtifactType] = Field( + alias="artifactType" + ) + + +class ProjectArtifactCollectionProjectArtifactType(GQLResult): + artifact_collection: Optional[ArtifactCollectionFragment] = Field( + alias="artifactCollection" + ) + + +ProjectArtifactCollection.model_rebuild() +ProjectArtifactCollectionProject.model_rebuild() +ProjectArtifactCollectionProjectArtifactType.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_collections.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_collections.py new file mode 100644 index 0000000000000000000000000000000000000000..a571c817d92912dd7672f6d90a7ab4b5c1bed3bd --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_collections.py @@ -0,0 +1,38 @@ +# 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 GQLResult + +from .fragments import ArtifactCollectionFragment, PageInfoFragment + + +class ProjectArtifactCollections(GQLResult): + project: Optional[ProjectArtifactCollectionsProject] + + +class ProjectArtifactCollectionsProject(GQLResult): + artifact_collections: Optional[ + ProjectArtifactCollectionsProjectArtifactCollections + ] = Field(alias="artifactCollections") + + +class ProjectArtifactCollectionsProjectArtifactCollections(GQLResult): + total_count: Optional[int] = Field(alias="totalCount", default=None) + page_info: PageInfoFragment = Field(alias="pageInfo") + edges: List[ProjectArtifactCollectionsProjectArtifactCollectionsEdges] + + +class ProjectArtifactCollectionsProjectArtifactCollectionsEdges(GQLResult): + node: Optional[ArtifactCollectionFragment] + + +ProjectArtifactCollections.model_rebuild() +ProjectArtifactCollectionsProject.model_rebuild() +ProjectArtifactCollectionsProjectArtifactCollections.model_rebuild() +ProjectArtifactCollectionsProjectArtifactCollectionsEdges.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_type.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_type.py new file mode 100644 index 0000000000000000000000000000000000000000..9de3c216e67ec42172d1c3afb306c6066fd750a3 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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 GQLResult + +from .fragments import ArtifactTypeFragment + + +class ProjectArtifactType(GQLResult): + project: Optional[ProjectArtifactTypeProject] + + +class ProjectArtifactTypeProject(GQLResult): + artifact_type: Optional[ArtifactTypeFragment] = Field(alias="artifactType") + + +ProjectArtifactType.model_rebuild() +ProjectArtifactTypeProject.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_types.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_types.py new file mode 100644 index 0000000000000000000000000000000000000000..3cef6f66d47e966749e73c30a0225a36f412cd2c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifact_types.py @@ -0,0 +1,37 @@ +# 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 GQLResult + +from .fragments import ArtifactTypeFragment, PageInfoFragment + + +class ProjectArtifactTypes(GQLResult): + project: Optional[ProjectArtifactTypesProject] + + +class ProjectArtifactTypesProject(GQLResult): + artifact_types: ProjectArtifactTypesProjectArtifactTypes = Field( + alias="artifactTypes" + ) + + +class ProjectArtifactTypesProjectArtifactTypes(GQLResult): + edges: List[ProjectArtifactTypesProjectArtifactTypesEdges] + page_info: PageInfoFragment = Field(alias="pageInfo") + + +class ProjectArtifactTypesProjectArtifactTypesEdges(GQLResult): + node: Optional[ArtifactTypeFragment] + + +ProjectArtifactTypes.model_rebuild() +ProjectArtifactTypesProject.model_rebuild() +ProjectArtifactTypesProjectArtifactTypes.model_rebuild() +ProjectArtifactTypesProjectArtifactTypesEdges.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifacts.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifacts.py new file mode 100644 index 0000000000000000000000000000000000000000..354b98ebf8979e70db438c5d0ff62624bfb1fe26 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/project_artifacts.py @@ -0,0 +1,54 @@ +# 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 GQLResult, Typename + +from .fragments import ArtifactFragment, PageInfoFragment + + +class ProjectArtifacts(GQLResult): + project: Optional[ProjectArtifactsProject] + + +class ProjectArtifactsProject(GQLResult): + artifact_type: Optional[ProjectArtifactsProjectArtifactType] = Field( + alias="artifactType" + ) + + +class ProjectArtifactsProjectArtifactType(GQLResult): + artifact_collection: Optional[ + ProjectArtifactsProjectArtifactTypeArtifactCollection + ] = Field(alias="artifactCollection") + + +class ProjectArtifactsProjectArtifactTypeArtifactCollection(GQLResult): + typename__: Typename[ + Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"] + ] + artifacts: Optional[ProjectArtifactsProjectArtifactTypeArtifactCollectionArtifacts] + + +class ProjectArtifactsProjectArtifactTypeArtifactCollectionArtifacts(GQLResult): + total_count: int = Field(alias="totalCount") + page_info: PageInfoFragment = Field(alias="pageInfo") + edges: List[ProjectArtifactsProjectArtifactTypeArtifactCollectionArtifactsEdges] + + +class ProjectArtifactsProjectArtifactTypeArtifactCollectionArtifactsEdges(GQLResult): + version: str + node: ArtifactFragment + + +ProjectArtifacts.model_rebuild() +ProjectArtifactsProject.model_rebuild() +ProjectArtifactsProjectArtifactType.model_rebuild() +ProjectArtifactsProjectArtifactTypeArtifactCollection.model_rebuild() +ProjectArtifactsProjectArtifactTypeArtifactCollectionArtifacts.model_rebuild() +ProjectArtifactsProjectArtifactTypeArtifactCollectionArtifactsEdges.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/registry_collections.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/registry_collections.py new file mode 100644 index 0000000000000000000000000000000000000000..08d419397e8b9b9742a85f4dfaf64d1ed9e5c77b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/registry_collections.py @@ -0,0 +1,46 @@ +# 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 GQLResult + +from .fragments import PageInfoFragment, RegistryCollectionFragment + + +class RegistryCollections(GQLResult): + organization: Optional[RegistryCollectionsOrganization] + + +class RegistryCollectionsOrganization(GQLResult): + org_entity: Optional[RegistryCollectionsOrganizationOrgEntity] = Field( + alias="orgEntity" + ) + + +class RegistryCollectionsOrganizationOrgEntity(GQLResult): + name: str + artifact_collections: Optional[ + RegistryCollectionsOrganizationOrgEntityArtifactCollections + ] = Field(alias="artifactCollections") + + +class RegistryCollectionsOrganizationOrgEntityArtifactCollections(GQLResult): + total_count: int = Field(alias="totalCount") + page_info: PageInfoFragment = Field(alias="pageInfo") + edges: List[RegistryCollectionsOrganizationOrgEntityArtifactCollectionsEdges] + + +class RegistryCollectionsOrganizationOrgEntityArtifactCollectionsEdges(GQLResult): + node: Optional[RegistryCollectionFragment] + + +RegistryCollections.model_rebuild() +RegistryCollectionsOrganization.model_rebuild() +RegistryCollectionsOrganizationOrgEntity.model_rebuild() +RegistryCollectionsOrganizationOrgEntityArtifactCollections.model_rebuild() +RegistryCollectionsOrganizationOrgEntityArtifactCollectionsEdges.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/registry_team_members.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/registry_team_members.py new file mode 100644 index 0000000000000000000000000000000000000000..3dd7f5d3705cb0cb15e6e8534ea9aeab8118d3e2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/registry_team_members.py @@ -0,0 +1,24 @@ +# 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 GQLResult + +from .fragments import TeamRegistryMemberFragment + + +class RegistryTeamMembers(GQLResult): + project: Optional[RegistryTeamMembersProject] + + +class RegistryTeamMembersProject(GQLResult): + team_members: List[TeamRegistryMemberFragment] = Field(alias="teamMembers") + + +RegistryTeamMembers.model_rebuild() +RegistryTeamMembersProject.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/registry_user_members.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/registry_user_members.py new file mode 100644 index 0000000000000000000000000000000000000000..55c1fe3e9b9145c395c91b418bf06228d8421547 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/registry_user_members.py @@ -0,0 +1,22 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/artifacts/ + +from __future__ import annotations + +from typing import List, Optional + +from wandb._pydantic import GQLResult + +from .fragments import UserRegistryMemberFragment + + +class RegistryUserMembers(GQLResult): + project: Optional[RegistryUserMembersProject] + + +class RegistryUserMembersProject(GQLResult): + members: List[UserRegistryMemberFragment] + + +RegistryUserMembers.model_rebuild() +RegistryUserMembersProject.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/registry_versions.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/registry_versions.py new file mode 100644 index 0000000000000000000000000000000000000000..de1f11d7d91f26eaab08cdd7cc24da73091ff879 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/registry_versions.py @@ -0,0 +1,45 @@ +# 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 GQLResult + +from .fragments import ArtifactMembershipFragment, PageInfoFragment + + +class RegistryVersions(GQLResult): + organization: Optional[RegistryVersionsOrganization] + + +class RegistryVersionsOrganization(GQLResult): + org_entity: Optional[RegistryVersionsOrganizationOrgEntity] = Field( + alias="orgEntity" + ) + + +class RegistryVersionsOrganizationOrgEntity(GQLResult): + name: str + artifact_memberships: Optional[ + RegistryVersionsOrganizationOrgEntityArtifactMemberships + ] = Field(alias="artifactMemberships") + + +class RegistryVersionsOrganizationOrgEntityArtifactMemberships(GQLResult): + page_info: PageInfoFragment = Field(alias="pageInfo") + edges: List[RegistryVersionsOrganizationOrgEntityArtifactMembershipsEdges] + + +class RegistryVersionsOrganizationOrgEntityArtifactMembershipsEdges(GQLResult): + node: Optional[ArtifactMembershipFragment] + + +RegistryVersions.model_rebuild() +RegistryVersionsOrganization.model_rebuild() +RegistryVersionsOrganizationOrgEntity.model_rebuild() +RegistryVersionsOrganizationOrgEntityArtifactMemberships.model_rebuild() +RegistryVersionsOrganizationOrgEntityArtifactMembershipsEdges.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/rename_registry.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/rename_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..73c55860a559883b4959fd87f1ad43189eb8aa8a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/rename_registry.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 GQLResult + +from .fragments import RegistryFragment + + +class RenameRegistry(GQLResult): + rename_project: Optional[RenameRegistryRenameProject] = Field(alias="renameProject") + + +class RenameRegistryRenameProject(GQLResult): + inserted: Optional[bool] + project: Optional[RegistryFragment] + + +RenameRegistry.model_rebuild() +RenameRegistryRenameProject.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/run_input_artifacts.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/run_input_artifacts.py new file mode 100644 index 0000000000000000000000000000000000000000..4f4cea9b55d2e719392f06a70e2e83690b905121 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/run_input_artifacts.py @@ -0,0 +1,41 @@ +# 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 GQLResult + +from .fragments import ArtifactFragment, PageInfoFragment + + +class RunInputArtifacts(GQLResult): + project: Optional[RunInputArtifactsProject] + + +class RunInputArtifactsProject(GQLResult): + run: Optional[RunInputArtifactsProjectRun] + + +class RunInputArtifactsProjectRun(GQLResult): + artifacts: Optional[RunInputArtifactsProjectRunArtifacts] + + +class RunInputArtifactsProjectRunArtifacts(GQLResult): + total_count: int = Field(alias="totalCount") + page_info: PageInfoFragment = Field(alias="pageInfo") + edges: List[RunInputArtifactsProjectRunArtifactsEdges] + + +class RunInputArtifactsProjectRunArtifactsEdges(GQLResult): + node: Optional[ArtifactFragment] + + +RunInputArtifacts.model_rebuild() +RunInputArtifactsProject.model_rebuild() +RunInputArtifactsProjectRun.model_rebuild() +RunInputArtifactsProjectRunArtifacts.model_rebuild() +RunInputArtifactsProjectRunArtifactsEdges.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/run_output_artifacts.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/run_output_artifacts.py new file mode 100644 index 0000000000000000000000000000000000000000..974cc30cbd9bd3908f86460bfb61820de9147d83 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/run_output_artifacts.py @@ -0,0 +1,41 @@ +# 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 GQLResult + +from .fragments import ArtifactFragment, PageInfoFragment + + +class RunOutputArtifacts(GQLResult): + project: Optional[RunOutputArtifactsProject] + + +class RunOutputArtifactsProject(GQLResult): + run: Optional[RunOutputArtifactsProjectRun] + + +class RunOutputArtifactsProjectRun(GQLResult): + artifacts: Optional[RunOutputArtifactsProjectRunArtifacts] + + +class RunOutputArtifactsProjectRunArtifacts(GQLResult): + total_count: int = Field(alias="totalCount") + page_info: PageInfoFragment = Field(alias="pageInfo") + edges: List[RunOutputArtifactsProjectRunArtifactsEdges] + + +class RunOutputArtifactsProjectRunArtifactsEdges(GQLResult): + node: Optional[ArtifactFragment] + + +RunOutputArtifacts.model_rebuild() +RunOutputArtifactsProject.model_rebuild() +RunOutputArtifactsProjectRun.model_rebuild() +RunOutputArtifactsProjectRunArtifacts.model_rebuild() +RunOutputArtifactsProjectRunArtifactsEdges.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/unlink_artifact.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/unlink_artifact.py new file mode 100644 index 0000000000000000000000000000000000000000..340482eb130662b076957b574b21b3f9cd5608b1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/unlink_artifact.py @@ -0,0 +1,19 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/artifacts/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLResult + + +class UnlinkArtifact(GQLResult): + result: Optional[UnlinkArtifactResult] + + +class UnlinkArtifactResult(GQLResult): + success: bool + + +UnlinkArtifact.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_artifact.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_artifact.py new file mode 100644 index 0000000000000000000000000000000000000000..93b69a7bca07394eef38e928d96e0a1f11281552 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_artifact.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 GQLResult + +from .fragments import ArtifactFragment + + +class UpdateArtifact(GQLResult): + result: Optional[UpdateArtifactResult] + + +class UpdateArtifactResult(GQLResult): + artifact: ArtifactFragment + + +UpdateArtifact.model_rebuild() +UpdateArtifactResult.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_artifact_portfolio.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_artifact_portfolio.py new file mode 100644 index 0000000000000000000000000000000000000000..2c3c5c3782eb8d6d99229a66f4d46c941e4d6488 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_artifact_portfolio.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 GQLResult + +from .fragments import ArtifactCollectionFragment + + +class UpdateArtifactPortfolio(GQLResult): + result: Optional[UpdateArtifactPortfolioResult] + + +class UpdateArtifactPortfolioResult(GQLResult): + artifact_collection: ArtifactCollectionFragment = Field(alias="artifactCollection") + + +UpdateArtifactPortfolio.model_rebuild() +UpdateArtifactPortfolioResult.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_artifact_sequence.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_artifact_sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..bf5a57c1d5e5399837dd4742e1e3dcd04f1285b7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_artifact_sequence.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 GQLResult + +from .fragments import ArtifactCollectionFragment + + +class UpdateArtifactSequence(GQLResult): + result: Optional[UpdateArtifactSequenceResult] + + +class UpdateArtifactSequenceResult(GQLResult): + artifact_collection: ArtifactCollectionFragment = Field(alias="artifactCollection") + + +UpdateArtifactSequence.model_rebuild() +UpdateArtifactSequenceResult.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_artifact_sequence_type.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_artifact_sequence_type.py new file mode 100644 index 0000000000000000000000000000000000000000..3aeac5df63d579e5cb39b94ac96fe1a5904ca8e2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_artifact_sequence_type.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 GQLResult + +from .fragments import ArtifactCollectionFragment + + +class UpdateArtifactSequenceType(GQLResult): + result: Optional[UpdateArtifactSequenceTypeResult] + + +class UpdateArtifactSequenceTypeResult(GQLResult): + artifact_collection: Optional[ArtifactCollectionFragment] = Field( + alias="artifactCollection" + ) + + +UpdateArtifactSequenceType.model_rebuild() +UpdateArtifactSequenceTypeResult.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_team_registry_role.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_team_registry_role.py new file mode 100644 index 0000000000000000000000000000000000000000..8bb11abdd86acf1573745f20d790e201413aeb81 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_team_registry_role.py @@ -0,0 +1,19 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/artifacts/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLResult + + +class UpdateTeamRegistryRole(GQLResult): + result: Optional[UpdateTeamRegistryRoleResult] + + +class UpdateTeamRegistryRoleResult(GQLResult): + success: bool + + +UpdateTeamRegistryRole.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_user_registry_role.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_user_registry_role.py new file mode 100644 index 0000000000000000000000000000000000000000..8b8cca373237909a42cd4858f5bd3fa618283520 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/update_user_registry_role.py @@ -0,0 +1,19 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/artifacts/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLResult + + +class UpdateUserRegistryRole(GQLResult): + result: Optional[UpdateUserRegistryRoleResult] + + +class UpdateUserRegistryRoleResult(GQLResult): + success: bool + + +UpdateUserRegistryRole.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/upsert_registry.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/upsert_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..a1114f6c8b775bdbfb259c469d64f45537e85602 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_generated/upsert_registry.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 GQLResult + +from .fragments import RegistryFragment + + +class UpsertRegistry(GQLResult): + upsert_model: Optional[UpsertRegistryUpsertModel] = Field(alias="upsertModel") + + +class UpsertRegistryUpsertModel(GQLResult): + inserted: Optional[bool] + project: Optional[RegistryFragment] + + +UpsertRegistry.model_rebuild() +UpsertRegistryUpsertModel.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_gqlutils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_gqlutils.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f4ee80bd189097c9b31383f7f757d0ad7c5658 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_gqlutils.py @@ -0,0 +1,161 @@ +from __future__ import annotations + +from contextlib import suppress +from dataclasses import dataclass +from functools import lru_cache +from typing import TYPE_CHECKING + +from wandb_gql import gql + +from wandb._iterutils import one +from wandb.proto.wandb_internal_pb2 import ServerFeature +from wandb.sdk.internal._generated import SERVER_FEATURES_QUERY_GQL, ServerFeaturesQuery + +if TYPE_CHECKING: + from wandb.apis.public import RetryingClient + from wandb.sdk.artifacts._generated.fetch_org_info_from_entity import ( + FetchOrgInfoFromEntityEntity, + ) + + +@lru_cache(maxsize=16) +def org_info_from_entity( + client: RetryingClient, entity: str +) -> FetchOrgInfoFromEntityEntity | None: + """Returns the organization info for a given entity.""" + from ._generated import FETCH_ORG_INFO_FROM_ENTITY_GQL, FetchOrgInfoFromEntity + + gql_op = gql(FETCH_ORG_INFO_FROM_ENTITY_GQL) + data = client.execute(gql_op, variable_values={"entity": entity}) + return FetchOrgInfoFromEntity.model_validate(data).entity + + +@lru_cache(maxsize=16) +def _server_features(client: RetryingClient) -> dict[str, bool]: + """Returns a mapping of `{server_feature_name (str) -> is_enabled (bool)}`. + + Results are cached per client instance. + """ + try: + response = client.execute(gql(SERVER_FEATURES_QUERY_GQL)) + 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): + return {} + raise + + result = ServerFeaturesQuery.model_validate(response) + if (server_info := result.server_info) and (features := server_info.features): + return {feat.name: feat.is_enabled for feat in features if feat} + return {} + + +def server_supports(client: RetryingClient, feature: str | int) -> bool: + """Return whether the current server supports the given feature. + + NOTE: This is deprecated. Please use `ServiceApi.feature_enabled()` when + possible, like in all public API code. + + 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 + try: + name = ServerFeature.Name(feature) if isinstance(feature, int) else feature + except ValueError: + return False # Invalid int-like value, assume unsupported + return _server_features(client).get(name) or False + + +@dataclass(frozen=True) +class OrgInfo: + org_name: str + entity_name: str + + def __contains__(self, other: str) -> bool: + return other in {self.org_name, self.entity_name} + + +def resolve_org_entity_name( + client: RetryingClient, + non_org_entity: str | None, + org_or_entity: str | None = None, +) -> str: + # Resolve the portfolio's org entity name. + # + # The `org_or_org_entity` parameter may be empty, an org display name, or an + # org entity name. + # + # If the server cannot fetch the portfolio's org name, return the provided + # value or raise an error if it is empty. Otherwise, return the fetched + # value after validating that the given organization, if provided, matches + # either the display or entity name. + if not non_org_entity: + raise ValueError("Entity name is required to resolve org entity name.") + + # Fetch candidate orgs to verify or identify the correct orgEntity name. + entity = org_info_from_entity(client, non_org_entity) + + # Parse possible organization(s) from the response... + # ---------------------------------------------------------------------------- + # If a team entity was provided, a single organization should exist under + # the team/org entity type. + if entity and (org := entity.organization) and (org_entity := org.org_entity): + # Ensure the provided name, if given, matches the org or org entity name before + # returning the org entity. + org_info = OrgInfo(org_name=org.name, entity_name=org_entity.name) + if (not org_or_entity) or (org_or_entity in org_info): + return org_entity.name + + # ---------------------------------------------------------------------------- + # If a personal entity was provided, the user may belong to multiple + # organizations. + if entity and (user := entity.user) and (orgs := user.organizations): + org_infos = [ + OrgInfo(org_name=org.name, entity_name=org_entity.name) + for org in orgs + if (org_entity := org.org_entity) + ] + if org_or_entity: + with suppress(StopIteration): + return next( + info.entity_name for info in org_infos if (org_or_entity in info) + ) + + if len(org_infos) == 1: + raise ValueError( + f"Expecting the organization name or entity name to match {org_infos[0].org_name!r} " + f"and cannot be linked/fetched with {org_or_entity!r}. " + "Please update the target path with the correct organization name." + ) + else: + raise ValueError( + "Personal entity belongs to multiple organizations " + f"and cannot be linked/fetched with {org_or_entity!r}. " + "Please update the target path with the correct organization name " + "or use a team entity in the entity settings." + ) + + else: + # If no input organization provided, error if entity belongs to: + # - multiple orgs, because we cannot determine which one to use. + # - no orgs, because there's nothing to use. + return one( + (org.entity_name for org in org_infos), + too_short=ValueError( + f"Unable to resolve an organization associated with personal entity: {non_org_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." + ), + too_long=ValueError( + f"Personal entity {non_org_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." + ), + ) + + raise ValueError(f"Unable to find organization for entity {non_org_entity!r}.") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_internal_artifact.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_internal_artifact.py new file mode 100644 index 0000000000000000000000000000000000000000..fabd09c35c21adaa9b9f185964fee2a9dd409f51 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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): + """An Artifact intended for internal use only. + + Includes artifacts of type `job`, `code` (with a `source-` collection name + prefix), `run_table` (with a `run-` collection name prefix), and any type that starts + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_models/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2b886b942e14290ede55f6ab0b779c55a484e976 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_models/__init__.py @@ -0,0 +1,13 @@ +"""Pydantic model classes and related helpers for artifacts code. + +Excludes GraphQL-generated classes. +""" + +__all__ = [ + "ArtifactsBase", + "RegistryData", + "ArtifactCollectionData", +] +from .artifact_collection import ArtifactCollectionData +from .base_model import ArtifactsBase +from .registry import RegistryData diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_models/artifact_collection.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_models/artifact_collection.py new file mode 100644 index 0000000000000000000000000000000000000000..8346d5cbd5b152e6fa27167b0afd93b6e818adbe --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_models/artifact_collection.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Tuple + +from pydantic import Field +from typing_extensions import Self + +from wandb._pydantic import field_validator + +from .base_model import ArtifactsBase + +if TYPE_CHECKING: + from wandb.sdk.artifacts._generated import ArtifactCollectionFragment + + +class ArtifactCollectionData(ArtifactsBase): + """Transport-free model for local `ArtifactCollection` data. + + For now, this is separated from the public `ArtifactCollection` model + to more easily ensure continuity in the public `ArtifactCollection` API. + + Note: + In a future change, consider making this the public `ArtifactCollection` class: + - Replace the existing `ArtifactCollection` class with this one. + - Rename this class to `ArtifactCollection`. + Note that this would be a breaking change. + """ + + typename__: str = Field(alias="__typename", frozen=True, repr=False) + """The GraphQL `__typename` for this object.""" + + id: str = Field(frozen=True, repr=False) + """The encoded GraphQL ID for this object.""" + + name: str = Field(min_length=1) # Disallow empty strings + """The name of this collection.""" + + type: str + """The artifact type of this collection.""" + + description: Optional[str] = None + """The description, if any, for this collection.""" + + created_at: str = Field(frozen=True) + """When this collection was created.""" + + updated_at: Optional[str] = None + """When this collection was last updated.""" + + project: str = Field(frozen=True) + """The name of this collection's project.""" + + entity: str = Field(frozen=True) + """The name of the entity that owns this collection's project.""" + + aliases: Optional[Tuple[str, ...]] = Field(default=None, frozen=True) + """All aliases assigned to artifact versions within this collection. + + Deliberately immutable since this should be a read-only attribute. + Collection aliases are gathered from member artifact versions and should + not be directly editable on the artifact collection itself. + + Note: + `None` indicates that aliases have not been fetched or parsed yet for + any reason, NOT that aliases are absent in this collection. + """ + + tags: List[str] = Field(default_factory=list) + """The tags assigned to this collection. + + Note that this is distinct from tags assigned to individual artifact + versions within the collection. + """ + + @field_validator("name", mode="plain") + def _validate_name(cls, v: str) -> str: + from wandb.sdk.artifacts._validators import validate_artifact_name + + return validate_artifact_name(v) + + @field_validator("tags", mode="plain") + def _validate_tags(cls, v: Any) -> list[str]: + """Ensure tags is a validated, deduped list of (str) tag names.""" + from wandb.sdk.artifacts._validators import validate_tags + + return validate_tags(v) + + @property + def is_sequence(self) -> bool: + """Return True if this collection is an `ArtifactSequence` (source collection).""" + from wandb._pydantic import gql_typename + from wandb.sdk.artifacts._generated import ArtifactSequenceTypeFields + + return self.typename__ == gql_typename(ArtifactSequenceTypeFields) + + @classmethod + def from_fragment(cls, obj: ArtifactCollectionFragment) -> Self: + """Instantiate this type from a GraphQL fragment.""" + if obj.project is None: + raise ValueError(f"Missing project info in {type(obj)!r} data") + + return cls( + typename__=obj.typename__, + id=obj.id, + name=obj.name, + type=obj.type.name, + description=obj.description, + created_at=obj.created_at, + updated_at=obj.updated_at, + project=obj.project.name, + entity=obj.project.entity.name, + tags=[e.node.name for e in obj.tags.edges if e.node], + aliases=None, + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_models/base_model.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_models/base_model.py new file mode 100644 index 0000000000000000000000000000000000000000..a8dcbb5038054e6841b13e892072941f3c418ffa --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_models/manifest.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_models/manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..e93a9368e9bb0fd6ec50c9acaea09a453a7338ec --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_models/manifest.py @@ -0,0 +1,27 @@ +from typing import Any, Dict, Literal, final + +from wandb._pydantic import field_validator, to_camel +from wandb.sdk.artifacts.artifact_manifest_entry import ArtifactManifestEntry + +from .base_model import ArtifactsBase +from .storage import StoragePolicyConfig + + +@final +class ArtifactManifestV1Data(ArtifactsBase, alias_generator=to_camel): + """Data model for the v1 artifact manifest.""" + + version: Literal[1] + + contents: Dict[str, ArtifactManifestEntry] + + storage_policy: str + storage_policy_config: StoragePolicyConfig + + @field_validator("contents", mode="before") + def _validate_entries(cls, v: Any) -> Any: + # The dict keys should be the `entry.path` values, but they've + # historically been dropped from the JSON objects. This restores + # them on instantiation. + # Pydantic will handle converting dicts -> ArtifactManifestEntries. + return {path: {**dict(entry), "path": path} for path, entry in v.items()} diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_models/pagination.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_models/pagination.py new file mode 100644 index 0000000000000000000000000000000000000000..89872a1a9d77368ee8c46a72a13763344a940cfe --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_models/pagination.py @@ -0,0 +1,27 @@ +"""Artifacts-specific data models for handling paginated results from GraphQL queries.""" + +from wandb._pydantic import Connection, ConnectionWithTotal + +from .._generated.fragments import ( + ArtifactCollectionFragment, + ArtifactFragment, + ArtifactMembershipFragment, + ArtifactTypeFragment, + FileFragment, + FileWithUrlFragment, + RegistryCollectionFragment, + RegistryFragment, +) + +ArtifactTypeConnection = Connection[ArtifactTypeFragment] +ArtifactCollectionConnection = ConnectionWithTotal[ArtifactCollectionFragment] +ProjectArtifactCollectionConnection = Connection[ArtifactCollectionFragment] +ArtifactMembershipConnection = Connection[ArtifactMembershipFragment] + +FileWithUrlConnection = Connection[FileWithUrlFragment] +ArtifactFileConnection = Connection[FileFragment] + +RunArtifactConnection = ConnectionWithTotal[ArtifactFragment] + +RegistryConnection = Connection[RegistryFragment] +RegistryCollectionConnection = ConnectionWithTotal[RegistryCollectionFragment] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_models/registry.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_models/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..852a5418417ffa06f4e6ad8e93a43d74788d6238 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_models/registry.py @@ -0,0 +1,106 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from pydantic import Field +from typing_extensions import Self + +from wandb._pydantic import GQLId, field_validator +from wandb._strutils import nameof +from wandb.apis.public.registries._freezable_list import AddOnlyArtifactTypesList +from wandb.apis.public.registries._utils import Visibility + +from .base_model import ArtifactsBase + +if TYPE_CHECKING: + from wandb.sdk.artifacts._generated import RegistryFragment + + +class RegistryData(ArtifactsBase): + """Transport-free model for local `Registry` data. + + For now, this is separated from the public `Registry` class + to more easily ensure continuity in the public `Registry` API. + """ + + id: GQLId = Field(frozen=True) + """The unique, encoded ID for this registry.""" + + created_at: str = Field(frozen=True) + """When this registry was created.""" + + updated_at: Optional[str] = Field(frozen=True) + """When this registry was last updated.""" + + organization: str = Field(frozen=True) + """The organization of the registry.""" + + entity: str = Field(frozen=True) + """The organization entity of the registry.""" + + name: str = Field(min_length=1) # Disallow empty strings + """The name of the registry without the `wandb-registry-` project prefix.""" + + description: Optional[str] = None + """The description, if any, of the registry.""" + + allow_all_artifact_types: bool + """Whether all artifact types are allowed in the registry.""" + + artifact_types: AddOnlyArtifactTypesList = Field( + default_factory=AddOnlyArtifactTypesList + ) + """The artifact types allowed in the registry. + + The meaning of this list depends on `allow_all_artifact_types`: + - If True: `artifact_types` are the previously saved or currently used + types in the registry. + - If False: `artifact_types` are the only allowed artifact types in the + registry. + """ + + visibility: Visibility = Field(alias="access") + """The visibility of the registry.""" + + @property + def full_name(self) -> str: + """The project name with the expected `wandb-registry-` prefix.""" + from wandb.sdk.artifacts._validators import REGISTRY_PREFIX + + return f"{REGISTRY_PREFIX}{self.name}" + + @field_validator("artifact_types", mode="plain") + def _validate_artifact_types(cls, v: Any) -> AddOnlyArtifactTypesList: + """Coerce `artifact_types` to an AddOnlyArtifactTypesList.""" + from wandb.sdk.artifacts._generated.fragments import ( + RegistryFragmentArtifactTypes, + ) + + if isinstance(v, RegistryFragmentArtifactTypes): + # This is a GQL connection object, so we need to extract the node names + return AddOnlyArtifactTypesList(e.node.name for e in v.edges if e.node) + + # By default, assume we were passed an iterable of strings + return AddOnlyArtifactTypesList(v) + + @classmethod + def from_fragment(cls, obj: RegistryFragment) -> Self: + from wandb.sdk.artifacts._validators import remove_registry_prefix + + if not obj.entity.organization: + raise ValueError( + f"Unable to parse registry organization from {nameof(type(obj))!r} object" + ) + + return cls( + id=obj.id, + created_at=obj.created_at, + updated_at=obj.updated_at, + organization=obj.entity.organization.name, + entity=obj.entity.name, + name=remove_registry_prefix(obj.name), + description=obj.description, + allow_all_artifact_types=obj.allow_all_artifact_types, + artifact_types=obj.artifact_types, + visibility=obj.access, + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_models/storage.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_models/storage.py new file mode 100644 index 0000000000000000000000000000000000000000..3d3b6243840d82ea15e04467fde349fe09848382 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_models/storage.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +from typing import Optional + +from pydantic import ConfigDict, StrictStr +from typing_extensions import Self + +from wandb._pydantic import to_camel +from wandb.sdk.artifacts.storage_layout import StorageLayout + +from .base_model import ArtifactsBase + + +class StoragePolicyConfig(ArtifactsBase): + model_config = ConfigDict( + frozen=True, + alias_generator=to_camel, + str_min_length=1, + str_strip_whitespace=True, + ) + + storage_layout: Optional[StorageLayout] = None + storage_region: Optional[StrictStr] = None + + @classmethod + def from_env( + cls, layout: StorageLayout | None = None, region: str | None = None + ) -> Self: + """Instantiate with default values magically configured from the environment.""" + return cls( + storage_layout=layout or StorageLayout.from_env(), storage_region=region + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_validators.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_validators.py new file mode 100644 index 0000000000000000000000000000000000000000..c5f6645f27099caa8119b8b18a6af137016165d5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/_validators.py @@ -0,0 +1,350 @@ +"""Internal validation utilities that are specific to artifacts.""" + +from __future__ import annotations + +import json +import re +from collections.abc import Callable +from dataclasses import dataclass, field, replace +from functools import singledispatch, wraps +from typing import TYPE_CHECKING, Any, Concatenate, Literal, Optional, TypeVar + +from pydantic.dataclasses import dataclass as pydantic_dataclass +from typing_extensions import ParamSpec, Self + +from wandb._iterutils import always_list, unique_list +from wandb._pydantic import from_json +from wandb._strutils import nameof +from wandb.util import json_friendly_val + +from .exceptions import ArtifactFinalizedError, ArtifactNotLoggedError + +if TYPE_CHECKING: + from collections.abc import Iterable + from typing import 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 + +NAME_MAXLEN: Final[int] = 128 + +INVALID_ARTIFACT_NAME_CHARS: Final[frozenset[str]] = frozenset("/") +INVALID_URL_CHARS: Final[frozenset[str]] = frozenset("/\\#?%:\r\n") +ARTIFACT_SEP_CHARS: Final[frozenset[str]] = frozenset("/:") + + +@dataclass +class LinkArtifactFields: + """Keep this list updated with fields where linked and source artifacts differ.""" + + entity_name: str + project_name: str + name: str + version: str + aliases: list[str] + + # These fields shouldn't be user-editable, linked artifacts always have these values + _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) > NAME_MAXLEN: + trunc_name = f"{name[:NAME_MAXLEN]} ..." + raise ValueError( + f"Artifact name is longer than {NAME_MAXLEN!r} characters: {trunc_name!r}" + ) + + if INVALID_ARTIFACT_NAME_CHARS.intersection(name): + raise ValueError( + "Artifact names must not contain any of the following characters: " + f"{', '.join(sorted(INVALID_ARTIFACT_NAME_CHARS))}. Got: {name!r}" + ) + + return name + + +def validate_project_name(name: str) -> str: + """Validate a project name according to W&B rules. + + Return the original name if successful. + + Args: + name: The project name string. + + Raises: + ValueError: If the name is invalid (too long or contains invalid characters). + """ + if not name: + raise ValueError("Project name cannot be empty") + if not (registry_name := name.removeprefix(REGISTRY_PREFIX)): + raise ValueError("Registry name cannot be empty") + + if len(name) > NAME_MAXLEN: + if registry_name != name: + msg = f"Invalid registry name {registry_name!r}, must be {NAME_MAXLEN - len(REGISTRY_PREFIX)!r} characters or less" + else: + msg = f"Invalid project name {name!r}, must be {NAME_MAXLEN!r} characters or less" + raise ValueError(msg) + + # Find the first occurrence of any invalid character + if invalid_chars := set(INVALID_URL_CHARS).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}" + ) + return name + + +def validate_aliases(aliases: Iterable[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) + if any(ARTIFACT_SEP_CHARS.intersection(name) for name in aliases_list): + invalid_chars = ", ".join(sorted(map(repr, ARTIFACT_SEP_CHARS))) + raise ValueError( + f"Aliases must not contain any of the following characters: {invalid_chars}" + ) + return aliases_list + + +def validate_artifact_types(types: Iterable[str] | str) -> list[str]: + """Validate the artifact type names and return them as a list.""" + types_list = always_list(types) + if any(ARTIFACT_SEP_CHARS.intersection(name) for name in types_list): + invalid_chars = ", ".join(sorted(map(repr, ARTIFACT_SEP_CHARS))) + raise ValueError( + f"Artifact types must not contain any of the following characters: {invalid_chars}" + ) + if any(len(name) > NAME_MAXLEN for name in types_list): + raise ValueError( + f"Artifact types must be less than or equal to {NAME_MAXLEN!r} characters" + ) + return types_list + + +TAG_REGEX: re.Pattern[str] = re.compile(r"^[-\w]+( +[-\w]+)*$") +"""Regex pattern for valid tag names.""" + + +def validate_tags(tags: Iterable[str] | str) -> list[str]: + """Validate artifact tag names and return them as a deduped list. + + In the case of duplicates, keep the first tag and 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 + + +@singledispatch +def validate_metadata(metadata: dict[str, Any] | str | None) -> dict[str, Any]: + """Validate the artifact metadata and return it as a dict.""" + raise TypeError(f"Cannot parse {type(metadata)} as artifact metadata") + + +@validate_metadata.register(type(None)) +@validate_metadata.register(str) +def _(metadata: str | None) -> dict[str, Any]: + return validate_metadata(from_json(metadata)) if metadata else {} + + +@validate_metadata.register(dict) +def _(metadata: dict[str, Any]) -> dict[str, Any]: + # NOTE: The backend doesn't currently allow JS-compatible `+/-Infinity` values. + # Forbid them here to avoid surprises, but revisit if we add future backend support. + # Note that prior behavior already converts `NaN` values to `None` (client-side). + metadata = from_json(json.dumps(json_friendly_val(metadata), allow_nan=False)) + if len(metadata) > MAX_ARTIFACT_METADATA_KEYS: + raise ValueError( + f"Artifact must not have more than {MAX_ARTIFACT_METADATA_KEYS!r} metadata keys." + ) + return metadata + + +def validate_ttl_duration_seconds(ttl_duration_seconds: int) -> int | None: + """Validate the `ttlDurationSeconds` value from a GraphQL response. + + A non-positive value indicates that TTL is DISABLED (-2), which we + convert to `None`. + """ + return ttl_duration_seconds if ttl_duration_seconds > 0 else 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]: + """Ensure an artifact method runs only 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]: + """Ensure an `Artifact` method runs only if the artifact is not 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} is not a registry project. Must start with: {REGISTRY_PREFIX!r}" + ) + return project.removeprefix(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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact.py new file mode 100644 index 0000000000000000000000000000000000000000..05cea3ae3fc63cda62db94352841ad3bd84c5c3b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact.py @@ -0,0 +1,2806 @@ +"""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 collections.abc import Iterator, Sequence +from concurrent.futures import Executor, ThreadPoolExecutor, as_completed +from copy import copy +from dataclasses import asdict, replace +from datetime import timedelta +from itertools import filterfalse +from pathlib import Path, PurePosixPath +from typing import ( # noqa: UP035 (can't use `type` - shadows `Artifact.type`) + IO, + TYPE_CHECKING, + Any, + Callable, + Final, + Literal, + Type, +) +from urllib.parse import quote, urljoin, urlparse + +from pydantic import NonNegativeInt + +import wandb +from wandb import data_types, env +from wandb._iterutils import one, unique_list +from wandb._pydantic import from_json +from wandb._strutils import nameof +from wandb.apis.normalize import normalize_exceptions +from wandb.apis.public import ArtifactCollection, ArtifactFiles, Run +from wandb.apis.public.service_api import ServiceApi +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_telemetry_pb2 import Deprecated +from wandb.sdk import wandb_setup +from wandb.sdk.data_types._dtypes import Type as WBType +from wandb.sdk.data_types._dtypes import TypeRegistry +from wandb.sdk.lib import retry, telemetry +from wandb.sdk.lib.deprecation import warn_and_record_deprecation +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_fast_id, 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 ._gqlutils import org_info_from_entity, resolve_org_entity_name, server_supports +from ._validators import ensure_logged, ensure_not_finalized +from .artifact_download_logger import ArtifactDownloadLogger +from .artifact_instance_cache import ( + artifact_instance_cache, + artifact_instance_cache_by_client_id, +) +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 +from .storage_policies._factories import make_http_session +from .storage_policies._multipart import should_multipart_download + +reset_path = vendor_setup() + +from wandb_gql import gql # noqa: E402 + +reset_path() + +if TYPE_CHECKING: + from collections.abc import Iterable + + from wandb.apis.public import RetryingClient + + from ._generated import ArtifactFragment, ArtifactMembershipFragment + from ._models.pagination import FileWithUrlConnection + from ._validators import FullArtifactPath, LinkArtifactFields + +logger = logging.getLogger(__name__) + + +_MB: Final[int] = 1024 * 1024 +_FILE_EXECUTOR_WORKERS = 32 +_MP_EXECUTOR_WORKERS = 32 + + +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. + + 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: + from wandb.sdk.artifacts._internal_artifact import InternalArtifact + + from ._validators import ( + validate_artifact_name, + validate_artifact_type, + validate_metadata, + ) + + 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!r}" + ) + + if incremental and not isinstance(self, InternalArtifact): + termwarn("Using experimental arg `incremental`") + + # Internal. + self._client: RetryingClient | None = None + self._service_api: ServiceApi | 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 + + # Client IDs don't need cryptographic strength, so use a faster implementation. + self._client_id: str = generate_fast_id(128) + self._sequence_client_id: str = generate_fast_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: + warn_and_record_deprecation( + feature=Deprecated(artifact__init_use_as=True), + 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 + + # NOTE: These fields only reflect the last fetched response from the + # server, if any. If the ArtifactManifest has already been fetched and/or + # populated locally, it should take priority when determining these values. + self._size: NonNegativeInt | None = None + self._digest: str | None = None + + self._manifest: ArtifactManifest | None = ArtifactManifestV1( + storage_policy=make_storage_policy(region=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] = [] + + self._fetch_file_urls_decorated: Callable[..., Any] | None = None + + # Cache. + artifact_instance_cache_by_client_id[self._client_id] = self + + def __repr__(self) -> str: + return f"" + + def _get_service_api(self) -> ServiceApi: + if self._service_api is None: + settings = wandb_setup.singleton().settings.model_copy() + settings.entity = self._source_entity or self._entity or settings.entity + self._service_api = ServiceApi(settings=settings) + return self._service_api + + @classmethod + def _from_id( + cls, + artifact_id: str, + client: RetryingClient, + *, + service_api: ServiceApi | None = None, + ) -> Artifact | None: + from ._generated import ARTIFACT_BY_ID_GQL, ArtifactByID + from ._validators import FullArtifactPath + + if cached_artifact := artifact_instance_cache.get(artifact_id): + return cached_artifact + + gql_op = gql(ARTIFACT_BY_ID_GQL) + + data = client.execute(gql_op, 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, service_api=service_api) + + @classmethod + def _membership_from_name( + cls, + *, + path: FullArtifactPath, + client: RetryingClient, + service_api: ServiceApi | None = None, + ) -> Artifact: + from ._generated import ( + ARTIFACT_MEMBERSHIP_BY_NAME_GQL, + ArtifactMembershipByName, + ) + + if not server_supports(client, pb.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." + ) + + gql_op = gql(ARTIFACT_MEMBERSHIP_BY_NAME_GQL) + gql_vars = {"entity": path.prefix, "project": path.project, "name": path.name} + data = client.execute(gql_op, variable_values=gql_vars) + result = ArtifactMembershipByName.model_validate(data) + + if not (project := result.project): + msg = f"project {path.project!r} not found under entity {path.prefix!r}" + raise ValueError(msg) + + if not (membership := project.artifact_collection_membership): + entity_project = f"{path.prefix}/{path.project}" + msg = f"artifact membership {path.name!r} not found in {entity_project!r}" + raise ValueError(msg) + + return cls._from_membership( + membership, + target=path, + client=client, + service_api=service_api, + ) + + @classmethod + def _from_name( + cls, + *, + path: FullArtifactPath, + client: RetryingClient, + service_api: ServiceApi | None = None, + enable_tracking: bool = False, + ) -> Artifact: + from ._generated import ARTIFACT_BY_NAME_GQL, ArtifactByName + + if server_supports(client, pb.PROJECT_ARTIFACT_COLLECTION_MEMBERSHIP): + return cls._membership_from_name( + path=path, + client=client, + service_api=service_api, + ) + + gql_vars = { + "entity": path.prefix, + "project": path.project, + "name": path.name, + "enableTracking": enable_tracking, + } + gql_op = gql(ARTIFACT_BY_NAME_GQL) + data = client.execute(gql_op, variable_values=gql_vars) + result = ArtifactByName.model_validate(data) + + if not (project := result.project): + msg = f"project {path.project!r} not found in entity {path.prefix!r}" + raise ValueError(msg) + + if not (artifact := project.artifact): + entity_project = f"{path.prefix}/{path.project}" + msg = f"artifact {path.name!r} not found in {entity_project!r}" + raise ValueError(msg) + + return cls._from_attrs(path, artifact, client, service_api=service_api) + + @classmethod + def _from_membership( + cls, + membership: ArtifactMembershipFragment, + target: FullArtifactPath, + client: RetryingClient, + service_api: ServiceApi | None = None, + ) -> Artifact: + from ._validators import is_artifact_registry_project + + 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}'." + ) + + # Update the target path to use the actual project/entity names returned in the + # response, in case they differ from the original target path + # E.g. uppercase vs lowercase, migrated legacy model registry, etc. + new_target = replace(target, prefix=proj.entity.name, project=proj.name) + + 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, + membership=membership, + service_api=service_api, + ) + + @classmethod + def _from_attrs( + cls, + path: FullArtifactPath, + src_art: ArtifactFragment, + client: RetryingClient, + *, + service_api: ServiceApi | None = None, + # aliases/version_index are taken from the membership, if given + membership: ArtifactMembershipFragment | None = None, + ) -> Artifact: + # Placeholder is required to skip validation. + artifact = cls("placeholder", type="placeholder") + artifact._client = client + artifact._service_api = service_api + artifact._entity = path.prefix + artifact._project = path.project + artifact._name = path.name + + artifact._assign_attrs(src_art, membership=membership) + + 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, + src_art: ArtifactFragment, + *, + # aliases/version_index are taken from the membership, if given + membership: ArtifactMembershipFragment | None = None, + is_link: bool | None = None, + ) -> None: + """Update this Artifact's attributes using the server response.""" + from ._validators import validate_metadata, validate_ttl_duration_seconds + + self._id = src_art.id + + src_collection = src_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{src_art.version_index}" + self._source_version = f"v{src_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 = src_art.artifact_type.name + self._description = src_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 membership: + aliases = [a.alias for a in membership.aliases] + elif src_art.aliases: + entity = self._entity + project = self._project + collection = self._name.split(":")[0] + aliases = [ + a.alias + for a in src_art.aliases + if ( + (alias_coll := a.artifact_collection) + and (alias_proj := alias_coll.project) + and alias_proj.entity.name == entity + and alias_proj.name == project + and alias_coll.name == collection + ) + ] + else: + aliases = [] + + version_aliases = list(filter(alias_is_version_index, aliases)) + other_aliases = list(filterfalse(alias_is_version_index, aliases)) + + try: + version = one( + version_aliases, too_short=TooFewItemsError, too_long=TooManyItemsError + ) + except TooFewItemsError: + # default to the membership version if passed to this method, + # otherwise fallback to the source version + if membership and (m_version_index := membership.version_index) is not None: + version = f"v{m_version_index}" + else: + version = f"v{src_art.version_index}" + 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 = copy(other_aliases) + self._saved_aliases = copy(other_aliases) + + self._tags = [tag.name for tag in src_art.tags] + self._saved_tags = copy(self._tags) + + self._metadata = validate_metadata(src_art.metadata) + + self._ttl_duration_seconds = validate_ttl_duration_seconds( + src_art.ttl_duration_seconds + ) + self._ttl_is_inherited = src_art.ttl_is_inherited + + self._state = ArtifactState(src_art.state) + self._size = src_art.size + self._digest = src_art.digest + + self._manifest = None + + self._commit_hash = src_art.commit_hash + self._file_count = src_art.file_count + self._created_at = src_art.created_at + self._updated_at = src_art.updated_at + self._history_step = src_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._service_api = self._service_api + 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 this 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 is retrieved from. + + A collection is an ordered group of artifact versions. + If this artifact is retrieved from a collection that it is linked to, + return that collection. Otherwise, return the collection + that the artifact version originates from. + + The collection that an artifact originates from is known as + the source sequence. + """ + if (client := self._client) is None: + raise RuntimeError("Client not initialized") + base_name = self.name.split(":")[0] + return ArtifactCollection( + client, + self.entity, + self.project, + base_name, + self.type, + service_api=self._service_api, + ) + + @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. + """ + if (client := self._client) is None: + raise RuntimeError("Client not initialized") + base_name = self.source_name.split(":")[0] + return ArtifactCollection( + client, + self.source_entity, + self.source_project, + base_name, + self.type, + service_api=self._service_api, + ) + + @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 this 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, which is the original logged artifact. + + If this artifact is a source artifact (`artifact.is_link == False`), + it will return itself. + """ + from ._validators import FullArtifactPath + + if not self.is_link: + return self + if self._source_artifact is None: + if (client := 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=client, + service_api=self._get_service_api(), + ) + 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. + """ + from ._validators import is_artifact_registry_project + + 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: + from ._validators import remove_registry_prefix + + if not all( + [ + base_url, + self.entity, + self.project, + self.collection.name, + self._version, + ] + ): + return "" + + try: + org_name = org_info_from_entity(self._client, self.entity).organization.name # type: ignore[union-attr] + except (AttributeError, ValueError): + return "" + + selection_path = quote( + f"{self.entity}/{self.project}/{self.collection.name}", safe="" + ) + return urljoin( + base_url, + f"orgs/{org_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. + """ + from ._validators import validate_metadata + + 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 `datetime.timedelta` 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/models/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.""" + from ._validators import validate_aliases + + 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. + """ + from ._validators import validate_tags + + 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.""" + warn_and_record_deprecation( + feature=Deprecated(artifact__use_as=True), + 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 self._manifest is None: + self._manifest = self._fetch_manifest() + return self._manifest + + def _fetch_manifest(self) -> ArtifactManifest: + """Fetch, parse, and load the full ArtifactManifest.""" + from ._generated import FETCH_ARTIFACT_MANIFEST_GQL, FetchArtifactManifest + + if (client := self._client) is None: + raise RuntimeError("Client not initialized for artifact queries") + + # From the GraphQL API, get the (expiring) directUrl for downloading the manifest. + gql_op = gql(FETCH_ARTIFACT_MANIFEST_GQL) + gql_vars = {"id": self.id} + data = client.execute(gql_op, variable_values=gql_vars) + result = FetchArtifactManifest.model_validate(data) + + # Now fetch the actual manifest contents from the directUrl. + if (artifact := result.artifact) and (manifest := artifact.current_manifest): + # Create a short lived session instead of using requests.get() + # because make_http_session() adds http headers from env vars. + # Artifact manifest json is also downloaded from object storage + # using presigned urls like artifact files, which requires adding + # extra http headers when user specifies them in env vars. + # + # FIXME: For successive/repeated calls to `manifest`, figure out + # how to reuse a single `requests.Session` within the constraints + # of the current API. Creating a new session for _each_ fetch is + # wasteful and introduces noticeable perf overhead when e.g. + # downloading many artifacts sequentially or concurrently. The + # storage policy's session is also not reused across different + # artifacts. + with make_http_session() as session: + response = session.get(manifest.file.direct_url) + return ArtifactManifest.from_manifest_json(from_json(response.content)) + + raise ValueError("Failed to fetch artifact 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. + """ + # Use the last fetched value of `Artifact.digest` ONLY if present AND the manifest + # has not been fetched and/or populated locally. + # Otherwise, use the manifest directly to recalculate the digest, as its contents + # may have been locally modified. + return ( + self._digest + if (self._manifest is None) and (self._digest is not None) + else self.manifest.digest() + ) + + @property + def size(self) -> int: + """The total size of the artifact in bytes. + + Includes any references tracked by this artifact. + """ + # Use the last fetched value of `Artifact.size` ONLY if present AND the manifest + # has not been fetched and/or populated locally. + # Otherwise, use the manifest directly to recalculate the size, as its contents + # may have been locally modified. + # + # NOTE on choice of GQL field: `Artifact.size` counts references, while + # `Artifact.storageBytes` does not. + return ( + self._size + if (self._manifest is None) and (self._size is not None) + else self.manifest.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 which logged history metrics for this artifact's source run. + + 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: + from ._generated import ARTIFACT_BY_ID_GQL, ArtifactByID + + if (client := self._client) is None: + raise RuntimeError("Client not initialized for artifact queries") + + gql_op = gql(ARTIFACT_BY_ID_GQL) + data = client.execute(gql_op, 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.""" + from ._generated import UPDATE_ARTIFACT_GQL, UpdateArtifact, UpdateArtifactInput + from ._validators import FullArtifactPath, validate_tags + + if (client := self._client) is None: + raise RuntimeError("Client not initialized for artifact mutations") + + entity, project, collection = self.entity, self.project, self.name.split(":")[0] + + old_aliases, new_aliases = set(self._saved_aliases), set(self.aliases) + target = FullArtifactPath(prefix=entity, project=project, name=collection) + self._add_aliases(new_aliases - old_aliases, target=target) + self._delete_aliases(old_aliases - new_aliases, target=target) + self._saved_aliases = copy(self.aliases) + + old_tags, new_tags = set(self._saved_tags), set(self.tags) + + gql_op = gql(UPDATE_ARTIFACT_GQL) + gql_input = UpdateArtifactInput( + artifact_id=self.id, + description=self.description, + metadata=json_dumps_safer(self.metadata), + ttl_duration_seconds=self._ttl_duration_seconds_to_gql(), + tags_to_add=[{"tagName": t} for t in validate_tags(new_tags - old_tags)], + tags_to_delete=[{"tagName": t} for t in validate_tags(old_tags - new_tags)], + ) + gql_vars = {"input": gql_input.model_dump()} + data = client.execute(gql_op, variable_values=gql_vars) + + result = UpdateArtifact.model_validate(data).result + 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 + + def _add_aliases(self, alias_names: set[str], target: FullArtifactPath) -> None: + from ._generated import ADD_ALIASES_GQL, AddAliasesInput + + if (client := self._client) is None: + raise RuntimeError("Client not initialized for artifact mutations") + + # If there aren't any aliases to add, we can skip the GraphQL call. + if alias_names: + target_props = { + "entityName": target.prefix, + "projectName": target.project, + "artifactCollectionName": target.name, + } + alias_inputs = [{**target_props, "alias": name} for name in alias_names] + gql_op = gql(ADD_ALIASES_GQL) + gql_input = AddAliasesInput(artifact_id=self.id, aliases=alias_inputs) + gql_vars = {"input": gql_input.model_dump()} + try: + client.execute(gql_op, variable_values=gql_vars) + except CommError as e: + msg = ( + "You do not have permission to add" + f" {'at least one of the following aliases' if len(alias_names) > 1 else 'the following alias'}" + f" to this artifact: {alias_names!r}" + ) + raise CommError(msg) from e + + def _delete_aliases(self, alias_names: set[str], target: FullArtifactPath) -> None: + from ._generated import DELETE_ALIASES_GQL, DeleteAliasesInput + + if (client := self._client) is None: + raise RuntimeError("Client not initialized for artifact mutations") + + # If there aren't any aliases to delete, we can skip the GraphQL call. + if alias_names: + target_props = { + "entityName": target.prefix, + "projectName": target.project, + "artifactCollectionName": target.name, + } + alias_inputs = [{**target_props, "alias": name} for name in alias_names] + gql_op = gql(DELETE_ALIASES_GQL) + gql_input = DeleteAliasesInput(artifact_id=self.id, aliases=alias_inputs) + gql_vars = {"input": gql_input.model_dump()} + try: + client.execute(gql_op, variable_values=gql_vars) + except CommError as e: + msg = ( + f"You do not have permission to delete" + f" {'at least one of the following aliases' if len(alias_names) > 1 else 'the following alias'}" + f" from this artifact: {alias_names!r}" + ) + raise CommError(msg) from e + + # 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/models/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)`.""" + warn_and_record_deprecation( + feature=Deprecated(artifact__get_path=True), + 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, + service_api=self._get_service_api(), + ) + 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 = 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 + + # 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.run_id.value = stream_id + + service = wl.ensure_service() + interface = service.inform_init(settings=settings, run_id=stream_id) + else: + assert wandb.run._interface + interface = wandb.run._interface + + handle = 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, mp_executor: Executor + ) -> None: + multipart_executor = ( + mp_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 + except IsADirectoryError: + wandb.termwarn( + f"Unable to download file {entry.path!r} as there is a directory with the same path, skipping." + ) + return + except NotADirectoryError: + wandb.termwarn( + f"Unable to download file {entry.path!r} as there is a file with the same path as a directory this file is expected to be in, skipping." + ) + return + download_logger.notify_downloaded() + + with ( + ThreadPoolExecutor(max_workers=_FILE_EXECUTOR_WORKERS) as file_executor, + ThreadPoolExecutor(max_workers=_MP_EXECUTOR_WORKERS) as mp_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( + file_executor.submit( + _download_entry, entry, mp_executor=mp_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 instead. + # Consider this for a future change, or (depending on appetite for risk) + # 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) + + def _build_fetch_file_urls_wrapper(self) -> Callable[..., Any]: + import requests + + @retry.retriable( + retry_timedelta=timedelta(minutes=3), + retryable_exceptions=(requests.RequestException), + ) + def _impl(cursor: str | None, per_page: int = 5000) -> FileWithUrlConnection: + from ._generated import ( + GET_ARTIFACT_FILE_URLS_GQL, + GET_ARTIFACT_MEMBERSHIP_FILE_URLS_GQL, + GetArtifactFileUrls, + GetArtifactMembershipFileUrls, + ) + from ._models.pagination import FileWithUrlConnection + + if self._client is None: + raise RuntimeError("Client not initialized") + + if server_supports(self._client, pb.ARTIFACT_COLLECTION_MEMBERSHIP_FILES): + query = gql(GET_ARTIFACT_MEMBERSHIP_FILE_URLS_GQL) + gql_vars = { + "entity": self.entity, + "project": self.project, + "collection": self.name.split(":")[0], + "alias": self.version, + "cursor": cursor, + "perPage": per_page, + } + data = self._client.execute(query, variable_values=gql_vars, timeout=60) + membership_result = GetArtifactMembershipFileUrls.model_validate(data) + + if not ( + (project := membership_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 FileWithUrlConnection.model_validate(files) + else: + query = gql(GET_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) + file_result = GetArtifactFileUrls.model_validate(data) + + if not ( + (artifact := file_result.artifact) + and (artifact_files := artifact.files) + ): + raise ValueError( + f"Unable to fetch files for artifact: {self.name!r}" + ) + return FileWithUrlConnection.model_validate(artifact_files) + + return _impl + + def _fetch_file_urls( + self, cursor: str | None, per_page: int = 5000 + ) -> FileWithUrlConnection: + if self._fetch_file_urls_decorated is None: + self._fetch_file_urls_decorated = self._build_fetch_file_urls_wrapper() + return self._fetch_file_urls_decorated(cursor, per_page) + + @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, + start: str | None = None, + ) -> 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. + start: Pagination cursor for resuming a past query, captured + from a previous paginator's `.cursor` attribute. + + Returns: + An iterator containing `File` objects. + + Raises: + ArtifactNotLoggedError: If the artifact is not logged. + """ + if (client := self._client) is None: + raise RuntimeError("Client not initialized") + return ArtifactFiles(client, self, names, per_page, start=start) + + 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: StrPath | None) -> FilePathStr: + root = str(dir_path or self._default_root()) + self._download_roots.add(os.path.abspath(root)) + return root + + 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 collection. + + Args: + delete_aliases: If set to `True`, delete all aliases associated + with the artifact. If `False`, raise an exception if + the artifact has existing aliases. This parameter is ignored + if the artifact is retrieved from a collection it is linked to. + + 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: + from ._generated import DELETE_ARTIFACT_GQL, DeleteArtifactInput + + if self._client is None: + raise RuntimeError("Client not initialized for artifact mutations") + + gql_op = gql(DELETE_ARTIFACT_GQL) + gql_input = DeleteArtifactInput( + artifact_id=self.id, + delete_aliases=delete_aliases, + ) + self._client.execute(gql_op, variable_values={"input": gql_input.model_dump()}) + + @normalize_exceptions + def link(self, target_path: str, aliases: Iterable[str] | None = None) -> Artifact: + """Link this artifact to a collection. + + Args: + target_path: The path of the collection. Path consists of the prefix + "wandb-registry-" along with the registry name and the + collection name `wandb-registry-{REGISTRY_NAME}/{COLLECTION_NAME}`. + aliases: Add one or more aliases to the linked artifact. The + "latest" alias is automatically applied to the most recent artifact + you link. + + Raises: + ArtifactNotLoggedError: If the artifact is not logged. + + Returns: + The linked artifact. + """ + from wandb import Api + from wandb.sdk.internal.internal_api import Api as InternalApi + + from ._generated import LINK_ARTIFACT_GQL, LinkArtifact, LinkArtifactInput + from ._validators import ArtifactPath, FullArtifactPath, validate_aliases + + if self.is_link: + wandb.termwarn( + "Linking to a link artifact will result in directly linking to the source artifact of that link artifact." + ) + + # Save the artifact first if necessary + if self.is_draft(): + if not self._is_draft_save_started(): + # Avoiding public `.source_project` property here, + # as it requires the artifact is logged first. + self.save(project=self._source_project) + + # Wait until the artifact is committed before trying to link it. + self.wait() + + if (client := self._client) is None: + raise RuntimeError("Client not initialized for artifact mutations") + + # FIXME: Find a way to avoid using InternalApi here, due to the perf overhead + settings = InternalApi().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 None + target.prefix = resolve_org_entity_name(client, 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 = [ + {"artifactCollectionName": target.name, "alias": a} + for a in validate_aliases(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()} + + # Newer server versions can return `artifactMembership` directly in the response, + # avoiding the need to re-fetch the linked artifact at the end. + omit_variables = omit_fields = None + if not server_supports( + client, pb.ARTIFACT_MEMBERSHIP_IN_LINK_ARTIFACT_RESPONSE + ): + omit_variables = {"includeAliases"} + omit_fields = {"artifactMembership"} + + gql_op = gql_compat( + LINK_ARTIFACT_GQL, omit_variables=omit_variables, omit_fields=omit_fields + ) + data = client.execute(gql_op, variable_values=gql_vars) + result = LinkArtifact.model_validate(data).result + + # 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=client, + service_api=self._get_service_api(), + ) + + # 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 a linked member of an artifact collection. + + Raises: + ArtifactNotLoggedError: If the artifact is not logged. + ValueError: If the artifact is not linked to any 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: + from ._generated import UNLINK_ARTIFACT_GQL, UnlinkArtifactInput + + if self._client is None: + raise RuntimeError("Client not initialized for artifact mutations") + + mutation = gql(UNLINK_ARTIFACT_GQL) + gql_input = UnlinkArtifactInput( + artifact_id=self.id, + artifact_portfolio_id=self.collection.id, + ) + gql_vars = {"input": gql_input.model_dump()} + 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!r}" + ) 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. + """ + from ._generated import ARTIFACT_USED_BY_GQL, ArtifactUsedBy + + if (client := self._client) is None: + raise RuntimeError("Client not initialized for artifact queries") + + query = gql(ARTIFACT_USED_BY_GQL) + gql_vars = {"id": self.id} + data = 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) + service_api = self._get_service_api() + return [ + Run( + client, + proj.entity.name, + proj.name, + run.name, + service_api=service_api, + ) + 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. + """ + from ._generated import ARTIFACT_CREATED_BY_GQL, ArtifactCreatedBy + from ._generated.fragments import RunInfoFragment + + if (client := self._client) is None: + raise RuntimeError("Client not initialized for artifact queries") + + gql_op = gql(ARTIFACT_CREATED_BY_GQL) + gql_vars = {"id": self.id} + data = client.execute(gql_op, variable_values=gql_vars) + result = ArtifactCreatedBy.model_validate(data) + + # `created_by` is a union of Run and User; only a Run has a project to + # construct a `Run` from. + if ( + (artifact := result.artifact) + and isinstance(creator := artifact.created_by, RunInfoFragment) + and (name := creator.name) + and (project := creator.project) + ): + return Run( + client, + project.entity.name, + project.name, + name, + service_api=self._get_service_api(), + ) + 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.""" + from ._generated import ARTIFACT_TYPE_GQL, ArtifactType + + name = name if (":" in name) else f"{name}:latest" + + gql_op = gql(ARTIFACT_TYPE_GQL) + gql_vars = {"entity": entity_name, "project": project_name, "name": name} + data = client.execute(gql_op, variable_values=gql_vars) + result = ArtifactType.model_validate(data) + if (project := result.project) and (artifact := project.artifact): + return artifact.artifact_type.name + return None + + def _ttl_duration_seconds_to_gql(self) -> int | None: + # Set the artifact TTL to `ttl_duration_seconds` if the user provided a value. + # Otherwise, use `ttl_status` to indicate backend values INHERIT (-1) or + # DISABLED (-2) when the TTL is None. + # When `ttl_change is None`, nothing changed and this is a no-op. + 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.""" + from wandb._pydantic import gql_typename + + from ._generated import ( + FETCH_LINKED_ARTIFACTS_GQL, + ArtifactPortfolioTypeFields, + FetchLinkedArtifacts, + ) + from ._validators import LinkArtifactFields + + if self.id is None: + raise ValueError( + "Unable to find any artifact memberships for artifact without an ID" + ) + + if (client := self._client) is None: + raise ValueError("Client is not initialized") + + gql_op = gql_compat(FETCH_LINKED_ARTIFACTS_GQL) + data = client.execute(gql_op, variable_values={"artifactID": self.id}) + result = FetchLinkedArtifacts.model_validate(data) + + 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__ == gql_typename(ArtifactPortfolioTypeFields)) + ) + ) + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_download_logger.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_download_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..04d3ffc263625f6824075e8d0520bdee1722c36a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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 collections.abc 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_file_cache.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_file_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..04e722edb3e5956f72f9ee12ad7905df13ff93ca --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_file_cache.py @@ -0,0 +1,257 @@ +"""Artifact cache.""" + +from __future__ import annotations + +import contextlib +import errno +import hashlib +import os +import shutil +import subprocess +import sys +from collections.abc import Iterator +from contextlib import AbstractContextManager +from functools import lru_cache +from pathlib import Path +from tempfile import NamedTemporaryFile +from typing import IO, 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 = ...) -> AbstractContextManager[IO]: ... + + +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 cache 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: + # Skip the cache but still use an intermediate temporary file to + # ensure atomicity. Place the temp file in the same root as the + # destination file to avoid cross-filesystem move/copy operations. + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_instance_cache.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_instance_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..85f4a83d6bd7d4daa703b8cee7a0748712c04140 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_instance_cache.py @@ -0,0 +1,18 @@ +"""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) # Cached by artifact ID +artifact_instance_cache_by_client_id: dict[str, Artifact] = CappedDict(100) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifest.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..3a1a3013775aac5350d48c171a2139258cc42dda --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifest.py @@ -0,0 +1,78 @@ +"""Artifact manifest.""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING, Annotated, Any, Dict # noqa: UP035 + +from pydantic import Field + +from wandb.sdk.lib.hashutil import HexMD5 + +from ._models.base_model import ArtifactsBase + +if TYPE_CHECKING: + from .artifact_manifest_entry import ArtifactManifestEntry + from .storage_policy import StoragePolicy + + +class ArtifactManifest(ArtifactsBase, ABC): + # Note: we can't name this "version" since it conflicts with the prior + # `version()` classmethod. + manifest_version: Annotated[Any, Field(repr=False)] + entries: Dict[str, ArtifactManifestEntry] = Field(default_factory=dict) # noqa: UP006 + + storage_policy: Annotated[StoragePolicy, Field(exclude=True, repr=False)] + + @classmethod + def version(cls) -> int: + return cls.model_fields["manifest_version"].default + + @classmethod + @abstractmethod + def from_manifest_json(cls, manifest_json: dict[str, Any]) -> ArtifactManifest: + if (version := manifest_json.get("version")) is None: + raise ValueError("Invalid manifest format. Must contain version field.") + + for sub in cls.__subclasses__(): + if sub.version() == version: + return sub.from_manifest_json(manifest_json) + raise ValueError("Invalid manifest version.") + + def __len__(self) -> int: + return len(self.entries) + + @abstractmethod + def to_manifest_json(self) -> dict[str, Any]: + raise NotImplementedError + + @abstractmethod + def digest(self) -> HexMD5: + raise NotImplementedError + + @abstractmethod + def size(self) -> int: + raise NotImplementedError + + def add_entry(self, entry: ArtifactManifestEntry, overwrite: bool = False) -> None: + if ( + (not overwrite) + and (old_entry := self.entries.get(entry.path)) + and (entry.digest != old_entry.digest) + ): + raise ValueError(f"Cannot add the same path twice: {entry.path!r}") + self.entries[entry.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!r}") + + 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]: + # entry keys (paths) use forward slash even for windows + dir_prefix = f"{directory}/" + return [obj for key, obj in self.entries.items() if key.startswith(dir_prefix)] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifest_entry.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifest_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..4aff8b9f1cbc457e1ced6eca43548caf47f0b787 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifest_entry.py @@ -0,0 +1,264 @@ +"""Artifact manifest entry.""" + +# Keep older-style type annotations in this legacy model. +# ruff: noqa: UP006, UP007, UP035, UP045 + +from __future__ import annotations + +import concurrent.futures +import hashlib +import logging +import os +from contextlib import suppress +from os.path import getsize +from typing import TYPE_CHECKING, Annotated, Any, Dict, Final, Optional, Union +from urllib.parse import urlparse + +from pydantic import Field, NonNegativeInt +from typing_extensions import Self + +from wandb._pydantic import field_validator, model_validator +from wandb._strutils import nameof +from wandb.proto.wandb_telemetry_pb2 import Deprecated +from wandb.sdk.lib.deprecation import warn_and_record_deprecation +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, URIStr + +from ._models.base_model import ArtifactsBase + +if TYPE_CHECKING: + from .artifact import Artifact + + +logger = logging.getLogger(__name__) + + +_WB_ARTIFACT_SCHEME: Final[str] = "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(ArtifactsBase): + """A single entry in an artifact manifest. + + External code should avoid instantiating this class directly. + """ + + path: LogicalPath + + digest: Union[B64MD5, ETag, URIStr, FilePathStr] + ref: Union[URIStr, FilePathStr, None] = None + birth_artifact_id: Annotated[Optional[str], Field(alias="birthArtifactID")] = None + size: Optional[NonNegativeInt] = None + extra: Dict[str, Any] = Field(default_factory=dict) + local_path: Optional[str] = None + + skip_cache: bool = False + + # Note: Pydantic treats these as private attributes, omitting them from + # validation and comparison logic. + _parent_artifact: Optional[Artifact] = None + _download_url: Optional[str] = None + + @field_validator("path", mode="before") + def _validate_path(cls, v: Any) -> LogicalPath: + """Coerce `path` to a LogicalPath. + + LogicalPath does not implement its own pydantic validator, so coerce + to LogicalPath in this field validator. + """ + return LogicalPath(v) + + @field_validator("local_path", mode="before") + def _validate_local_path(cls, v: Any) -> str | None: + """Coerce `local_path` to a str. Necessary if the input is a `PosixPath`.""" + return str(v) if v else None + + @model_validator(mode="after") + def _infer_size_from_local_path(self) -> Self: + """If `size` isn't set, try to infer it from `local_path`.""" + if (self.size is None) and self.local_path: + self.size = getsize(self.local_path) + return self + + def __repr__(self) -> str: + # For compatibility with prior behavior, don't display `extra` if it's empty + exclude = None if self.extra else {"extra"} + repr_dict = self.model_dump(by_alias=False, exclude_none=True, exclude=exclude) + return f"{nameof(type(self))}({', '.join(f'{k}={v!r}' for k, v in repr_dict.items())})" + + @property + def name(self) -> LogicalPath: + """Deprecated; use `path` instead.""" + warn_and_record_deprecation( + feature=Deprecated(artifactmanifestentry__name=True), + 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() + rootdir = artifact._add_download_root(root) + dest_path = os.path.join(rootdir, self.path) + + # 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) + + # Override the target cache path IF we're skipping the cache. + # Note that `override_cache_path is None` <=> `skip_cache is False`. + override_cache_path = FilePathStr(dest_path) if skip_cache else None + storage_policy = artifact.manifest.storage_policy + if self.ref is not None: + cache_path = storage_policy.load_reference( + self, local=True, dest_path=override_cache_path + ) + else: + cache_path = storage_policy.load_file( + artifact, self, dest_path=override_cache_path, executor=executor + ) + + # Determine the final path + final_path = FilePathStr( + override_cache_path or copy_or_overwrite_changed(cache_path, dest_path) + ) + + # Cache the checksum for future downloads + _write_cached_checksum(final_path, self.digest) + + return 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 (parent_artifact := self._parent_artifact) is None: + return self.ref + return parent_artifact.manifest.storage_policy.load_reference(self, 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(parent_id)}/{self.path}" + + def to_json(self) -> dict[str, Any]: + # NOTE: The method name `to_json` is a bit misleading, as this returns a + # python dict, NOT a JSON string. The historical name is kept for continuity, + # but consider deprecating this in favor of `BaseModel.model_dump()`. + return self.model_dump(exclude_none=True) # type: ignore[return-value] + + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifests/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifests/artifact_manifest_v1.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifests/artifact_manifest_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..18226f7674fcd11734277c1605ddaeed2ac7e5aa --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_manifests/artifact_manifest_v1.py @@ -0,0 +1,72 @@ +"""Artifact manifest v1.""" + +# Keep older-style type annotations in this legacy model. +# ruff: noqa: UP006, UP035 + +from __future__ import annotations + +from operator import itemgetter +from typing import Annotated, Any, ClassVar, Dict, Literal, final + +from pydantic import Field + +from wandb.sdk.lib.hashutil import HexMD5, _md5 + +from .._factories import make_storage_policy +from .._models.manifest import ArtifactManifestV1Data +from ..artifact_manifest import ArtifactManifest +from ..artifact_manifest_entry import ArtifactManifestEntry +from ..storage_policy import StoragePolicy + + +@final +class ArtifactManifestV1(ArtifactManifest): + manifest_version: Annotated[Literal[1], Field(repr=False)] = 1 + entries: Dict[str, ArtifactManifestEntry] = Field(default_factory=dict) + + storage_policy: StoragePolicy = Field( + default_factory=make_storage_policy, exclude=True, repr=False + ) + + @classmethod + def from_manifest_json(cls, manifest_json: dict[str, Any]) -> ArtifactManifestV1: + data = ArtifactManifestV1Data(**manifest_json) + + policy_name = data.storage_policy + policy_cfg = data.storage_policy_config + policy = StoragePolicy.lookup_by_name(policy_name).from_config(policy_cfg) + return cls( + manifest_version=data.version, entries=data.contents, storage_policy=policy + ) + + 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. + """ + omit_entry_fields = {"path", "local_path", "skip_cache"} + return { + "version": self.manifest_version, + "storagePolicy": self.storage_policy.name(), + "storagePolicyConfig": self.storage_policy.config(), + "contents": { + path: entry.model_dump(exclude=omit_entry_fields, exclude_defaults=True) + for path, entry in self.entries.items() + }, + } + + _DIGEST_HEADER: ClassVar[bytes] = b"wandb-artifact-manifest-v1\n" + """Encoded prefix/header for the ArtifactManifest digest.""" + + def digest(self) -> HexMD5: + hasher = _md5(self._DIGEST_HEADER) + # sort by key (path) + for path, entry in sorted(self.entries.items(), key=itemgetter(0)): + hasher.update(f"{path}:{entry.digest}\n".encode()) + return hasher.hexdigest() + + def size(self) -> int: + return sum(entry.size for entry in self.entries.values() if entry.size) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_saver.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_saver.py new file mode 100644 index 0000000000000000000000000000000000000000..d00940dccd72810254ecc0afbc9cec0b36de5e64 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_saver.py @@ -0,0 +1,275 @@ +"""Artifact saver.""" + +from __future__ import annotations + +import concurrent.futures +import json +import os +import tempfile +from collections.abc import Awaitable, Sequence +from typing import TYPE_CHECKING + +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) + self._manifest.storage_policy._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() + + # Queue the commit. It will only happen after all file uploads finish. + 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 and 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_state.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_state.py new file mode 100644 index 0000000000000000000000000000000000000000..4df836c8b60e482e3de8a103b4b0e646800922a7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_ttl.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_ttl.py new file mode 100644 index 0000000000000000000000000000000000000000..e63c69031923aa36a2214526443861497f3575d6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/exceptions.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..464d6a7b026171f534d3aa992b859f57434dccaa --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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 AttributeError (Python 3.10+) by exposing `name` and `obj`. + # See: https://docs.python.org/3/library/exceptions.html#AttributeError + try: + super().__init__(msg, name=name, obj=obj) + except TypeError: + # The `name`/`obj` keywords 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/staging.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/staging.py new file mode 100644 index 0000000000000000000000000000000000000000..24a6313ca0507d1f4ee110570c80062644c08cb9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/storage_handler.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/storage_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..c1883e5144cf8bf602b11a7012c0a85cb1025979 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/http_handler.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/http_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..ea6f07d8c4086001c81511b672db12a89cc2be31 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/storage_handlers/http_handler.py @@ -0,0 +1,120 @@ +"""HTTP storage handler.""" + +from __future__ import annotations + +import os +from dataclasses import asdict +from typing import TYPE_CHECKING, Any, Dict, Optional, cast # noqa: UP035 +from urllib.parse import ParseResult + +from pydantic.dataclasses import dataclass as pydantic_dataclass +from typing_extensions import Self + +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.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 + + +@pydantic_dataclass(frozen=True) +class _HttpEntryInfo: + """Partial ArtifactManifestEntry fields parsed from an HTTP response.""" + + ref: str # The reference URL for the manifest entry, i.e. original URL of the request + extra: Dict[str, Any] # noqa: UP006 + digest: Optional[str] # noqa: UP045 + size: Optional[int] # noqa: UP045 + + @classmethod + def from_response(cls, rsp: requests.Response) -> Self: + # NOTE(tonyyli): For continuity with prior behavior, note that: + # - `extra["etag"]` includes leading/trailing quotes, if any, from the ETag + # - `digest` strips leading/trailing quotes, if any, from the ETag + # + # - `digest` apparently falls back to the original reference URL (request URL) + # if no ETag is present. This is weird: wouldn't we hash the response body + # instead of using the URL? For now, at the time of writing/refactoring this, + # we'll maintain the prior behavior to minimize risk of breakage. + headers: CaseInsensitiveDict = rsp.headers + etag = headers.get("etag") + ref_url = rsp.request.url + return cls( + ref=cast(str, ref_url), + extra={"etag": etag} if etag else {}, + digest=etag.strip('"') if etag else ref_url, + size=headers.get("content-length"), + ) + + +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 _get_stream(self, url: str) -> requests.Response: + """Returns a streaming response from a GET request to the given URL.""" + return self._session.get( + url, + stream=True, + ) + + def load_path( + self, + manifest_entry: ArtifactManifestEntry, + local: bool = False, + ) -> URIStr | FilePathStr: + if (ref_url := manifest_entry.ref) is None: + raise ValueError("Missing URL on artifact manifest entry") + if not local: + return ref_url + + expected_digest = manifest_entry.digest + + path, hit, cache_open = self._cache.check_etag_obj_path( + url=ref_url, etag=expected_digest, size=manifest_entry.size or 0 + ) + if hit: + return path + + with self._get_stream(ref_url) as rsp: + entry_info = _HttpEntryInfo.from_response(rsp) + if (digest := entry_info.digest) != expected_digest: + raise ValueError( + f"Digest mismatch for url {ref_url!r}: expected {expected_digest!r} but found {digest!r}" + ) + + with cache_open(mode="wb") as file: + for data in rsp.iter_content(chunk_size=128 * 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._get_stream(path) as rsp: + entry_info = _HttpEntryInfo.from_response(rsp) + return [ArtifactManifestEntry(path=name, **asdict(entry_info))] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/storage_layout.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/storage_layout.py new file mode 100644 index 0000000000000000000000000000000000000000..368b0cc1126e55e3fe48688d3dcdc1b826a8df20 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/storage_layout.py @@ -0,0 +1,16 @@ +"""Storage layout.""" + +from __future__ import annotations + +from enum import Enum + + +class StorageLayout(str, Enum): + V1 = "V1" + V2 = "V2" + + @classmethod + def from_env(cls) -> StorageLayout: + from wandb.env import get_use_v1_artifacts + + return cls.V1 if get_use_v1_artifacts() else cls.V2 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/storage_policy.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/storage_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..0bb2a230c5e57d804f61fb0c1ab104eb3d924b87 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/artifacts/storage_policy.py @@ -0,0 +1,89 @@ +"""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._models.storage import StoragePolicyConfig + 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): + _api: InternalApi | None = None + + 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: StoragePolicyConfig) -> 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/_dtypes.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/_dtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..b4d05c6be3b911e5d2ec210a3d2bc1f1e46a1c18 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/_dtypes.py @@ -0,0 +1,903 @@ +from __future__ import annotations + +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", 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: 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.Any | None) -> 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: dict[str, t.Any], artifact: Artifact | None = 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: Artifact | None = 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: Artifact | None = 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[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[list[type]] = [] + + # Contains the further specification of the Type + _params: 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.Any | None = 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: Artifact | None = None) -> 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: dict[str, t.Any], + artifact: Artifact | None = 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.Any | None = 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[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[list[type]] = [] + + def assign_type(self, wb_type: Type) -> AnyType | InvalidType: + return ( + self + if not (isinstance(wb_type, (NoneType, 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[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[list[type]] = [None.__class__] + + +class StringType(Type): + name = "string" + types: t.ClassVar[list[type]] = [str] + + +class NumberType(Type): + name = "number" + types: t.ClassVar[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[list[type]] = [datetime.datetime, datetime.date] + + +if np: + TimestampType.types.append(np.datetime64) + + +class BooleanType(Type): + name = "boolean" + types: t.ClassVar[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[list[type]] = [] + + def __init__(self, class_name: str): + self.params.update({"class_name": class_name}) + + @classmethod + def from_obj(cls, py_obj: t.Any | None = None) -> PythonObjectType: + return cls(py_obj.__class__.__name__) + + +class ConstType(Type): + """A constant value (currently only primitives supported).""" + + name = "const" + types: t.ClassVar[list[type]] = [] + + def __init__(self, val: t.Any | None = None, is_set: bool | None = 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, list)) + val = set(val) + + self.params.update({"val": val, "is_set": is_set}) + + def assign(self, py_obj: t.Any | None = None) -> Type: + return self.assign_type(ConstType(py_obj)) + + @classmethod + def from_obj(cls, py_obj: t.Any | None = None) -> ConstType: + return cls(py_obj) + + def __repr__(self): + return str(self.params["val"]) + + +def _flatten_union_types(wb_types: list[Type]) -> 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: list[Type], + obj_or_type: Type | t.Any | None, + type_mode=False, +) -> 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[list[type]] = [] + + def __init__( + self, + allowed_types: t.Sequence[ConvertibleToType] | None = 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.Any | None = None) -> 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) -> 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[list[type]] = [list, tuple, set, frozenset] + + def __init__( + self, + element_type: ConvertibleToType | None = None, + length: int | None = 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.Any | None = 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) -> 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.Any | None = None) -> 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, tuple, set, 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[list[type]] = [] # will manually add type if np is available + _serialization_path: dict[str, str] | None + + def __init__( + self, + shape: t.Sequence[int], + serialization_path: dict[str, str] | None = None, + ): + self.params.update({"shape": list(shape)}) + self._serialization_path = serialization_path + + @classmethod + def from_obj(cls, py_obj: t.Any | None = 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) -> 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.Any | None = None) -> 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: Artifact | None = None) -> 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) -> dict[str, str] | None: + 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[list[type]] = [dict] + + def __init__( + self, + type_map: dict[str, ConvertibleToType] | None = 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.Any | None = 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) -> 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.Any | None = None) -> 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/_private.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/_private.py new file mode 100644 index 0000000000000000000000000000000000000000..887bc8a231014d06dbe65590663064ec792eeb84 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/audio.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/audio.py new file mode 100644 index 0000000000000000000000000000000000000000..4f556266620b6927c0bf313dd356e37e21f9b914 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/audio.py @@ -0,0 +1,205 @@ +from __future__ import annotations + +import hashlib +import os +import pathlib +from typing import TYPE_CHECKING + +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: str | pathlib.Path | list | np.ndarray, + sample_rate: int | None = None, + caption: str | None = 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: bool | None = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/bokeh.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/bokeh.py new file mode 100644 index 0000000000000000000000000000000000000000..c8a086102ce7c39a3ba87c1ffd20245b668973a6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/bokeh.py @@ -0,0 +1,99 @@ +from __future__ import annotations + +import codecs +import json +import os +import pathlib +from typing import TYPE_CHECKING + +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 + + +def _doc_to_json(doc): + # Bokeh 3.9 returns Serialized[DocJson] from to_json() by default. + # Ask for plain JSON when supported; older Bokeh versions already + # return plain JSON and do not accept the 'deferred' kwarg. + try: + return doc.to_json(deferred=False) + except TypeError: + return doc.to_json() + + +class Bokeh(Media): + """Wandb class for Bokeh plots. + + Args: + val: Bokeh plot + """ + + _log_type = "bokeh-file" + + def __init__( + self, + data_or_path: 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(_doc_to_json(_data)) + b_json = _doc_to_json(self.b_obj) + roots = b_json.get("roots") + if isinstance(roots, dict) and "references" in roots: + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/graph.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/graph.py new file mode 100644 index 0000000000000000000000000000000000000000..bc59f31f51b48406cc4dd80ad8f2f5c71f438fbb --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/histogram.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/histogram.py new file mode 100644 index 0000000000000000000000000000000000000000..95c6c1e91d29adbe168b33741c176eae9cb0d5e8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/histogram.py @@ -0,0 +1,110 @@ +from __future__ import annotations + +import sys +from collections.abc import Sequence +from typing import TYPE_CHECKING + +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: Sequence | None = None, + np_histogram: NumpyHistogram | None = 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: LocalRun | Artifact | None = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/html.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/html.py new file mode 100644 index 0000000000000000000000000000000000000000..75db1b7cee29e24808581e20474ae314ff1b3f99 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/html.py @@ -0,0 +1,166 @@ +from __future__ import annotations + +import os +import pathlib +from collections.abc import Sequence +from typing import TYPE_CHECKING + +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: 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: 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: 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/image.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/image.py new file mode 100644 index 0000000000000000000000000000000000000000..9de5765e025bfddb9bbd11a4f56fd80b66d3c998 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/image.py @@ -0,0 +1,984 @@ +from __future__ import annotations + +import hashlib +import logging +import os +import pathlib +from collections.abc import Sequence +from io import BytesIO +from typing import TYPE_CHECKING, Any, TypeAlias, 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 + + TorchTensorType: TypeAlias = torch.Tensor | torch.Variable + ImageDataType: TypeAlias = ( + matplotlib.artist.Artist | PILImage | TorchTensorType | np.ndarray + ) + ImageDataOrPathType: TypeAlias = "str | pathlib.Path | Image | ImageDataType" + + +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: str | None + _grouping: int | None + _caption: str | None + _width: int | None + _height: int | None + _image: PILImage | None + _classes: Classes | None + _boxes: dict[str, BoundingBoxes2D] | None + _masks: dict[str, ImageMask] | None + _file_type: str | None + + def __init__( + self, + data_or_path: ImageDataOrPathType, + mode: str | None = None, + caption: str | None = None, + grouping: int | None = None, + classes: Classes | Sequence[dict] | None = None, + boxes: dict[str, BoundingBoxes2D] | dict[str, dict] | None = None, + masks: dict[str, ImageMask] | dict[str, dict] | None = None, + file_type: str | None = 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 Pillow docs for more information 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/models/ref/python/data-types/boundingboxes2d + masks: A dictionary containing mask information for the image. + see https://docs.wandb.ai/models/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: int | None = None, + caption: str | None = None, + classes: Classes | Sequence[dict] | None = None, + boxes: dict[str, BoundingBoxes2D] | dict[str, dict] | None = None, + masks: dict[str, ImageMask] | dict[str, dict] | None = None, + file_type: str | None = 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] + ) + 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: str | None = None, + file_type: str | None = 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).convert(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).convert(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: Classes | None = 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: dict[str, ImageMask] | None = 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: dict[str, BoundingBoxes2D] | None = 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: int | str, + step: int | str, + id_: int | str | None = None, + ignore_copy_err: bool | None = 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" + ) + + # Validate the key before checking server capabilities so invalid + # Windows filenames fail fast instead of blocking on a version lookup. + util.make_file_path_upload_safe(str(key)) + + 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: 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: np.ndarray | torch.Tensor, + file_type: str | None = 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: 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: int | str, + ) -> list[dict | None] | bool: + """Collect all masks from a list of images. + + " + """ + all_mask_groups: list[dict | None] = [] + 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: int | str, + ) -> list[dict | None] | bool: + """Collect all boxes from a list of images. + + " + """ + all_box_groups: list[dict | None] = [] + 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] + ) -> bool | Sequence[str | None]: + """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) -> PILImage | None: + if ( + self._image is None + and 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 + } + box_score_keys = { + key + for val in py_obj._boxes.values() + for box in val._val + for key in box.get("scores", {}) + } + + 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 + } + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/molecule.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/molecule.py new file mode 100644 index 0000000000000000000000000000000000000000..bc199cf6b4be3a3735bed3b97766be05b718aab6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/molecule.py @@ -0,0 +1,253 @@ +from __future__ import annotations + +import io +import os +import pathlib +from collections.abc import Sequence +from typing import TYPE_CHECKING, TypeAlias + +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: TypeAlias = 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: str | pathlib.Path | TextIO, + caption: str | None = 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: str | None = 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: str | None = 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: 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: 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/object_3d.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/object_3d.py new file mode 100644 index 0000000000000000000000000000000000000000..a5b71d778cc62fe62f22f8a073751d6d7e099e7d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/object_3d.py @@ -0,0 +1,539 @@ +from __future__ import annotations + +import codecs +import itertools +import os +import pathlib +from collections.abc import Sequence +from typing import TYPE_CHECKING, ClassVar, Literal, TextIO, TypeAlias, TypedDict + +import wandb +from wandb import util +from wandb.sdk.lib import json_util, 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: TypeAlias = 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: TypeAlias = 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: str | None + color: RGBColor + score: numeric | None + + 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: str | None = None, + score: numeric | None = 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: np.ndarray | str | pathlib.Path | TextIO | dict, + caption: str | None = None, + **kwargs: str | FileFormat3D | None, + ) -> 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_util.dump(data, fp) + 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_util.dump(list_data, fp) + 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: TextIO | str, + file_type: FileFormat3D | None = 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: Sequence[Vector3D] | None = 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: 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) and ( + 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: 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/plotly.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/plotly.py new file mode 100644 index 0000000000000000000000000000000000000000..3b1d5a24e6f26aef6c49063b3e2e7bb2f308c0a9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/plotly.py @@ -0,0 +1,98 @@ +from __future__ import annotations + +import codecs +import os +from collections.abc import Sequence +from typing import TYPE_CHECKING, TypeAlias + +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: TypeAlias = ( + 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: plotly.Figure | matplotlib.artist.Artist + ) -> 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: 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: 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/saved_model.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/saved_model.py new file mode 100644 index 0000000000000000000000000000000000000000..3f95f99c4d93b83bb37010d969bcbd0b932a87c1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/saved_model.py @@ -0,0 +1,439 @@ +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() + try: + return cast( + bool, + ( + dynamic_sklearn.base.is_classifier(obj) + or dynamic_sklearn.base.is_outlier_detector(obj) + or dynamic_sklearn.base.is_regressor(obj) + ), + ) + except AttributeError: + # sklearn >= 1.6 raises AttributeError from `is_classifier()` for non-sklearn objects + return False + + @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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/table.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/table.py new file mode 100644 index 0000000000000000000000000000000000000000..a98d8ab071521dfa404945cf40b2321ab17c9a67 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/table.py @@ -0,0 +1,1462 @@ +from __future__ import annotations + +import base64 +import binascii +import codecs +import datetime +import json +import logging +import os +from typing import TYPE_CHECKING, Any, Literal + +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, _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/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: Literal["IMMUTABLE", "MUTABLE", "INCREMENTAL"] | None = "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, strict=False): + 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, _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, 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, 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, _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") + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/table_decorators.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/table_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..9aabbbc565df165f5f49a377a4811298f31badf8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/table_decorators.py @@ -0,0 +1,109 @@ +"""Decorators for W&B Table operations.""" + +from __future__ import annotations + +from collections.abc import Callable +from functools import wraps +from typing import Any, Concatenate, TypeVar + +from typing_extensions import 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/trace_tree.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/trace_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..f62bcbf2ecb0d1ff37e988a38d91b7f5ad54fee4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/trace_tree.py @@ -0,0 +1,441 @@ +"""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. +""" + +from __future__ import annotations + +import dataclasses +import hashlib +import json +from dataclasses import dataclass, field +from enum import Enum +from typing import TYPE_CHECKING, Any + +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: dict[str, Any] | None = field(default=None) + outputs: dict[str, Any] | None = field(default=None) + + +@dataclass() +class Span: + span_id: str | None = field(default=None) + name: str | None = field(default=None) + start_time_ms: int | None = field(default=None) + end_time_ms: int | None = field(default=None) + status_code: StatusCode | None = field(default=None) + status_message: str | None = field(default=None) + attributes: dict[str, Any] | None = field(default=None) + results: list[Result] | None = field(default=None) + child_spans: list[Span] | None = field(default=None) + span_kind: SpanKind | None = 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: dict | None = 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: LocalRun | Artifact | None) -> 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: str | None = None, + status_code: str | None = None, + status_message: str | None = None, + metadata: dict | None = None, + start_time_ms: int | None = None, + end_time_ms: int | None = None, + inputs: dict | None = None, + outputs: dict | None = None, + model_dict: dict | None = 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: str | None = None, + status_code: str | None = None, + status_message: str | None = None, + metadata: dict | None = None, + start_time_ms: int | None = None, + end_time_ms: int | None = None, + inputs: dict | None = None, + outputs: dict | None = 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) -> dict[str, str] | None: + """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) -> dict[str, str] | None: + """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) -> dict[str, str] | None: + """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) -> str | None: + """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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8b3e3be52891566f424c27452dc398f0d7d15236 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/utils.py @@ -0,0 +1,263 @@ +from __future__ import annotations + +import datetime +import logging +import os +from collections.abc import Sequence +from decimal import Decimal +from typing import TYPE_CHECKING, TypeAlias, 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: TypeAlias = ( + dict + | WBValue + | Sequence[WBValue] + | plotly.Figure + | matplotlib.artist.Artist + | pd.DataFrame + | object + ) + + +def history_dict_to_json( + run: LocalRun | None, + payload: dict, + step: int | None = None, + ignore_copy_err: bool | None = 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: LocalRun | None, + key: str, + val: ValToJsonType, + namespace: str | int | None = None, + ignore_copy_err: bool | None = None, +) -> 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/video.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/video.py new file mode 100644 index 0000000000000000000000000000000000000000..ac3e6c10afa3934e7e92041a0e9f4fd55a4f92d4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/data_types/video.py @@ -0,0 +1,304 @@ +from __future__ import annotations + +import functools +import logging +import os +import pathlib +from collections.abc import Sequence +from io import BytesIO +from typing import TYPE_CHECKING, Any, Literal + +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: int | None = 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: int | None + _height: int | None + + def __init__( + self, + data_or_path: str | pathlib.Path | np.ndarray | TextIO | BytesIO, + caption: str | None = None, + fps: int | None = None, + format: Literal["gif", "mp4", "webm", "ogg"] | None = 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: 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: 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/integration_utils/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/integration_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/integration_utils/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/integration_utils/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..291b576100be6644b0710ca15bee5c41ff05ad2b Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/integration_utils/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/integration_utils/__pycache__/auto_logging.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/integration_utils/__pycache__/auto_logging.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2929befeef922b75b9a337492a0cae84d9e6d1c3 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/integration_utils/__pycache__/auto_logging.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/integration_utils/__pycache__/data_logging.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/integration_utils/__pycache__/data_logging.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd58019165d4a5b9232bf69a97f457259ba34e91 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/integration_utils/__pycache__/data_logging.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/integration_utils/auto_logging.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/integration_utils/auto_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..2ae3f4ef7f3aa70e818a92b5e4ffe67e4649e633 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/integration_utils/auto_logging.py @@ -0,0 +1,233 @@ +from __future__ import annotations + +import asyncio +import functools +import inspect +import logging +from collections.abc import Sequence +from typing import Any, Protocol, 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 = dict[str, Any] | None + + +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: V | None = None) -> V | None: ... # pragma: no cover + + +class ArgumentResponseResolver(Protocol): + def __call__( + self, + args: Sequence[Any], + kwargs: dict[str, Any], + response: Response, + start_time: float, + time_elapsed: float, + ) -> dict[str, Any] | None: ... # 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: str | None = 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: wandb.Run | None = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/integration_utils/data_logging.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/integration_utils/data_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..ddd3c6134d8cdb11deba4386eeeb36a1cb766fb7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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. +from __future__ import annotations + +import sys +from collections.abc import Callable, Sequence +from typing import TYPE_CHECKING, Any + +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: Sequence | dict[str, Sequence] + validation_targets: Sequence | dict[str, Sequence] | None + validation_indexes: list[_TableIndex] + prediction_row_processor: Callable | None + class_labels_table: wandb.Table | None + infer_missing_processors: bool + + def __init__( + self, + inputs: Sequence | dict[str, Sequence], + targets: Sequence | dict[str, Sequence] | None = None, + indexes: list[_TableIndex] | None = None, + validation_row_processor: Callable | None = None, + prediction_row_processor: Callable | None = None, + input_col_name: str = "input", + target_col_name: str = "target", + table_name: str = "wb_validation_data", + artifact_type: str = "validation_dataset", + class_labels: list[str] | None = 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: wandb.Table | None + 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) -> 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: 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) -> dict | Sequence | Any | None: + """Used to make an example input, target, or output.""" + example: dict | Sequence | Any | None + + 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: 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: Sequence | Any, + class_labels_table: wandb.Table | None = None, + possible_base_example: Sequence | Any | None = 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: dict | Sequence, + example_target: dict | Sequence | Any, + class_labels_table: wandb.Table | None = 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: dict | Sequence, + example_input: dict | Sequence, + class_labels_table: wandb.Table | None = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/interface/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/interface/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/interface/constants.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/interface/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..09fe1e26f0ce72e23df8b627ff15e332f6ebc4e6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/interface/interface.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/interface/interface.py new file mode 100644 index 0000000000000000000000000000000000000000..023d1ff6e73118fbb3b23b1a135bc7ff5ef96f34 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/interface/interface.py @@ -0,0 +1,1066 @@ +from __future__ import annotations + +import abc +import gzip +import logging +import time +from collections.abc import Iterable +from pathlib import Path +from secrets import token_hex +from typing import TYPE_CHECKING, Any + +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.lib import json_util as json +from wandb.sdk.lib.filesystem import FilesDict, PolicyName +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 + +if TYPE_CHECKING: + from wandb.sdk.artifacts.artifact import Artifact + from wandb.sdk.artifacts.artifact_manifest import ArtifactManifest + + from ..wandb_run import Run + + +logger = logging.getLogger("wandb") + + +def file_policy_to_enum(policy: PolicyName) -> pb.FilesItem.PolicyType: + 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) -> 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(abc.ABC): + """Methods for sending run messages (Records) to the service. + + None of the methods may be called from an asyncio context other than + deliver_async() or those with a `nowait=True` argument. + """ + + _drop: bool + + def __init__(self) -> None: + self._drop = False + + @abc.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. + """ + + def publish_header(self) -> None: + header = pb.HeaderRecord() + self._publish_header(header) + + @abc.abstractmethod + def _publish_header(self, header: pb.HeaderRecord) -> None: + raise NotImplementedError + + def deliver_status(self) -> MailboxHandle[pb.Result]: + return self._deliver_status(pb.StatusRequest()) + + @abc.abstractmethod + def _deliver_status( + self, + status: pb.StatusRequest, + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + def _make_config( + self, + data: dict | None = None, + key: tuple[str, ...] | str | None = None, + val: Any | None = None, + obj: pb.ConfigRecord | None = 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) + + @abc.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) + + @abc.abstractmethod + def _publish_cancel(self, cancel: pb.CancelRequest) -> None: + raise NotImplementedError + + def publish_config( + self, + data: dict | None = None, + key: tuple[str, ...] | str | None = None, + val: Any | None = None, + ) -> None: + cfg = self._make_config(data=data, key=key, val=val) + + self._publish_config(cfg) + + @abc.abstractmethod + def _publish_config(self, cfg: pb.ConfigRecord) -> None: + raise NotImplementedError + + @abc.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) + + @abc.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) + + @abc.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) + + @abc.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: pb.ArtifactManifest | None = 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: + from wandb.sdk.artifacts.staging import get_staging_dir + + 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: str | None = None, + project: str | None = None, + organization: str | None = 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) + + @abc.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) + + @abc.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: Iterable[str] | None = None, + history_step: int | None = None, + is_user_created: bool = False, + use_after_commit: bool = False, + finalize: bool = True, + ) -> MailboxHandle[pb.Result]: + from wandb.sdk.artifacts.staging import get_staging_dir + + 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 + + @abc.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: str | None, + ) -> 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 + + @abc.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: Iterable[str] | None = 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) + + @abc.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) + + @abc.abstractmethod + def _publish_tbdata(self, tbrecord: pb.TBRecord) -> None: + raise NotImplementedError + + @abc.abstractmethod + def _publish_telemetry(self, telem: tpb.TelemetryRecord) -> None: + raise NotImplementedError + + def publish_environment(self, environment: pb.EnvironmentRecord) -> None: + self._publish_environment(environment) + + @abc.abstractmethod + def _publish_environment(self, environment: pb.EnvironmentRecord) -> None: + raise NotImplementedError + + def publish_partial_history( + self, + run: Run, + data: dict, + user_step: int, + step: int | None = None, + flush: bool | None = 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) + + @abc.abstractmethod + def _publish_partial_history(self, history: pb.PartialHistoryRequest) -> None: + raise NotImplementedError + + def publish_history( + self, + run: Run, + data: dict, + step: int | None = 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) + + @abc.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) + + @abc.abstractmethod + def _publish_preempting(self, preempt_rec: pb.RunPreemptingRecord) -> None: + raise NotImplementedError + + def publish_output( + self, + name: str, + data: str, + *, + nowait: bool = False, + ) -> 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, nowait=nowait) + + @abc.abstractmethod + def _publish_output(self, outdata: pb.OutputRecord, *, nowait: bool) -> None: + raise NotImplementedError + + def publish_output_raw( + self, + name: str, + data: str, + *, + nowait: bool = False, + ) -> 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, nowait=nowait) + + @abc.abstractmethod + def _publish_output_raw( + self, + outdata: pb.OutputRawRecord, + *, + nowait: bool, + ) -> None: + raise NotImplementedError + + def publish_output_logger( + self, + line: str, + *, + nowait: bool = False, + ) -> None: + o = pb.OutputLoggerRecord(line=line) + self._publish_output_logger(o, nowait=nowait) + + @abc.abstractmethod + def _publish_output_logger( + self, + outdata: pb.OutputLoggerRecord, + *, + nowait: bool, + ) -> None: + raise NotImplementedError + + def publish_pause(self) -> None: + pause = pb.PauseRequest() + self._publish_pause(pause) + + @abc.abstractmethod + def _publish_pause(self, pause: pb.PauseRequest) -> None: + raise NotImplementedError + + def publish_resume(self) -> None: + resume = pb.ResumeRequest() + self._publish_resume(resume) + + @abc.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) + + @abc.abstractmethod + def _publish_alert(self, alert: pb.AlertRecord) -> None: + raise NotImplementedError + + def _make_exit(self, exit_code: int | None) -> pb.RunExitRecord: + exit = pb.RunExitRecord() + if exit_code is not None: + exit.exit_code = exit_code + return exit + + def publish_keepalive(self) -> None: + keepalive = pb.KeepaliveRequest() + self._publish_keepalive(keepalive) + + @abc.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: dict | None, + 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) + + @abc.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) + + @abc.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") + + @abc.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) + + @abc.abstractmethod + def _deliver_finish_sync( + self, sync: pb.SyncFinishRequest + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + @abc.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) + + @abc.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) + + @abc.abstractmethod + def _deliver_attach( + self, + status: pb.AttachRequest, + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + def deliver_network_status(self) -> MailboxHandle[pb.Result]: + status = pb.NetworkStatusRequest() + return self._deliver_network_status(status) + + @abc.abstractmethod + def _deliver_network_status( + self, + status: pb.NetworkStatusRequest, + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + def deliver_get_summary(self) -> MailboxHandle[pb.Result]: + get_summary = pb.GetSummaryRequest() + return self._deliver_get_summary(get_summary) + + @abc.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) + + @abc.abstractmethod + def _deliver_get_system_metrics( + self, get_summary: pb.GetSystemMetricsRequest + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + def deliver_exit(self, exit_code: int | None) -> MailboxHandle[pb.Result]: + exit_data = self._make_exit(exit_code) + return self._deliver_exit(exit_data) + + @abc.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) + + @abc.abstractmethod + def _deliver_poll_exit( + self, + poll_exit: pb.PollExitRequest, + ) -> 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) + + @abc.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) + + @abc.abstractmethod + def _deliver_request_run_status( + self, run_status: pb.RunStatusRequest + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/interface/interface_queue.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/interface/interface_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..8ab20b2db31d3bcd8c207aa208ddf9d233df206b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/interface/interface_queue.py @@ -0,0 +1,59 @@ +from __future__ import annotations + +import logging +from multiprocessing.process import BaseProcess +from typing import TYPE_CHECKING + +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): + """Legacy implementation of InterfaceShared. + + This was used by legacy-service to pass messages back to itself before + the existence of wandb-core. It may be removed once legacy-service is + completely removed (including its use in `wandb sync`). + + Since it was used by the internal service, it does not implement + the "deliver" methods, which are only used in the client. + """ + + def __init__( + self, + record_q: Queue[pb.Record] | None = None, + result_q: Queue[pb.Result] | None = None, + process: BaseProcess | None = None, + ) -> None: + self.record_q = record_q + self.result_q = result_q + self._process = process + super().__init__() + + @override + def _publish(self, record: pb.Record, *, nowait: bool = False) -> None: + if self._process and not self._process.is_alive(): + raise Exception("The wandb backend process has shutdown") + if self.record_q: + self.record_q.put(record) + + @override + async def deliver_async( + self, + record: pb.Record, + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + @override + def _deliver(self, record: pb.Record) -> MailboxHandle[pb.Result]: + raise NotImplementedError diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/interface/interface_shared.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/interface/interface_shared.py new file mode 100644 index 0000000000000000000000000000000000000000..22d48e9c03b97a4e5d1b3b03b182501a9c622836 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/interface/interface_shared.py @@ -0,0 +1,492 @@ +from __future__ import annotations + +import abc +import logging +from typing import Any, cast + +from typing_extensions import override + +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, abc.ABC): + """Partially implemented InterfaceBase. + + There is little reason for this to exist separately from InterfaceBase, + which itself is not a pure abstract class and has no other direct + subclasses. Most methods are implemented in this class in terms of the + protected _publish and _deliver methods defined by subclasses. + """ + + def __init__(self) -> None: + super().__init__() + + @abc.abstractmethod + def _publish( + self, + record: pb.Record, + *, + nowait: bool = False, + ) -> None: + """Send a record to the internal service. + + Args: + record: The record to send. This method assigns its stream ID. + nowait: If true, this does not block on socket IO and is safe + to call in W&B's asyncio thread, but it will also not slow + down even if the socket is blocked and allow data to accumulate + in the Python memory. + """ + + @abc.abstractmethod + def _deliver(self, record: pb.Record) -> MailboxHandle[pb.Result]: + """Send a record to the internal service and return a response handle. + + Args: + record: The record to send. This method assigns its stream ID. + + Returns: + A mailbox handle for waiting for a response. + """ + + @override + def _publish_output( + self, + outdata: pb.OutputRecord, + *, + nowait: bool = False, + ) -> None: + rec = pb.Record() + rec.output.CopyFrom(outdata) + self._publish(rec, nowait=nowait) + + @override + def _publish_output_raw( + self, + outdata: pb.OutputRawRecord, + *, + nowait: bool = False, + ) -> None: + rec = pb.Record() + rec.output_raw.CopyFrom(outdata) + self._publish(rec, nowait=nowait) + + @override + def _publish_output_logger( + self, + outdata: pb.OutputLoggerRecord, + *, + nowait: bool = False, + ) -> None: + rec = pb.Record() + rec.output_logger.CopyFrom(outdata) + self._publish(rec, nowait=nowait) + + def _publish_cancel(self, cancel: pb.CancelRequest) -> None: + rec = self._make_request(cancel=cancel) + 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: pb.GetSummaryRequest | None = None, + pause: pb.PauseRequest | None = None, + resume: pb.ResumeRequest | None = None, + status: pb.StatusRequest | None = None, + network_status: pb.NetworkStatusRequest | None = None, + poll_exit: pb.PollExitRequest | None = None, + partial_history: pb.PartialHistoryRequest | None = None, + sampled_history: pb.SampledHistoryRequest | None = None, + run_start: pb.RunStartRequest | None = None, + check_version: pb.CheckVersionRequest | None = None, + log_artifact: pb.LogArtifactRequest | None = None, + download_artifact: pb.DownloadArtifactRequest | None = None, + link_artifact: pb.LinkArtifactRequest | None = None, + defer: pb.DeferRequest | None = None, + attach: pb.AttachRequest | None = None, + server_info: pb.ServerInfoRequest | None = None, + keepalive: pb.KeepaliveRequest | None = None, + run_status: pb.RunStatusRequest | None = None, + sender_mark: pb.SenderMarkRequest | None = None, + sender_read: pb.SenderReadRequest | None = None, + sync_finish: pb.SyncFinishRequest | None = None, + status_report: pb.StatusReportRequest | None = None, + cancel: pb.CancelRequest | None = None, + summary_record: pb.SummaryRecordRequest | None = None, + telemetry_record: pb.TelemetryRecordRequest | None = None, + get_system_metrics: pb.GetSystemMetricsRequest | None = None, + python_packages: pb.PythonPackagesRequest | None = None, + job_input: pb.JobInputRequest | None = None, + probe_system_info: pb.ProbeSystemInfoRequest | None = 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 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 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: pb.RunRecord | None = None, + config: pb.ConfigRecord | None = None, + files: pb.FilesRecord | None = None, + summary: pb.SummaryRecord | None = None, + history: pb.HistoryRecord | None = None, + stats: pb.StatsRecord | None = None, + exit: pb.RunExitRecord | None = None, + artifact: pb.ArtifactRecord | None = None, + tbrecord: pb.TBRecord | None = None, + alert: pb.AlertRecord | None = None, + final: pb.FinalRecord | None = None, + metric: pb.MetricRecord | None = None, + header: pb.HeaderRecord | None = None, + footer: pb.FooterRecord | None = None, + request: pb.Request | None = None, + telemetry: tpb.TelemetryRecord | None = None, + preempting: pb.RunPreemptingRecord | None = None, + use_artifact: pb.UseArtifactRecord | None = None, + output: pb.OutputRecord | None = None, + output_raw: pb.OutputRawRecord | None = None, + environment: pb.EnvironmentRecord | None = 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 + + def _publish_defer(self, state: pb.DeferRequest.DeferState) -> None: + defer = pb.DeferRequest(state=state) + rec = self._make_request(defer=defer) + rec.control.local = True + self._publish(rec) + + def publish_defer(self, state: int = 0) -> None: + self._publish_defer(cast("pb.DeferRequest.DeferState", 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_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_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_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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/interface/interface_sock.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/interface/interface_sock.py new file mode 100644 index 0000000000000000000000000000000000000000..79b914dff1fd71ecb538f18300b56fea9b69c95b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/interface/interface_sock.py @@ -0,0 +1,59 @@ +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING + +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: pb.Record) -> None: + record._info.stream_id = self._stream_id + + @override + def _publish(self, record: pb.Record, *, nowait: bool = False) -> None: + self._assign(record) + request = spb.ServerRequest() + request.record_publish.CopyFrom(record) + + if nowait: + self._asyncer.run_soon(lambda: self._client.publish(request)) + else: + self._asyncer.run(lambda: self._client.publish(request)) + + @override + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/interface/summary_record.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/interface/summary_record.py new file mode 100644 index 0000000000000000000000000000000000000000..9fdf25fb8551dd87fa39624d339f4cb10a9be965 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/interface/summary_record.py @@ -0,0 +1,69 @@ +"""Summary Record. + +This module implements a summary record as an intermediate format before being converted +to a protocol buffer. +""" + +from __future__ import annotations + +import typing as t + + +class SummaryRecord: + """Encodes a diff -- analogous to the SummaryRecord protobuf message.""" + + update: list[SummaryItem] + remove: 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: 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..384844d23830a35243901eaf0ad56d83c3d9add0 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/context.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/context.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3103560650a9389115e672a24195fd99d371cf69 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/context.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/datastore.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/datastore.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5086c12dfd3d850a103242c19cfad608fd29b7c1 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/datastore.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/file_pusher.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/file_pusher.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d025781adedf4c8d3b6da5cb7a3e7f08580e34f Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/file_pusher.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/file_stream.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/file_stream.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4722247a82429d5c64850b9cfd1248df94ba5e64 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/file_stream.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/handler.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/handler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ba5482deae302c2f79d5505a78d6ee5da55b0c6 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/handler.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/incremental_table_util.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/incremental_table_util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f552b144f240666006d9930de09d51615efc2cc Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/incremental_table_util.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/job_builder.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/job_builder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dca03f5126a4a736837b4da5d3d376b90414c8e9 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/job_builder.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/profiler.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/profiler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e382e226e145743a83abd73efea7683ffaa8788d Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/profiler.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/progress.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/progress.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b82a1940368658485466ea03630eaf83f61eb0d9 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/progress.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/run.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/run.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4581f9cb280df55ede7512ff26da0856dcc395c Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/run.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/sample.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/sample.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..907de4ea3d65a97a76e76dba9724e4fce15ed35e Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/sample.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/sender.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/sender.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..345f89c1b18bc9fbf365d956d9b2d0e38cc1679a Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/sender.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/sender_config.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/sender_config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f49008934345410c9259a7947d3b164a5af0e44 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/sender_config.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/settings_static.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/settings_static.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f06eed2c6b079fe3e2a49f085e7ac2c9cc491313 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/settings_static.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/tb_watcher.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/tb_watcher.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc2fcea64909c4c1a1b471540146dcea422a20a0 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/__pycache__/tb_watcher.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..efba046d8a690634a316a9033f74e8320370e61e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdb0ca9748b217b622ba5bd5caa53e83fc3519a8 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/__pycache__/enums.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/__pycache__/enums.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3439e5e5c749924adf828b2dc485d6f0b62eec8 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/__pycache__/enums.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/__pycache__/input_types.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/__pycache__/input_types.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f147b26a08ddbb85843fbe76173319a40210ef4 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/__pycache__/input_types.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/__pycache__/operations.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/__pycache__/operations.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e0743be4743c7fcb5b6356eab5c899c3e7f2a21 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/__pycache__/operations.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/__pycache__/server_features_query.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/__pycache__/server_features_query.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b152562a6de07ea9c3076c93f2ce1bbd0c3d6063 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/__pycache__/server_features_query.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/enums.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..cc7d61d95669bab416e88c3acc378913704e64e8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/input_types.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/input_types.py new file mode 100644 index 0000000000000000000000000000000000000000..cc7d61d95669bab416e88c3acc378913704e64e8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/operations.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/operations.py new file mode 100644 index 0000000000000000000000000000000000000000..6d204236d0154d142ccc4ac22ade6befe7e6e012 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/server_features_query.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/_generated/server_features_query.py new file mode 100644 index 0000000000000000000000000000000000000000..c31ee720f7db95dcb97c8015b0a29db83c6cf07b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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 GQLResult + + +class ServerFeaturesQuery(GQLResult): + server_info: Optional[ServerFeaturesQueryServerInfo] = Field(alias="serverInfo") + + +class ServerFeaturesQueryServerInfo(GQLResult): + features: List[Optional[ServerFeaturesQueryServerInfoFeatures]] + + +class ServerFeaturesQueryServerInfoFeatures(GQLResult): + name: str + is_enabled: bool = Field(alias="isEnabled") + + +ServerFeaturesQuery.model_rebuild() +ServerFeaturesQueryServerInfo.model_rebuild() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/context.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/context.py new file mode 100644 index 0000000000000000000000000000000000000000..c83c2453954dc73b65c5c91a1ed0953216c6e4e6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/context.py @@ -0,0 +1,90 @@ +"""Context Keeper.""" + +from __future__ import annotations + +import logging +import threading + +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) -> Context | None: + 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) -> Context | None: + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/datastore.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/datastore.py new file mode 100644 index 0000000000000000000000000000000000000000..b7a30d25d7bc0a1cd2172bec38b8be4074c43721 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/datastore.py @@ -0,0 +1,283 @@ +"""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 +""" + +from __future__ import annotations + +import logging +import os +import struct +import zlib +from typing import TYPE_CHECKING + +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") + +except Exception: + strtobytes = str + + +class DataStore: + _index: int + _flush_offset: int + + def __init__(self) -> None: + self._opened_for_scan = False + self._fp: IO[Any] | None = 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 + + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/file_pusher.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/file_pusher.py new file mode 100644 index 0000000000000000000000000000000000000000..f5ce01544041573add44ce612b76bd864273e41d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/file_pusher.py @@ -0,0 +1,179 @@ +from __future__ import annotations + +import concurrent.futures +import logging +import os +import queue +import tempfile +import threading +import time +from typing import TYPE_CHECKING + +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: SettingsStatic | None = 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: step_upload.OnRequestFinishFn | None = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/file_stream.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/file_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..645b843b4b335702c91bf644900c92308a55af38 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/file_stream.py @@ -0,0 +1,672 @@ +from __future__ import annotations + +import functools +import itertools +import json +import logging +import os +import queue +import random +import sys +import threading +import time +from collections.abc import Callable +from types import TracebackType +from typing import TYPE_CHECKING, Any, NamedTuple + +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.analytics import get_sentry +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] + ) -> 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) + get_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]) -> 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) + get_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: int | None + last_normal: int | None + + 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: dict | None = None, + ) -> None: + settings = settings or dict() + # NOTE: exc_info is set in thread_except_body context and readable by calling threads + self._exc_info: ( + tuple[type[BaseException], BaseException, TracebackType] + | tuple[None, 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) -> int | float: + # Defaults to 30 + heartbeat_seconds: int | float = self._api.dynamic_settings["heartbeat_seconds"] + return heartbeat_seconds + + def rate_limit_seconds(self) -> 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: FileStreamApi.Finish | None = 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") + get_sentry().exception(exc_info) + raise + + def _handle_response(self, response: 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: dict | None = 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: set[str] | None = 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, + ) + ) + + return not ( + uploaded_list + and isinstance( + request_with_retry( + self._client.post, + self._endpoint, + json={ + "complete": False, + "failed": False, + "dropped": self._dropped_chunks, + "uploaded": uploaded_list, + }, + ), + Exception, + ) + ) + + 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, +) -> 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: Callable | None = 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) and ( + e.response is not None + and e.response.status_code in {400, 403, 404, 409} + ): + # 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. + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/handler.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/handler.py new file mode 100644 index 0000000000000000000000000000000000000000..a921255f5a223299462d9af7a6fba2908b5fa578 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/handler.py @@ -0,0 +1,842 @@ +"""Handle Manager.""" + +from __future__ import annotations + +import json +import logging +import math +import numbers +import time +from collections import defaultdict +from collections.abc import Callable, Iterable, Sequence +from queue import Queue +from threading import Event +from typing import TYPE_CHECKING, Any, 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: RunRecord | None + _settings: SettingsStatic + _record_q: Queue[Record] + _result_q: Queue[Result] + _stopped: Event + _writer_q: Queue[Record] + _interface: InterfaceQueue + _tb_watcher: tb_watcher.TBWatcher | None + _metric_defines: dict[str, MetricRecord] + _metric_globs: dict[str, MetricRecord] + _metric_track: dict[tuple[str, ...], float] + _metric_copy: dict[tuple[str, ...], Any] + _track_time: float | None + _accumulate_time: float + _run_start_time: float | None + _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: bool | None, + ) -> bool: + updated = False + best_key: tuple[str, ...] | None = None + if s.none: + return False + if s.copy and len(kl) > 1: + # non-key list copy already done in _update_summary + _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: MetricRecord | None = 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 + return bool( + self._update_summary_metrics( + d.summary, kl=kl, v=v, float_v=float_v, goal_max=goal_max + ) + ) + + def _update_summary_list( + self, + kl: list[str], + v: Any, + d: MetricRecord | None = 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) -> MetricRecord | None: + """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("*") and 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 and 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 and "_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: int | None = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/incremental_table_util.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/incremental_table_util.py new file mode 100644 index 0000000000000000000000000000000000000000..b1d53f7eac0cdc19328f05937427bbd173e0bdfd --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/internal_api.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/internal_api.py new file mode 100644 index 0000000000000000000000000000000000000000..bf1121d98e2815c4d733dcb6a433d4a2b6376978 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/internal_api.py @@ -0,0 +1,4099 @@ +from __future__ import annotations + +import base64 +import datetime +import functools +import http.client +import json +import logging +import os +import re +import socket +import sys +import threading +from collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence +from copy import deepcopy +from pathlib import Path +from typing import IO, TYPE_CHECKING, Any, Literal, NamedTuple, TextIO, overload + +import click +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.analytics import get_sentry +from wandb.apis.normalize import normalize_exceptions, parse_backend_error_messages +from wandb.errors import AuthenticationError, CommError, UsageError +from wandb.integration.sagemaker import parse_sm_secrets +from wandb.proto.wandb_internal_pb2 import ServerFeature +from wandb.sdk import wandb_setup +from wandb.sdk.internal import settings_static +from wandb.sdk.internal._generated import SERVER_FEATURES_QUERY_GQL, ServerFeaturesQuery +from wandb.sdk.lib.gql_request import GraphQLSession +from wandb.sdk.lib.hashutil import B64MD5, md5_file_b64 + +from ..lib import retry, wbauth +from ..lib.filenames import DIFF_FNAME, METADATA_FNAME +from . import context +from .progress import Progress + +logger = logging.getLogger(__name__) + +LAUNCH_DEFAULT_PROJECT = "model-registry" + +if TYPE_CHECKING: + from typing import Literal, TypedDict + + import requests + + from .progress import ProgressFn + + class CreateArtifactFileSpecInput(TypedDict, total=False): + """Corresponds to `type CreateArtifactFileSpecInput` in schema.graphql.""" + + artifactID: str + name: str + md5: str + mimetype: str | None + artifactManifestID: str | None + uploadPartsInput: list[dict[str, object]] | None + + class CreateArtifactFilesResponseFile(TypedDict): + id: str + name: str + displayName: str + uploadUrl: str | None + 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, total=False): + section: str + git_remote: str + ignore_globs: list[str] + base_url: str + root_dir: str | None + api_key: str | None + entity: str | None + organization: str | None + project: str | None + _extra_http_headers: Mapping[str, str] | None + _proxies: Mapping[str, str] | None + + _Response = MutableMapping + SweepState = Literal["RUNNING", "PAUSED", "CANCELED", "FINISHED"] + Number = int | float + +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: context.Context | None + + 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: ( + wandb.Settings # + | settings_static.SettingsStatic + | DefaultSettings + | None + ) = None, + load_settings: bool = True, + retry_timedelta: datetime.timedelta | None = None, + environ: MutableMapping[str, str] = os.environ, + retry_callback: Callable[[int, str], Any] | None = None, + api_key: str | None = None, + ) -> None: + import requests + + self._environ = environ + self._global_context = context.Context() + self._local_data = _ThreadLocalData() + + default_overrides: dict[str, Any] = ( + dict(default_settings) if default_settings else {} + ) + self.default_settings: DefaultSettings = { + "section": default_overrides.get("section", "default"), + "git_remote": default_overrides.get("git_remote", "origin"), + "ignore_globs": default_overrides.get("ignore_globs", []), + "base_url": default_overrides.get("base_url", "https://api.wandb.ai"), + "root_dir": default_overrides.get("root_dir"), + "api_key": default_overrides.get("api_key"), + "entity": default_overrides.get("entity"), + "organization": default_overrides.get("organization"), + "project": default_overrides.get("project"), + "_extra_http_headers": default_overrides.get("_extra_http_headers"), + "_proxies": default_overrides.get("_proxies"), + } + + if load_settings: + global_settings = wandb_setup.singleton().settings + if root_dir := self.default_settings["root_dir"]: + global_settings = global_settings.model_copy() + global_settings.root_dir = root_dir + + self._settings = global_settings.read_system_settings().all() + else: + self._settings = {} + + # Mutable settings set by the _file_stream_api + self.dynamic_settings = { + "system_sample_seconds": 2, + "system_samples": 15, + "heartbeat_seconds": 30, + } + + self.retry_timedelta = retry_timedelta or datetime.timedelta(days=7) + self.retry_uploads = 10 + + # 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", "{}") + ) + + 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}" + else: + 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", + 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: str | None = 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._max_cli_version: str | None = None + + self._server_features_cache: dict[str, bool] | None = 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: context.Context | None) -> 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.""" + import requests + + 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.gql(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) -> str | None: + return self._current_run_id + + @property + def user_agent(self) -> str: + return f"W&B Internal Client {wandb.__version__}" + + @property + def api_key(self) -> str | None: + from wandb.sdk.lib import wbauth + + if ( # + (auth := wbauth.session_credentials(host=self.api_url)) + and isinstance(auth, wbauth.AuthApiKey) + ): + return auth.api_key + + return ( + os.getenv(env.API_KEY) + or wbauth.read_netrc_auth(host=self.api_url) + or parse_sm_secrets().get(env.API_KEY) + or self.default_settings.get("api_key") + ) + + @property + def access_token(self) -> str | None: + """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: + str | None: 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}") + + auth = wbauth.AuthIdentityTokenFile( + host=self.settings("base_url"), + path=str(token_file), + credentials_file=wandb_setup.singleton().settings.credentials_file, + ) + return auth.fetch_access_token() + + @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 + + @overload + def settings(self, key: None = None) -> dict[str, Any]: ... + + @overload + def settings(self, key: str) -> Any: ... + + def settings(self, key: str | None = 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: dict[str, Any] = dict(self.default_settings) + result.update(self._settings) + result.update( + { + "entity": env.get_entity( + self._settings.get( + "entity", + result.get("entity"), + ), + env=self._environ, + ), + "organization": env.get_organization( + self._settings.get( + "organization", + result.get("organization"), + ), + env=self._environ, + ), + "project": env.get_project( + self._settings.get( + "project", + result.get("project"), + ), + env=self._environ, + ), + "base_url": env.get_base_url( + self._settings.get( + "base_url", + result.get("base_url"), + ), + env=self._environ, + ), + } + ) + + return result if key is None else result[key] + + def clear_setting(self, key: str) -> None: + self._settings.pop(key, None) + + def set_setting(self, key: str, value: Any) -> None: + self._settings[key] = value + + 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: str | None = None, run: str | None = 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 fail_run_queue_item( + self, + run_queue_item_id: str, + message: str, + stage: str, + file_paths: list[str] | None = None, + ) -> bool: + variable_values: dict[str, str | (list[str] | None)] = { + "runQueueItemId": run_queue_item_id, + "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 + } + } + """ + + mutation = gql(mutation_string) + response = self.gql(mutation, variable_values=variable_values) + result: bool = response["failRunQueueItem"]["success"] + return result + + 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: int | str) -> bool: + """Return whether the current server supports the given feature. + + NOTE: This is deprecated. Outside of this file, please use + `ServiceApi.feature_enabled()`. The `ServiceApi` is a sort of + replacement to this "internal" `Api` class. + + 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: list[str] | None = None, + ) -> bool: + 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) -> str | None: + if self._max_cli_version is not None: + return self._max_cli_version + + _, 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]]: + query = gql( + """ + query Viewer{ + viewer { + id + entity + username + email + flags + teams { + edges { + node { + name + } + } + } + } + serverInfo { + cliVersionInfo + latestLocalVersionInfo { + outOfDate + latestVersionString + versionOnThisInstanceString + } + } + } + """ + ) + res = self.gql(query) + return res.get("viewer") or {}, res.get("serverInfo") or {} + + @normalize_exceptions + def list_projects(self, entity: str | None = 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: str | None = 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: str | None = None, + entity: str | None = 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: str | None = 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: str | None = None, entity: str | None = None + ) -> tuple[str, dict[str, Any], str | None, 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. + """ + import requests + + 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: str | None = 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 + ) -> dict[str, Any] | None: + """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: str | None = None, + description: str | None = None, + entity: str | None = 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, + }, + ) + 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: dict[str, float | int | str] | None, + ) -> dict[str, Any] | None: + mutation_params = """ + $entityName: String!, + $resource: String!, + $config: JSONString!, + $templateVariables: JSONString + """ + mutation_inputs = """ + entityName: $entityName, + resource: $resource, + config: $config, + templateVariables: $templateVariables + """ + + variable_values = { + "entityName": entity, + "resource": resource, + "config": config, + } + + 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: dict[str, Any] | None = 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: str | None = None, + config_id: str | None = None, + ) -> dict[str, Any] | None: + 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, + } + + result: dict[str, Any] | None = 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: str | None = None, + template_variables: dict | None = None, + external_links: dict | None = None, + ) -> dict[str, Any] | None: + 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: dict[str, int | float | str] | None, + priority: int | None = None, + ) -> dict[str, Any] | None: + 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 priority is not None: + variables["priority"] = priority + mutation_params += ", $priority: Int" + mutation_input += ", priority: $priority" + + if template_variables is not None: + variables.update({"templateVariableValues": json.dumps(template_variables)}) + mutation_params += ", $templateVariableValues: JSONString" + mutation_input += ", templateVariableValues: $templateVariableValues" + + mutation = gql( + f""" + mutation pushToRunQueueByName( + {mutation_params} + ) {{ + pushToRunQueueByName( + input: {{ + {mutation_input} + }} + ) {{ + runQueueItemId + runSpec + }} + }} + """ + ) + + try: + result: dict[str, Any] | None = 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: dict | None, + project_queue: str, + priority: int | None = None, + ) -> dict[str, Any] | None: + 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 template_variables is not None: + mutation_params += ", $templateVariableValues: JSONString" + mutation_input += ", templateVariableValues: $templateVariableValues" + variables.update({"templateVariableValues": json.dumps(template_variables)}) + + 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: dict[str, Any] | None = response["pushToRunQueue"] + return result + + @normalize_exceptions + def pop_from_run_queue( + self, + queue_name: str, + entity: str | None = None, + project: str | None = None, + agent_id: str | None = None, + ) -> dict[str, Any] | None: + 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: dict[str, Any] | None = response["popFromRunQueue"] + return result + + @normalize_exceptions + def ack_run_queue_item(self, item_id: str, run_id: str | None = 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( + self, + entity: str, + project: str, + queues: list[str], + agent_config: dict[str, Any], + version: str, + ) -> 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])}" + ) + + hostname = socket.gethostname() + + variable_values = { + "entity": entity, + "project": project, + "queues": polling_queue_ids, + "hostname": hostname, + "agentConfig": json.dumps(agent_config), + "version": version, + } + + mutation_params = """ + $entity: String!, + $project: String!, + $queues: [ID!]!, + $hostname: String!, + $agentConfig: JSONString, + $version: String + """ + + mutation_input = """ + entityName: $entity, + projectName: $project, + runQueues: $queues, + hostname: $hostname, + agentConfig: $agentConfig, + 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, + ) -> dict: + 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) -> dict: + 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: str | None = None, + name: str | None = None, + project: str | None = None, + host: str | None = None, + group: str | None = None, + tags: list[str] | None = None, + config: dict | None = None, + description: str | None = None, + entity: str | None = None, + state: str | None = None, + display_name: str | None = None, + notes: str | None = None, + repo: str | None = None, + job_type: str | None = None, + program_path: str | None = None, + commit: str | None = None, + sweep_name: str | None = None, + summary_metrics: str | None = None, + num_retries: int | None = None, + ) -> tuple[dict, bool]: + """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 + } + } + """ + + 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"]) + + return ( + response["upsertBucket"]["bucket"], + response["upsertBucket"]["inserted"], + ) + + @normalize_exceptions + def rewind_run( + self, + run_name: str, + metric_name: str, + metric_value: float, + program_path: str | None = None, + entity: str | None = None, + project: str | None = None, + num_retries: int | None = 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 upload_urls( + self, + project: str, + files: list[str] | dict[str, IO], + run: str | None = None, + entity: str | None = None, + description: str | None = 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" + + 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: list[str] | dict[str, IO], + run: str | None = None, + entity: str | None = None, + description: str | None = 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: str | None = None, + entity: str | None = 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: str | None = None, + entity: str | None = None, + ) -> dict[str, str] | None: + """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 + """ + import requests + + check_httpclient_logger_handler() + + http_headers = {} + + auth = None + if self.access_token is not None: + http_headers["Authorization"] = f"Bearer {self.access_token}" + else: + auth = ("api", self.api_key or "") + + response = requests.get( + url, + auth=auth, + 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: str | None = None, + ) -> tuple[str, requests.Response | None]: + """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.""" + import requests + 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: bytes | None = 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: dict[str, str] | None = None, + ) -> requests.Response | None: + """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 + """ + import requests + + 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: + get_sentry().reraise(e) + return response + + def upload_file( + self, + url: str, + file: IO[bytes], + callback: ProgressFn | None = None, + extra_headers: dict[str, str] | None = None, + ) -> requests.Response | None: + """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 + """ + import requests + + check_httpclient_logger_handler() + extra_headers = extra_headers.copy() if extra_headers else {} + response: requests.Response | None = 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: + get_sentry().reraise(e) + + return response + + @normalize_exceptions + def register_agent( + self, + host: str, + sweep_id: str | None = None, + project_name: str | None = None, + entity: str | None = 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. + + Raises: + SweepNotFoundError: If the server returns a 404, indicating the + sweep was likely deleted. + """ + import requests + + from wandb.sdk.launch.sweeps import SweepNotFoundError + + 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 requests.exceptions.HTTPError as e: + if e.response is not None and e.response.status_code == 404: + raise SweepNotFoundError( + "Sweep not found. The sweep may have been deleted." + ) from e + logger.exception("Error communicating with W&B.") + return [] + 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 + and "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: str | None = None, + launch_scheduler: str | None = None, + scheduler: str | None = None, + obj_id: str | None = None, + project: str | None = None, + entity: str | None = None, + state: str | None = None, + prior_runs: list[str] | None = None, + display_name: str | None = None, + template_variable_values: dict[str, Any] | None = 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 + """ + import yaml + + 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. + 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) + + config_str = yaml.dump( + json.loads(json.dumps(config)), Dumper=NonOctalStringDumper + ) + filters = None + if prior_runs: + filters = json.dumps({"$or": [{"name": r} for r in prior_runs]}) + + err: Exception | None = 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 + + @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: str | None = None, entity: str | None = 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: list[str] | dict[str, IO], + run: str | None = None, + entity: str | None = None, + project: str | None = None, + description: str | None = None, + force: bool = True, + progress: TextIO | Literal[False] = False, + ) -> list[requests.Response | None]: + """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]: + from wandb.sdk.artifacts._validators import is_artifact_registry_project + + 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.") + + 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: str | None = None, + project_name: str | None = None, + run_name: str | None = None, + use_as: str | None = None, + artifact_entity_name: str | None = None, + artifact_project_name: str | None = 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", + ] + + if 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: str | None = None, + project_name: str | None = None, + run_name: str | None = None, + artifact_entity_name: str | None = None, + artifact_project_name: str | None = None, + use_as: str | None = None, + ) -> dict[str, Any] | None: + 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 + + def create_artifact_type( + self, + artifact_type_name: str, + entity_name: str | None = None, + project_name: str | None = None, + description: str | None = None, + ) -> str | None: + 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: str | None = response["createArtifactType"]["artifactType"]["id"] + return _id + + def _get_create_artifact_mutation( + self, + history_step: int | None, + distributed_id: str | None, + ) -> str: + types = "" + values = "" + + if history_step not in [0, None]: + types += "$historyStep: Int64!," + values += "historyStep: $historyStep," + + if distributed_id: + types += "$distributedID: String," + values += "distributedID: $distributedID," + + query_template = """ + mutation CreateArtifact( + $artifactTypeName: String!, + $artifactCollectionNames: [String!], + $entityName: String!, + $projectName: String!, + $runName: String, + $description: String, + $digest: String!, + $aliases: [ArtifactAliasInput!], + $metadata: JSONString, + $clientID: ID, + $sequenceClientID: ID, + $ttlDurationSeconds: Int64, + $tags: [TagInput!], + _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, + clientID: $clientID, + sequenceClientID: $sequenceClientID, + enableDigestDeduplication: true, + ttlDurationSeconds: $ttlDurationSeconds, + tags: $tags, + _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: str | None = None, + sequence_client_id: str | None = None, + entity_name: str | None = None, + project_name: str | None = None, + run_name: str | None = None, + description: str | None = None, + metadata: dict | None = None, + ttl_duration_seconds: int | None = None, + aliases: list[dict[str, str]] | None = None, + tags: list[dict[str, str]] | None = None, + distributed_id: str | None = None, + is_user_created: bool | None = False, + history_step: int | None = None, + ) -> tuple[dict, dict]: + query_template = self._get_create_artifact_mutation( + 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: str | None, + complete_multipart_action: str = "Complete", + ) -> str | None: + 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: str | None = response["completeMultipartUploadArtifact"]["digest"] + return digest + + def create_artifact_manifest( + self, + name: str, + digest: str, + artifact_id: str | None, + base_artifact_id: str | None = None, + entity: str | None = None, + project: str | None = None, + run: str | None = 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: str | None = None, + digest: str | None = None, + include_upload: bool | None = 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, + ) -> str | None: + 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 + + @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 + storagePath + uploadMultipartUrls { + uploadID + uploadUrlParts { + partNumber + uploadUrl + } + } + artifact { + id + } + } + } + } + } + } + """ + + # 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" + + 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: str | None = None, + wait_duration: Number | None = 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: str | None = None, project: str | None = None + ) -> SweepState: + query = gql( + """ + query GetSweepState($entity: String, $project: String, $sweep: String!) { + project(name: $project, entityName: $entity) { + sweep(sweepName: $sweep) { + state + } + } + } + """ + ) + response = self.gql( + query, + variable_values={ + "sweep": sweep, + "entity": entity or self.settings("entity"), + "project": project or self.settings("project"), + }, + ) + return response["project"]["sweep"]["state"] + + def set_sweep_state( + self, + sweep: str, + state: SweepState, + entity: str | None = None, + project: str | None = 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: str | None = None, + project: str | None = 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: str | None = None, + project: str | None = 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: str | None = None, + project: str | None = 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: str | None = None, + project: str | None = 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.""" + import requests + + 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: str | Mapping[str, Any], + ) -> dict[str, Any] | None: + 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: dict[str, Any] | None = self.gql(mutation, variable_values)[ + "createCustomChart" + ] + return result diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/job_builder.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/job_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..8fad99c7674b339761f0d7b800270e4ec283676a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/job_builder.py @@ -0,0 +1,641 @@ +"""job builder.""" + +from __future__ import annotations + +import json +import logging +import os +import re +import sys +from collections.abc import Callable +from typing import TYPE_CHECKING, Any, Literal, TypedDict + +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 and 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: str | None + dockerfile: str | None + + +class ArtifactSourceDict(TypedDict): + artifact: str + entrypoint: list[str] + notebook: bool + build_context: str | None + dockerfile: str | None + + +class ImageSourceDict(TypedDict): + image: 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] + + +class ArtifactInfoForJob(TypedDict): + id: str + name: str + + +def get_min_supported_for_source_dict( + source: GitSourceDict | ArtifactSourceDict | ImageSourceDict, +) -> Version | None: + """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 and (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: str | None + _requirements_path: str | None + _config: dict[str, Any] | None + _summary: dict[str, Any] | None + _logged_code_artifact: ArtifactInfoForJob | None + _disable: bool + _partial_source_id: str | None # Partial job source artifact id. + _aliases: list[str] + _job_seq_id: str | None + _job_version_alias: str | None + _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: Literal["repo", "artifact", "image"] | None = ( + 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: dict | None, 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[GitSourceDict | None, str | None]: + 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: Callable[[Any], None] | Callable[[Any], None] | 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[ArtifactSourceDict | None, str | None]: + 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/platform/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 and 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: str | None, + metadata: dict[str, Any], + ) -> tuple[ + GitSourceDict | ArtifactSourceDict | ImageSourceDict | None, + str | None, + ]: + """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: 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/platform/launch/create-job", + "warn", + ) + return None, None + + return source, name + + def build( + self, + api: Api, + build_context: str | None = None, + dockerfile: str | None = None, + base_image: str | None = None, + ) -> Artifact | None: + """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/platform/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/models/track/environment-variables", + "warn", + ) + return None + + runtime: str | None = 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/platform/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: str | None = None + source_info: JobSourceDict | None = 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/platform/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" and os.path.exists( + os.path.join(self._files_dir, DIFF_FNAME) + ): + # add diff + 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]) -> str | None: + 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] + ) -> str | None: + 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/platform/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, + ) -> dict | None: + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/profiler.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..9973e42984580a3fca6dc6706728a58ed22d4277 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/progress.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/progress.py new file mode 100644 index 0000000000000000000000000000000000000000..452a65e02644fe397c726cb7adc9149077cbdf52 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/progress.py @@ -0,0 +1,77 @@ +"""progress.""" + +from __future__ import annotations + +import os +from typing import IO, TYPE_CHECKING + +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: ProgressFn | None = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/run.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/run.py new file mode 100644 index 0000000000000000000000000000000000000000..885729a8b0c27eb91f9b0ff006576186be491235 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/sample.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/sample.py new file mode 100644 index 0000000000000000000000000000000000000000..7bffe7562e4b28614bad3e4c1cbf5be5423532fe --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/sender.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/sender.py new file mode 100644 index 0000000000000000000000000000000000000000..371a561e8541510143760a5085dab3f5993dfec3 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/sender.py @@ -0,0 +1,1682 @@ +"""sender.""" + +from __future__ import annotations + +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 collections.abc import Generator +from datetime import datetime +from queue import Queue +from typing import TYPE_CHECKING, Any, Literal + +import requests + +import wandb +from wandb import util +from wandb.analytics import get_sentry +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: int | None + summary: dict[str, Any] | None + config: dict[str, Any] | None + tags: list[str] | None + + 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: file_stream.FileStreamApi | None + _run: RunRecord | None + _entity: str | None + _project: str | None + _dir_watcher: DirWatcher | None + _pusher: FilePusher | None + _record_exit: Record | None + _exit_result: RunExitResult | None + _resume_state: ResumeState + _rewind_response: dict[str, Any] | None + _cached_server_info: dict[str, Any] + _cached_viewer: dict[str, Any] + _ds: datastore.DataStore | None + _output_raw_streams: dict[StreamLiterals, _OutputRawStream] + _output_raw_file: filesystem.CRDedupedFile | None + _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() + + # 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: 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: type[BaseException] | None, + exc_value: BaseException | None, + exc_traceback: traceback.TracebackException | None, + ) -> 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) -> wandb_internal_pb2.ErrorInfo | None: + """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: str | None = 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: sender_config.BackendConfigDict | None = 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: sender_config.BackendConfigDict | None, + ) -> 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 + inserted = True + else: + server_run, inserted = 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._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: str | None = 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) + get_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(filesystem.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: str | None = 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: filesystem.GlobStr, policy: filesystem.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( + filesystem.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(filesystem.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: int | None = None + ) -> dict | None: + 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 + get_sentry().end_session() + + def _max_cli_version(self) -> str | None: + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/sender_config.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/sender_config.py new file mode 100644 index 0000000000000000000000000000000000000000..aa4bcee881ce2654d87bcccc640cb8f56d42954f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/sender_config.py @@ -0,0 +1,206 @@ +from __future__ import annotations + +import json +from collections.abc import Sequence +from typing import Any, NewType + +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: dict[str, Any] | None = 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: str | None, + 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, +) -> dict[str, Any] | None: + """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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/settings_static.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/settings_static.py new file mode 100644 index 0000000000000000000000000000000000000000..cff36b2b6c06c9a956c70c46641947f3b6d41f47 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/settings_static.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +from collections.abc import Iterable +from typing import Any + +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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/tb_watcher.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/tb_watcher.py new file mode 100644 index 0000000000000000000000000000000000000000..59759c0cb2507e599cb7cf911655eb30a04459cf --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/internal/tb_watcher.py @@ -0,0 +1,520 @@ +"""tensorboard watcher.""" + +from __future__ import annotations + +import glob +import logging +import os +import queue +import socket +import sys +import threading +import time +from typing import TYPE_CHECKING, Any + +import wandb +from wandb import util +from wandb.plot import CustomChart +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.lib.filesystem 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=[(filesystem.GlobStr(glob.escape(file_name)), "live")]) + ) + + +def is_tfevents_file_created_by( + path: str, hostname: str | None, start_time: float | None +) -> 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: TBEventConsumer | None = 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) -> str | None: + namespace: str | None + 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: str | None, + 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: str | None = 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: float | None = 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: str | None): + self.event = event + self.namespace = namespace + self.created_at = time.time() + + def __lt__(self, other: Event) -> bool: + return self.event.wall_time < other.event.wall_time + + +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: filesystem.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: TBHistory | None = 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: + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7e904eff616c9977433debc96586b56665825708 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/_launch.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/_launch.py new file mode 100644 index 0000000000000000000000000000000000000000..1f2fddebdfa461f5cd422234e12ae8e8a4134f06 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/_launch.py @@ -0,0 +1,333 @@ +from __future__ import annotations + +import asyncio +import logging +import os +import sys +from typing import Any + +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: str | None, + max_jobs: int | None, + queues: tuple[str] | None, + config: str | None, + verbosity: int | None, +) -> 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. + """ + import yaml + + 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: str | None = None, + name: str | None = None, + project: str | None = None, + entity: str | None = None, + docker_image: str | None = None, + entry_point: list[str] | None = None, + version: str | None = None, + resource: str | None = None, + resource_args: dict[str, Any] | None = None, + launch_config: dict[str, Any] | None = None, + synchronous: bool | None = None, + run_id: str | None = None, + repository: str | None = 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: str | None = None, + entry_point: list[str] | None = None, + version: str | None = None, + name: str | None = None, + resource: str | None = None, + resource_args: dict[str, Any] | None = None, + project: str | None = None, + entity: str | None = None, + docker_image: str | None = None, + config: dict[str, Any] | None = None, + synchronous: bool | None = True, + run_id: str | None = None, + repository: str | None = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/_launch_add.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/_launch_add.py new file mode 100644 index 0000000000000000000000000000000000000000..76dd70c2e2838d2625c6119b1fc35710eb0beb68 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/_launch_add.py @@ -0,0 +1,257 @@ +from __future__ import annotations + +import asyncio +import pprint +from typing import Any + +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: dict | None, + project_queue: str, + priority: int | None = None, +) -> Any: + return api.push_to_run_queue( + queue_name, launch_spec, template_variables, project_queue, priority + ) + + +def launch_add( + uri: str | None = None, + job: str | None = None, + config: dict[str, Any] | None = None, + template_variables: dict[str, float | int | str] | None = None, + project: str | None = None, + entity: str | None = None, + queue_name: str | None = None, + resource: str | None = None, + entry_point: list[str] | None = None, + name: str | None = None, + version: str | None = None, + docker_image: str | None = None, + project_queue: str | None = None, + resource_args: dict[str, Any] | None = None, + run_id: str | None = None, + build: bool | None = False, + repository: str | None = None, + sweep_id: str | None = None, + author: str | None = None, + priority: int | None = 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: str | None, + config: dict[str, Any] | None, + template_variables: dict | None, + project: str | None, + entity: str | None, + queue_name: str | None, + resource: str | None, + entry_point: list[str] | None, + name: str | None, + version: str | None, + docker_image: str | None, + project_queue: str | None, + resource_args: dict[str, Any] | None = None, + run_id: str | None = None, + build: bool | None = False, + repository: str | None = None, + sweep_id: str | None = None, + author: str | None = None, + priority: int | None = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/_project_spec.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/_project_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..8b2b1456ac29ca1ade5880006214f0f85181b897 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/_project_spec.py @@ -0,0 +1,611 @@ +"""Convert launch arguments into a runnable wandb launch script. + +Arguments can come from a launch spec or call to wandb launch. +""" + +from __future__ import annotations + +import enum +import json +import logging +import os +import shlex +import shutil +import tempfile +from copy import deepcopy +from typing import TYPE_CHECKING, Any, 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 CODE_MOUNT_DIR, 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 + + +def _get_accelerator_base_image( + resource_args_build: dict[str, Any], +) -> str | None: + """Return configured accelerator base image from raw builder resource args.""" + for accelerator_key in ("accelerator", "cuda"): + base_image = resource_args_build.get(accelerator_key, {}).get("base_image") + if base_image is None or base_image == "": + continue + + if not isinstance(base_image, str): + raise LaunchError( + "Invalid accelerator base image. Expected " + f"builder.{accelerator_key}.base_image to be a string Docker " + f"image reference, got {type(base_image).__name__}." + ) + + return base_image + + return None + + +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: str | None, + job: str | None, + api: Api, + launch_spec: dict[str, Any], + target_entity: str, + target_project: str, + name: str | None, + docker_config: dict[str, Any], + git_info: dict[str, str], + overrides: dict[str, Any], + resource: str, + resource_args: dict[str, Any], + run_id: str | None, + sweep_id: str | None = None, + ): + self.uri = uri + self.job = job + if job is not None: + wandb.termlog(f"{LOG_PREFIX}Launching job: {job}") + self._job_artifact: Artifact | None = 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) + self._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: str | None = launch_spec.get("python_version") + self._job_dockerfile: str | None = None + self._job_build_context: str | None = None + self._job_base_image: str | None = None + self.accelerator_base_image: str | None = _get_accelerator_base_image( + self._resource_args_build + ) + self.docker_image: str | None = 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: EntryPoint | None = ( + None # todo: keep multiple entrypoint support? + ) + self.init_overrides(overrides) + self.init_source() + self.init_git(git_info) + self.deps_type: str | None = None + self._runtime: str | None = None + self.run_id = run_id or generate_id() + self._queue_name: str | None = None + self._queue_entity: str | None = None + self._run_queue_item_id: str | None = None + self._job_source_type: str | None = None + self._job_source_info: dict[str, Any] = {} + self._auto_default_base_image: bool = False + + 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: EntryPoint | None = None + self.override_dockerfile: str | None = 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, + ) + override_working_dir = overrides.get("working_dir") + self.resolved_working_dir: str = ( + f"{CODE_MOUNT_DIR}/{override_working_dir}" + if override_working_dir + else CODE_MOUNT_DIR + ) + + 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: str | None = 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"), # type: ignore [arg-type] + launch_spec.get("resource_args", {}), + launch_spec.get("run_id"), + launch_spec.get("sweep_id", {}), + ) + + @property + def job_dockerfile(self) -> str | None: + return self._job_dockerfile + + @property + def job_build_context(self) -> str | None: + return self._job_build_context + + @property + def job_base_image(self) -> str | None: + 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) -> str | None: + return self._queue_name + + @queue_name.setter + def queue_name(self, value: str) -> None: + self._queue_name = value + + @property + def queue_entity(self) -> str | None: + 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) -> str | None: + 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 + + @property + def job_source_type(self) -> str | None: + return self._job_source_type + + def set_job_source_type(self, source_type: str) -> None: + self._job_source_type = source_type + + @property + def job_source_info(self) -> dict[str, Any]: + return self._job_source_info + + def set_job_source_info(self, source_info: dict[str, Any]) -> None: + self._job_source_info = source_info + + 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 + return self.source != LaunchSource.JOB + + @property + def docker_image(self) -> str | None: + """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) -> EntryPoint | None: + """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: str | None, 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/create_job.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/create_job.py new file mode 100644 index 0000000000000000000000000000000000000000..9f33f95798b9d30f0fb8760887efab1eac671dd1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/create_job.py @@ -0,0 +1,543 @@ +from __future__ import annotations + +import json +import logging +import os +import re +import sys +import tempfile +from typing import Any + +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: str | None = None, + project: str | None = None, + name: str | None = None, + description: str | None = None, + aliases: list[str] | None = None, + runtime: str | None = None, + entrypoint: str | None = None, + git_hash: str | None = None, + build_context: str | None = None, + dockerfile: str | None = None, +) -> Artifact | None: + """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.10. + 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.10", + 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: str | None = None, + project: str | None = None, + name: str | None = None, + description: str | None = None, + aliases: list[str] | None = None, + runtime: str | None = None, + entrypoint: str | None = None, + git_hash: str | None = None, + build_context: str | None = None, + dockerfile: str | None = None, + base_image: str | None = None, + services: dict[str, str] | None = None, + schema: dict[str, Any] | None = None, +) -> tuple[Artifact | None, 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 and 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.10 or 3.11, 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: str | None, + runtime: str | None, + path: str, + entrypoint: str | None, +) -> tuple[dict[str, Any] | None, list[str] | None]: + """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: str | None = None, + runtime: str | None = None, +) -> dict[str, Any] | None: + # 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: str | None = None +) -> tuple[dict[str, Any] | None, list[str] | None]: + 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: str | None, + project: str | None, + name: str | None, +) -> str | None: + """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: str | None) -> 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: list[str] | None +) -> 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/errors.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..44111ff236245d71b59826791c5c232f0de3b090 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/git_reference.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/git_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..1049d1db3b3d397e314cb53a0f3ef7a4791f447d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/git_reference.py @@ -0,0 +1,110 @@ +"""Support for parsing GitHub URLs (which might be user provided) into constituent parts.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from enum import IntEnum + +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[str | None, str | None, 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: str | None = 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) -> str | None: + 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: 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/loader.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..fe99216b10c0e0eaa24c8a67ac3e48e496de9d15 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/loader.py @@ -0,0 +1,251 @@ +"""Utilities for the agent.""" + +from __future__ import annotations + +from typing import Any + +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: dict[str, Any] | None) -> 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: dict[str, Any] | None, 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/platform/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: dict[str, Any] | None, + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..00ea985f3481e935d4294e0fd16c24124c73f291 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/utils.py @@ -0,0 +1,817 @@ +from __future__ import annotations + +import asyncio +import json +import logging +import os +import platform +import re +import subprocess +import sys +from collections import defaultdict +from collections.abc import Iterator +from typing import TYPE_CHECKING, Any, 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) -> str | None: + job_parts = job.split("/") + if len(job_parts) == 3: + return job_parts[1] + return None + + +def set_project_entity_defaults( + uri: str | None, + job: str | None, + api: Api, + project: str | None, + entity: str | None, + launch_config: dict[str, Any] | None, +) -> tuple[str | None, 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: dict[str, Any] | None): + 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") and launch_spec.get("template_variables"): + 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: str | None, + job: str | None, + api: Api, + name: str | None, + project: str | None, + entity: str | None, + docker_image: str | None, + resource: str | None, + entry_point: list[str] | None, + version: str | None, + resource_args: dict[str, Any] | None, + launch_config: dict[str, Any] | None, + run_id: str | None, + repository: str | None, + author: str | None, + sweep_id: str | None = 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" +) -> str | None: + 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: str | None, + 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: str | None) -> str | None: + """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") + 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: dict[str, Any] | None, + build_config: dict[str, Any] | None, + registry_config: dict[str, Any] | None, +) -> 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: JobAndRunStatusTracker | None +) -> 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, str | None]) -> 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, str | None]) -> 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]) -> str | None: + """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: 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) and (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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/wandb_reference.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/wandb_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..937d939f4094af6bc25d0da2e96f514cebf675bf --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/launch/wandb_reference.py @@ -0,0 +1,131 @@ +"""Support for parsing W&B URLs (which might be user provided) into constituent parts.""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import IntEnum +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: str | None = None + + entity: str | None = None + project: str | None = None + + # Set when we don't know how to parse yet + path: str | None = None + + # Reference type will determine what other fields are set + ref_type: ReferenceType | None = None + + run_id: str | None = None + + job_name: str | None = 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) -> WandbReference | None: + """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 and parts[0] not in RESERVED_NON_ENTITIES: + ref.path = None + ref.entity = parts[0] + if len(parts) > 1 and 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) + return bool(ref and ref.is_job_or_run()) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4289765c6c7c4fda2dbe42dddc1f5f7d69da0c45 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/asyncio_compat.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/asyncio_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..50be01e1e2f7968a2db16aa71a47091718b83317 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/asyncio_compat.py @@ -0,0 +1,279 @@ +"""Functions for compatibility with asyncio.""" + +from __future__ import annotations + +import asyncio +import concurrent +import concurrent.futures +import contextlib +import threading +from collections.abc import AsyncIterator, Callable, Coroutine +from typing import Any, 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[None]] = [] + + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/asyncio_manager.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/asyncio_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..a8a07c54dc6d863d7a65bec5a006e4eb8b3fafac --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/asyncio_manager.py @@ -0,0 +1,256 @@ +"""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 collections.abc import Awaitable, Callable +from typing import 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[[], Awaitable[_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[[], Awaitable[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[[], Awaitable[_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( + "Cannot schedule tasks after join()." # + + " Did you call wandb.teardown()?" + ) + + 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[[], Awaitable[_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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/capped_dict.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/capped_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..63a4ea2b96aa738fd5402548ec355104aebb9030 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/capped_dict.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +import collections +from typing import Any + + +class CappedDict(collections.OrderedDict): + default_max_size = 50 + + def __init__(self, max_size: int | None = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/config_util.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/config_util.py new file mode 100644 index 0000000000000000000000000000000000000000..31b677f99fe6b5ed943d80147779fd5d58db70f8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/config_util.py @@ -0,0 +1,105 @@ +from __future__ import annotations + +import json +import logging +import os +from typing import Any + +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): + import yaml + + 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 +) -> dict[str, Any] | None: + import yaml + + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/console_capture.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/console_capture.py new file mode 100644 index 0000000000000000000000000000000000000000..65a2dcd6fc84bf44e8979e05ead026dce12f8746 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/console_capture.py @@ -0,0 +1,308 @@ +"""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 contextlib +import contextvars +import logging +import sys +import threading +from collections.abc import Callable, Iterator +from typing import IO, AnyStr, 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()`. + """ + + +# See _enter_callbacks() for why this is an RLock. +_module_rlock = threading.RLock() + +# See _enter_callbacks(). +_is_writing = False +_is_caused_by_callback = contextvars.ContextVar( + "_is_caused_by_callback", + default=False, +) + +_patch_exception: CannotCaptureConsoleError | None = None + + +def _maybe_raise_patch_exception() -> None: + """Raise _patch_exception if it's set.""" + if _patch_exception: + # Each `raise` call modifies the exception's __traceback__, so we must + # reset the traceback to reuse the exception. + # + # See https://bugs.python.org/issue45924 for an example of the problem. + raise _patch_exception.with_traceback(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. + """ + _maybe_raise_patch_exception() + + with _module_rlock: + 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. + """ + _maybe_raise_patch_exception() + + with _module_rlock: + 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] + + def write_with_callbacks(s: AnyStr, /) -> int: + n = orig_write(s) + + with contextlib.ExitStack() as stack: + stack.enter_context(_reset_on_exception()) + stack.enter_context(wb_logging.log_to_all_runs()) + callbacks_list = stack.enter_context(_enter_callbacks(callbacks)) + + for cb in callbacks_list: + cb(s, n) + + 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 + + +@contextlib.contextmanager +def _enter_callbacks( + callbacks: dict[int, _WriteCallback], +) -> Iterator[list[_WriteCallback]]: + """Returns a list of callbacks to invoke. + + This prevents deadlocks and some infinite loops by returning an empty list + when: + + * A callback prints + * A callback blocks on a thread that's printing + * A callback schedules an async task that prints + + It is impossible to prevent all infinite loops: a callback could put + a message into a queue, causing an unrelated thread to print later, + invoking the same callback and repeating forever. + """ + global _is_writing + + # NOTE 1: _is_writing + # + # The global _is_writing variable is necessary despite the contextvar + # because it's possible to create a thread without copying the context. + # This is the default behavior for threading.Thread() before Python 3.14. + # + # A side effect of it is that when multiple threads print simultaneously, + # some messages will not be captured. + # + # NOTE 2: _module_rlock + # + # We use a reentrant lock primarily because GC can trigger on the current + # thread at any time. Since GC can run arbitrary code via `__del__`, it may + # print and hit this lock while it's already held. + # + # Technically, even the simple methods called while holding the lock + # could be patched to print, but a reentrant lock just turns this + # deadlock into an infinite loop. + # + # Text printed during GC may or may not be captured. + # Assuming that the GC thread cannot itself be stolen, GC does not thwart + # the infinite loop protections: + # + # * If _is_writing == True, GC will not print or touch _is_writing + # * If _is_writing == False, GC will set it to True and reset it to + # False before giving back the thread + # + # Specifically, there is no situation where _is_writing "spontaneously" + # changes from True to False. + + with _module_rlock: + if _is_writing or _is_caused_by_callback.get(): + callbacks_list = None + + else: + callbacks_list = list(callbacks.values()) + _is_writing = True + _is_caused_by_callback.set(True) + + if callbacks_list is None: + yield [] + return + + try: + yield callbacks_list + finally: + with _module_rlock: + _is_writing = False + _is_caused_by_callback.set(False) + + +@contextlib.contextmanager +def _reset_on_exception() -> Iterator[None]: + """Clear all callbacks on any exception, suppressing it. + + This prevents 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. + """ + try: + yield + except BaseException as e: + with _module_rlock: + _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 + + +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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/credentials.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/credentials.py new file mode 100644 index 0000000000000000000000000000000000000000..03e01a866feb401042de739818b743c6dad98bd4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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 + +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. + """ + import requests + + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/deprecation.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/deprecation.py new file mode 100644 index 0000000000000000000000000000000000000000..85e64c9d65d0e9be0c65ae6a9802597e0772a525 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/deprecation.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, TypeAlias + +import wandb +from wandb.sdk.lib import telemetry + +if TYPE_CHECKING: + from wandb.proto.wandb_telemetry_pb2 import Deprecated + + +UNSET: DoNotSet = object() +"""A temporary default value for removing formerly optional parameters. + +This helps distinguish explicit None arguments from implicit None. + +Usage: + def myfunction(old_param: DoNotSet = UNSET) -> ...: + if old_param is not UNSET: + warn_user() + else: + # Set to None if checked in downstream logic, + # since UNSET is not None. + old_param = None + ... + + myfunction() # Does not warn + myfunction(old_param=None) # Warns +""" + +DoNotSet: TypeAlias = object +"""The type of UNSET.""" + + +def warn_and_record_deprecation( + *, + feature: Deprecated, + message: str, + run: wandb.Run | None = None, +) -> None: + """Warn the user that a feature has been deprecated and update telemetry. + + Args: + feature: A Deprecated protobuf message with the relevant field set to True. + message: The deprecation warning message to display to the user. + run: The run whose telemetry to update. + """ + with telemetry.context(run=run or wandb.run) as tel: + tel.deprecated.MergeFrom(feature) + + wandb.termwarn(message, repeat=False) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/disabled.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/disabled.py new file mode 100644 index 0000000000000000000000000000000000000000..34e0e82e12770c7f1071f8726eeb1c31b8b66ce2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/disabled.py @@ -0,0 +1,30 @@ +from typing import Any + + +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: + from wandb.proto.wandb_telemetry_pb2 import Deprecated + from wandb.sdk.lib.deprecation import warn_and_record_deprecation + + warn_and_record_deprecation( + feature=Deprecated(run_disabled=True), + message="RunDisabled is deprecated and is a no-op. " + '`wandb.init(mode="disabled")` now returns an instance of `wandb.Run`.', + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/exit_hooks.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/exit_hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..4a4705dc56ae02d8ad18c22d520ca143491c51bf --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/exit_hooks.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +import sys +import traceback +from types import TracebackType +from typing import TYPE_CHECKING + +import wandb +from wandb.errors import Error + +if TYPE_CHECKING: + from typing import NoReturn + + +class ExitHooks: + exception: BaseException | None = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/file_stream_utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/file_stream_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..473df5d1ac2c9658902e3f1f6af9e4c95ae41984 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/file_stream_utils.py @@ -0,0 +1,120 @@ +# + +from collections.abc import Iterable +from typing import Any + + +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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/filenames.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/filenames.py new file mode 100644 index 0000000000000000000000000000000000000000..ef53cfcd65acfdefdfc04506ec496e080450e5d0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/filenames.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +import os +from collections.abc import Callable, Generator + +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 in ( + METADATA_FNAME, + CONFIG_FNAME, + REQUIREMENTS_FNAME, + OUTPUT_FNAME, + DIFF_FNAME, + CONDA_ENVIRONMENTS_FNAME, + ) or name.startswith("wandb") + + +def filtered_dir( + root: str, + include_fn: Callable[[str, str], bool] | Callable[[str], bool], + exclude_fn: 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/filesystem.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/filesystem.py new file mode 100644 index 0000000000000000000000000000000000000000..99381fd1b8a14fd5d5817372cd2001cffc4cdd73 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/filesystem.py @@ -0,0 +1,569 @@ +from __future__ import annotations + +import contextlib +import ctypes +import dataclasses +import errno +import logging +import os +import platform +import re +import shutil +import tempfile +import threading +from collections.abc import Generator, Iterable +from pathlib import Path, PurePath +from typing import IO, Any, BinaryIO, Literal, NewType, TypedDict + +from wandb.sdk.lib.paths import StrPath +from wandb.sdk.wandb_settings import Settings + +GlobStr = NewType("GlobStr", str) + +logger = logging.getLogger(__name__) + +PolicyName = Literal["now", "live", "end"] + +# https://en.wikipedia.org/wiki/Filename#Comparison_of_filename_limitations +PROBLEMATIC_PATH_CHARS = "".join(chr(i) for i in range(32)) + ':"*<>?|' + + +class FilesDict(TypedDict): + files: Iterable[tuple[GlobStr, PolicyName]] + + +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) -> StrPath | None: + """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 + + +@dataclasses.dataclass +class LinkStats: + """Tracks statistics about file linking operations.""" + + n_symlink: int = 0 + n_hardlink: int = 0 + n_copy: int = 0 + n_copy_downgraded: int = 0 + + def record( + self, + mode: Literal["symlink", "hardlink", "copy"], + downgraded: bool = False, + ) -> None: + """Record a file operation. + + Args: + mode: Type of operation - "symlink", "hardlink", or "copy". + downgraded: Whether policy was downgraded from "live" to "now". + """ + if mode == "symlink": + self.n_symlink += 1 + elif mode == "hardlink": + self.n_hardlink += 1 + elif mode == "copy": + self.n_copy += 1 + if downgraded: + self.n_copy_downgraded += 1 + + def emit_warnings(self) -> None: + """Emit appropriate warnings based on recorded operations.""" + from wandb import termwarn + + if self.n_symlink: + termwarn( + f"Symlinked {self.n_symlink} file{'s' if self.n_symlink > 1 else ''} " + "into the W&B run directory; call wandb.save again to sync new files." + ) + + if self.n_hardlink: + termwarn( + f"Linked {self.n_hardlink} file{'s' if self.n_hardlink > 1 else ''} " + "into the W&B run directory (hardlinks); call wandb.save again to sync new files." + ) + + if self.n_copy: + if self.n_copy_downgraded: + termwarn( + f"Copied {self.n_copy} file{'s' if self.n_copy > 1 else ''} " + "(cross-volume or links unavailable). " + "Downgrading policy to 'now' for those files because live updates " + "won't propagate from the originals. Re-run wandb.save to resync, " + "or place your run directory on the same drive to enable hardlinks." + ) + else: + termwarn( + f"Copied {self.n_copy} file{'s' if self.n_copy > 1 else ''} " + "into the W&B run directory; call wandb.save again to sync new files." + ) + + +def validate_glob_path(glob_path: PurePath, base_path: PurePath) -> None: + """Validate that glob path is within base path. + + Args: + glob_path: The glob pattern path to validate. + base_path: The base path that should contain the glob. + + Raises: + ValueError: If validation fails. + """ + 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 and relative_glob.parts[0] == "*": + raise ValueError("Glob may not start with '*' relative to the base path") + + +def are_paths_on_same_drive(path1: Path, path2: Path) -> 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 = path1.resolve().drive + path2_drive = 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 + + +def unlink_path(path: Path) -> None: + """Best-effort removal of a pre-existing file/symlink/dir. + + Args: + path: Path to remove. + """ + with contextlib.suppress(FileNotFoundError): + if path.is_symlink() or path.is_file(): + path.unlink() + + +def link_or_copy( + settings: Settings, + src: Path, + dst: Path, +) -> Literal["symlink", "hardlink", "copy"]: + """Link or copy a file using the best available method. + + Tries strategies in order: symlink -> hardlink -> copy. + + Args: + src: Source file path (should be resolved/absolute). + dst: Destination file path. + allow_symlink: Whether to attempt symlinks before hardlinks. + + Returns: + The strategy that succeeded. + """ + if settings.symlink: + try: + dst.symlink_to(src, target_is_directory=src.is_dir()) + except (OSError, NotImplementedError): + pass + else: + return "symlink" + + if are_paths_on_same_drive(src, dst.parent): + try: + os.link(str(src), str(dst)) + except OSError: + pass + else: + return "hardlink" + + tmp = dst.with_name(dst.name + ".tmp~wandb") + shutil.copy2(str(src), str(tmp)) + os.replace(str(tmp), str(dst)) + return "copy" + + +def link_or_copy_with_policy( + settings: Settings, + src: Path, + dst: Path, + requested_policy: PolicyName, + stats: LinkStats, +) -> PolicyName: + """Link or copy a file using the best available method. + + Tries strategies in order: symlink -> hardlink -> copy. + Updates stats and returns the effective policy. + + Args: + settings: wandb settings object with symlink preference. + src: Source file path. + dst: Destination file path. + requested_policy: Requested upload policy ("live", "now", or "end"). + stats: Stats object to update with operation type. + + Returns: + Effective policy after any necessary downgrade. + """ + mode = link_or_copy(settings, src, dst) + + effective_policy = requested_policy + downgraded = False + if mode == "copy" and requested_policy == "live": + downgraded = True + effective_policy = "now" + + stats.record(mode, downgraded=downgraded) + return effective_policy diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/fsm.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/fsm.py new file mode 100644 index 0000000000000000000000000000000000000000..0605ee72d09a4404dead4d4a68c1c3db9a119e33 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/fsm.py @@ -0,0 +1,168 @@ +#!/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 __future__ import annotations + +from abc import abstractmethod +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from typing import Generic, TypeAlias + +from typing_extensions import Protocol, 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 = ( + 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: Callable[[T_FsmInputs], None] | 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: Callable[[T_FsmInputs], None] | 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/gitlib.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/gitlib.py new file mode 100644 index 0000000000000000000000000000000000000000..4145fcdc11ffb67e6cb80a408ef43820c2c1d877 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/gitlib.py @@ -0,0 +1,244 @@ +from __future__ import annotations + +import configparser +import logging +import os +from typing import TYPE_CHECKING, Any +from urllib.parse import urlparse, urlunparse + +import wandb + +try: + from git import ( # type: ignore + GitCommandError, + InvalidGitRepositoryError, + NoSuchPathError, + Repo, + ) +except ImportError: + pass + +if TYPE_CHECKING: + from git import Repo + + +logger = logging.getLogger(__name__) + + +class GitRepo: + def __init__( + self, + root: str | None = None, + remote: str = "origin", + lazy: bool = True, + remote_url: str | None = None, + commit: str | None = 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) -> Repo | None: + self._repo_initialized = True + try: + from git import Repo + except ImportError: + 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) -> Repo | None: + 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) -> bool | None: + 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) -> str | None: + 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: str | None) -> 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/gql_request.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/gql_request.py new file mode 100644 index 0000000000000000000000000000000000000000..b2f436e33b37be2741b88418d6eafc9ebeda0819 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/gql_request.py @@ -0,0 +1,78 @@ +"""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 collections.abc import Callable +from typing import Any + +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) + """ + import requests + + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/handler_util.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/handler_util.py new file mode 100644 index 0000000000000000000000000000000000000000..b4efd8d571baebab80f9a7702efdd962f0c9028d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/hashutil.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/hashutil.py new file mode 100644 index 0000000000000000000000000000000000000000..23292e015a2657a5826ccd71aa2376ee35174b87 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/hashutil.py @@ -0,0 +1,98 @@ +from __future__ import annotations + +import base64 +import hashlib +import logging +import mmap +import time +from typing import TYPE_CHECKING, 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 +# +ETag: TypeAlias = str +HexMD5: TypeAlias = str +B64MD5: TypeAlias = str + + +def _md5(data: bytes = b"") -> _hashlib.HASH: + """Allow FIPS-compliant md5 hash when supported.""" + return hashlib.md5(data, usedforsecurity=False) + + +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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/import_hooks.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/import_hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab72bf8ecb663d4bf322cb7cfce0133d5ef6470 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/import_hooks.py @@ -0,0 +1,276 @@ +"""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). +""" + +from __future__ import annotations + +import sys +import threading +from collections.abc import Callable +from importlib.util import find_spec +from typing import Any + +# 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: 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: str | None) -> 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: str | None = None, + ) -> _ImportHookChainedLoader | None: + # 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: str | None = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/interrupt.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/interrupt.py new file mode 100644 index 0000000000000000000000000000000000000000..19cc0fe914674d1a328b278024c03efef8b61ad9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/ipython.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/ipython.py new file mode 100644 index 0000000000000000000000000000000000000000..2c5cbf6d2c3ca70c74e7db179687fe2157daf684 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/ipython.py @@ -0,0 +1,142 @@ +from __future__ import annotations + +import logging +import sys +import warnings +from typing import Literal + +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" + + +def in_vscode_notebook() -> bool: + """Returns True if we're in a VSCode notebook.""" + try: + from IPython import get_ipython + except ModuleNotFoundError: + return False + + ipython = get_ipython() + if not ipython: + return False + + return ipython.kernel.shell.user_ns.get("__vsc_ipynb_file__") is not None + + +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) -> ProgressWidget | None: + """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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/json_util.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/json_util.py new file mode 100644 index 0000000000000000000000000000000000000000..aa3c8b3cf6718c87e6a37a671e205272b383dc28 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/json_util.py @@ -0,0 +1,54 @@ +"""JSON helpers backed by pydantic-core, with stdlib fallback. + +The wrapper mirrors the stdlib `json` surface (`dumps`/`dump`/`loads`/`load`) +and routes the hot path through `pydantic_core` for speed. Anything pydantic +cannot do — unrecognized kwargs, unserializable objects without a fallback, +etc. — is caught and re-tried with the stdlib so semantics stay aligned. +""" + +from __future__ import annotations + +import json +import logging +from typing import Any + +import pydantic_core + +logger = logging.getLogger(__name__) + + +def dumps(obj: Any, **kwargs: Any) -> str: + """Serialize `obj` to a JSON string.""" + try: + cls = kwargs.get("cls") + fallback = kwargs.get("default") or (cls and cls().default) + return pydantic_core.to_json( + obj, + indent=kwargs.get("indent"), + inf_nan_mode="constants", + fallback=fallback, + ).decode() + except Exception: + logger.exception("pydantic_core.to_json failed; using stdlib json") + return json.dumps(obj, **kwargs) + + +def dump(obj: Any, fp: Any, **kwargs: Any) -> None: + """Serialize `obj` as JSON and write the result to `fp`.""" + fp.write(dumps(obj, **kwargs)) + + +def loads(s: str | bytes | bytearray, **kwargs: Any) -> Any: + """Deserialize a JSON string to a Python object.""" + if kwargs: + return json.loads(s, **kwargs) + try: + return pydantic_core.from_json(s) + except Exception: + logger.exception("pydantic_core.from_json failed; using stdlib json") + return json.loads(s) + + +def load(fp: Any, **kwargs: Any) -> Any: + """Read JSON from `fp` and return the deserialized object.""" + return loads(fp.read(), **kwargs) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/lazyloader.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/lazyloader.py new file mode 100644 index 0000000000000000000000000000000000000000..0c7aec3f94ac6bab37154c3fb796ac0ac63ba9a4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/logger_capture.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/logger_capture.py new file mode 100644 index 0000000000000000000000000000000000000000..21ceb04db959c484dc002f93cfa0169832591372 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/logger_capture.py @@ -0,0 +1,27 @@ +from __future__ import annotations + +import logging + +from typing_extensions import override + +import wandb + + +class LoggerHandler(logging.Handler): + """A logging.Handler that forwards log records using `run.write_logs()`.""" + + def __init__( + self, + run: wandb.Run, + level: int | str = logging.NOTSET, + ) -> None: + super().__init__(level=level) + self._run = run + self.setFormatter(logging.Formatter("%(levelname)s:%(name)s:%(message)s")) + + @override + def emit(self, record: logging.LogRecord) -> None: + try: + self._run.write_logs(self.format(record)) + except Exception: + self.handleError(record) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/module.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/module.py new file mode 100644 index 0000000000000000000000000000000000000000..74516737c87aa2f7f09678e085c3817015156f84 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/paths.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/paths.py new file mode 100644 index 0000000000000000000000000000000000000000..bffcbf177759d180b9169c5b37086b8251afefdf --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/paths.py @@ -0,0 +1,106 @@ +from __future__ import annotations + +import os +import platform +from functools import wraps +from pathlib import PurePath, PurePosixPath +from typing import Any, TypeAlias, Union + +# 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/preinit.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/preinit.py new file mode 100644 index 0000000000000000000000000000000000000000..d03cfd3cc8ebd29e5710cecfde09a328df4a762d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/preinit.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +from collections.abc import Callable +from typing import Any + +import wandb + + +class PreInitObject: + def __init__(self, name: str, destination: Any | None = 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: Any | None = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/printer.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/printer.py new file mode 100644 index 0000000000000000000000000000000000000000..f68fd867702809cddce3b814006a1cacc5602379 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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 collections.abc 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'
{}
{grid}
' + if title: + return f"

{title}


{grid}
" + return f"{_JUPYTER_TABLE_STYLES}{grid}
" + + @override + def panel(self, columns: list[str]) -> str: + row = "".join([f'
{col}
' 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/printer_asyncio.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/printer_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..49f7593c3d358053a4d8037e84ee94ab4b35fabe --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/printer_asyncio.py @@ -0,0 +1,45 @@ +import asyncio +from collections.abc import Callable +from typing import 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: + async def update_spinner() -> None: + tick = 0 + with spinner_printer.dynamic_text() as text_area: + if not text_area: + spinner_printer.display(text) + return + + while True: + spinner = spinner_printer.loading_symbol(tick) + text_area.set_text(f"{spinner} {text}") + tick += 1 + await asyncio.sleep(0.1) + + async with asyncio_compat.cancel_on_exit(update_spinner()): + return await asyncio.get_running_loop().run_in_executor(None, func) + + asyncer = wandb_setup.singleton().asyncer + return asyncer.run(loop_run_with_spinner) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/progress.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/progress.py new file mode 100644 index 0000000000000000000000000000000000000000..ccc791895951124e8663c893ff4cf19de48bfd38 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/progress.py @@ -0,0 +1,359 @@ +"""Defines an object for printing run progress at the end of a script.""" + +from __future__ import annotations + +import asyncio +import contextlib +import time +from collections.abc import Iterator +from typing import 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 + +_INDENT = " " +_MAX_LINES_TO_PRINT = 6 +_MAX_OPS_TO_PRINT = 5 + + +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 = -1 + self._last_printed_line = "" + + def update( + self, + stats_or_list: pb.OperationStats | list[pb.OperationStats], + ) -> None: + """Update the displayed information. + + Args: + stats_or_list: A single group of operations, or zero or more + labeled operation groups. + """ + self._tick += 1 + + if not self._progress_text_area: + line = self._to_static_text(stats_or_list) + if line and line != self._last_printed_line: + self._printer.display(line) + self._last_printed_line = line + return + + lines = self._to_dynamic_text(stats_or_list) + if not lines: + loading_symbol = self._printer.loading_symbol(self._tick) + if loading_symbol: + lines = [f"{loading_symbol} {self._default_text}"] + else: + lines = [self._default_text] + + self._progress_text_area.set_text("\n".join(lines)) + + def _to_dynamic_text( + self, + stats_or_list: pb.OperationStats | list[pb.OperationStats], + ) -> list[str]: + """Returns text to show in a dynamic text area.""" + loading_symbol = self._printer.loading_symbol(self._tick) + + if isinstance(stats_or_list, list): + return _GroupedOperationStatsPrinter( + self._printer, + _MAX_LINES_TO_PRINT, + loading_symbol, + ).render(stats_or_list) + + else: + return _OperationStatsPrinter( + self._printer, + _MAX_LINES_TO_PRINT, + loading_symbol, + ).render(stats_or_list) + + def _to_static_text( + self, + stats_or_list: pb.OperationStats | list[pb.OperationStats], + ) -> str: + """Returns a single line of text to print out.""" + if isinstance(stats_or_list, list): + sorted_prefixed_stats = list( + (f"[{stats.label}] " if stats.label else "", stats) + for stats in sorted(stats_or_list, key=lambda s: s.label) + ) + else: + sorted_prefixed_stats = [("", stats_or_list)] + + group_strs: list[str] = [] + total_operations = 0 + total_printed = 0 + + for prefix, stats in sorted_prefixed_stats: + total_operations += stats.total_operations + if not stats.operations: + continue + + group_ops: list[str] = [] + i = 0 + while total_printed < _MAX_OPS_TO_PRINT and i < len(stats.operations): + group_ops.append(stats.operations[i].desc) + total_printed += 1 + i += 1 + + if group_ops: + group_strs.append(prefix + "; ".join(group_ops)) + + line = "; ".join(group_strs) + remaining = total_operations - total_printed + if total_printed > 0 and remaining > 0: + line += f" (+ {remaining} more)" + + return line + + +class _GroupedOperationStatsPrinter: + """Renders a list of labeled operation stats groups into lines of text.""" + + def __init__( + self, + printer: p.Printer, + max_lines: int, + loading_symbol: str, + ) -> None: + self._printer = printer + self._max_lines = max_lines + self._loading_symbol = loading_symbol + + def render(self, stats_list: list[pb.OperationStats]) -> list[str]: + """Convert labeled operation stats groups into text to display. + + Args: + stats_list: A list of labeled operation stats. + + Returns: + The lines of text to print. The lines do not end with the newline + character. Returns an empty list if there are no operations. + """ + lines: list[str] = [] + + for stats in sorted(stats_list, key=lambda s: s.label): + # Don't display empty groups. + if not stats.operations: + continue + + if stats.label: + remaining_non_header_lines = self._max_lines - len(lines) - 1 + indent = _INDENT + else: + remaining_non_header_lines = self._max_lines - len(lines) + indent = "" + + # Ensure enough space left for at least one line of content + # after the header. + if remaining_non_header_lines < 1: + break + + # Group header (if not empty). + if stats.label: + lines.append(stats.label) + + # Group content. + stats_lines = _OperationStatsPrinter( + printer=self._printer, + max_lines=remaining_non_header_lines, + loading_symbol=self._loading_symbol, + ).render(stats) + for line in stats_lines: + lines.append(f"{indent}{line}") + + return lines + + +class _OperationStatsPrinter: + """Renders operation stats into lines of text.""" + + def __init__( + self, + printer: p.Printer, + max_lines: int, + loading_symbol: str, + ) -> None: + self._printer = printer + self._max_lines = max_lines + self._loading_symbol = loading_symbol + + self._lines: list[str] = [] + self._ops_shown = 0 + + def render(self, stats: pb.OperationStats) -> list[str]: + """Convert the stats into a list of lines to display. + + Args: + stats: Collection of operations to display. + + Returns: + The lines of text to print. The lines do not end with the newline + character. Returns an empty list if there are no operations. + """ + for op in stats.operations: + self._add_operation(op, is_subtask=False, indent="") + + if self._ops_shown < stats.total_operations: + if 1 <= self._max_lines <= len(self._lines): + self._ops_shown -= 1 + self._lines.pop() + + remaining = stats.total_operations - self._ops_shown + + self._lines.append(f"+ {remaining} more task(s)") + + return 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 + + status_indent_level = 0 # alignment for the status message, if any + parts: list[str] = [] + + # Subtask indicator. + if is_subtask and self._printer.supports_unicode: + status_indent_level += 2 # +1 for space + parts.append("↳") + + # Loading symbol. + if self._loading_symbol: + status_indent_level += 2 # +1 for space + 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) + status_indent = " " * status_indent_level + self._lines.append( + f"{indent}{status_indent}{error_word} {error_desc}", + ) + + # Subtasks. + if op.subtasks: + subtask_indent = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/proto_util.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/proto_util.py new file mode 100644 index 0000000000000000000000000000000000000000..0ca71ace8f0fe1e7ec654d483e9110ac0ba8f347 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/proto_util.py @@ -0,0 +1,92 @@ +# +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any + +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: 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/redirect.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/redirect.py new file mode 100644 index 0000000000000000000000000000000000000000..cc4df6ee4e61eec8a622301f7fc86b89be05f3ee --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/redirect.py @@ -0,0 +1,874 @@ +from __future__ import annotations + +try: + import fcntl + import pty + import termios + import tty +except ImportError: # windows + pty = tty = termios = fcntl = None # type: ignore + +import itertools +import logging +import os +import queue +import re +import signal +import struct +import sys +import threading +import time +from collections import defaultdict +from collections.abc import Callable, Iterable +from typing import Literal + +import wandb +from wandb.sdk.lib import console_capture + + +class _Numpy: # fallback in case numpy is not available + def where(self, x): + return ([i for i in range(len(x)) if x[i]],) + + def diff(self, x): + return [x[i + 1] - x[i] for i in range(len(x) - 1)] + + def arange(self, x): + class Arr(list): + def __getitem__(self, s): + if isinstance(s, slice): + self._start = s.start + return self + return super().__getitem__(s) + + def __getslice__(self, i, j): + self._start = i + return self + + def __iadd__(self, i): # type: ignore + for j in range(self._start, len(self)): + self[j] += i + + return Arr(range(x)) + + +try: + import numpy as np # type: ignore +except ImportError: + np = _Numpy() # type: ignore + + +logger = logging.getLogger("wandb") + + +ANSI_CSI_RE = re.compile("\001?\033\\[((?:\\d|;)*)([a-zA-Z])\002?") +ANSI_OSC_RE = re.compile("\001?\033\\]([^\a]*)(\a)\002?") + +_LAST_WRITE_TOKEN = b"L@stWr!t3T0k3n" + +SEP_RE = re.compile( + "\r|\n|" + # Unprintable ascii characters: + + "|".join([chr(i) for i in range(2**8) if repr(chr(i)).startswith("'\\x")]) +) + +ANSI_FG = list(map(str, itertools.chain(range(30, 40), range(90, 98)))) +ANSI_BG = list(map(str, itertools.chain(range(40, 50), range(100, 108)))) + +ANSI_FG_DEFAULT = "39" +ANSI_BG_DEFAULT = "49" + +ANSI_RESET = "0" + +ANSI_STYLES = { + "1": "bold", + "2": "/bold", + "3": "italics", + "4": "underscore", + "5": "blink", + "7": "reverse", + "9": "strikethrough", + "22": "/bold", + "23": "/italics", + "24": "/underscore", + "25": "/blink", + "27": "/reverse", + "29": "/strikethrough", +} + +ANSI_STYLES_REV = {v: k for k, v in ANSI_STYLES.items()} + + +CSI = "\033[" + + +def _get_char(code): + return "\033[" + str(code) + "m" + + +class Char: + """Class encapsulating a single character, its foreground, background and style attributes.""" + + __slots__ = ( + "data", + "fg", + "bg", + "bold", + "italics", + "underscore", + "blink", + "strikethrough", + "reverse", + ) + + def __init__( + self, + data=" ", + fg=ANSI_FG_DEFAULT, + bg=ANSI_BG_DEFAULT, + bold=False, + italics=False, + underscore=False, + blink=False, + strikethrough=False, + reverse=False, + ): + self.data = data + self.fg = fg + self.bg = bg + self.bold = bold + self.italics = italics + self.underscore = underscore + self.blink = blink + self.strikethrough = strikethrough + self.reverse = reverse + + def reset(self): + # Reset everything other than data to defaults + default = self.__class__() + for k in self.__slots__[1:]: + self[k] = default[k] + + def __getitem__(self, k): + return getattr(self, k) + + def __setitem__(self, k, v): + setattr(self, k, v) + + def copy(self, **kwargs): + attrs = {} + for k in self.__slots__: + if k in kwargs: + attrs[k] = kwargs[k] + else: + attrs[k] = self[k] + return self.__class__(**attrs) + + def __eq__(self, other): + return all(self[k] == other[k] for k in self.__slots__) + + +_defchar = Char() + + +class Cursor: + """A 2D cursor. + + Attributes: + x: x-coordinate. + y: y-coordinate. + char: the character to inherit colors and styles from. + """ + + __slots__ = ("x", "y", "char") + + def __init__(self, x=0, y=0, char=None): + if char is None: + char = Char() + self.x = x + self.y = y + self.char = char + + +class TerminalEmulator: + """An FSM emulating a terminal. + + Characters are stored in a 2D matrix (buffer) indexed by the cursor. + """ + + _MAX_LINES = 100 + + def __init__(self): + self.buffer = defaultdict(lambda: defaultdict(lambda: _defchar)) + self.cursor = Cursor() + self._num_lines = None # Cache + + # For diffing: + self._prev_num_lines = None + self._prev_last_line = None + + def cursor_up(self, n=1): + n = min(n, self.cursor.y) + self.cursor.y -= n + + def cursor_down(self, n=1): + self.cursor.y += n + + def cursor_left(self, n=1): + n = min(n, self.cursor.x) + self.cursor.x -= n + + def cursor_right(self, n=1): + self.cursor.x += n + + def carriage_return(self): + self.cursor.x = 0 + + def cursor_position(self, line, column): + self.cursor.x = min(column, 1) - 1 + self.cursor.y = min(line, 1) - 1 + + def cursor_column(self, column): + self.cursor.x = min(column, 1) - 1 + + def cursor_line(self, line): + self.cursor.y = min(line, 1) - 1 + + def linefeed(self): + self.cursor_down() + self.carriage_return() + + def _get_line_len(self, n): + if n not in self.buffer: + return 0 + line = self.buffer[n] + if not line: + return 0 + n = max(line.keys()) + for i in range(n, -1, -1): + if line[i] != _defchar: + return i + 1 + return 0 + + @property + def num_lines(self): + if self._num_lines is not None: + return self._num_lines + ret = 0 + if self.buffer: + n = max(self.buffer.keys()) + for i in range(n, -1, -1): + if self._get_line_len(i): + ret = i + 1 + break + self._num_lines = ret + return ret + + def display(self): + return [ + [self.buffer[i][j].data for j in range(self._get_line_len(i))] + for i in range(self.num_lines) + ] + + def erase_screen(self, mode=0): + if mode == 0: + for i in range(self.cursor.y + 1, self.num_lines): + if i in self.buffer: + del self.buffer[i] + self.erase_line(mode) + if mode == 1: + for i in range(self.cursor.y): + if i in self.buffer: + del self.buffer[i] + self.erase_line(mode) + elif mode == 2 or mode == 3: + self.buffer.clear() + + def erase_line(self, mode=0): + curr_line = self.buffer[self.cursor.y] + if mode == 0: + for i in range(self.cursor.x, self._get_line_len(self.cursor.y)): + if i in curr_line: + del curr_line[i] + elif mode == 1: + for i in range(self.cursor.x + 1): + if i in curr_line: + del curr_line[i] + else: + curr_line.clear() + + def insert_lines(self, n=1): + for i in range(self.num_lines - 1, self.cursor.y, -1): + self.buffer[i + n] = self.buffer[i] + for i in range(self.cursor.y + 1, self.cursor.y + 1 + n): + if i in self.buffer: + del self.buffer[i] + + def _write_plain_text(self, plain_text): + self.buffer[self.cursor.y].update( + [ + (self.cursor.x + i, self.cursor.char.copy(data=c)) + for i, c in enumerate(plain_text) + ] + ) + self.cursor.x += len(plain_text) + + def _write_text(self, text): + prev_end = 0 + for match in SEP_RE.finditer(text): + start, end = match.span() + self._write_plain_text(text[prev_end:start]) + prev_end = end + c = match.group() + if c == "\n": + self.linefeed() + elif c == "\r": + self.carriage_return() + elif c == "\b": + self.cursor_left() + else: + continue + self._write_plain_text(text[prev_end:]) + + def _remove_osc(self, text): + return re.sub(ANSI_OSC_RE, "", text) + + def write(self, data): + self._num_lines = None # invalidate cache + data = self._remove_osc(data) + prev_end = 0 + for match in ANSI_CSI_RE.finditer(data): + start, end = match.span() + text = data[prev_end:start] + csi = data[start:end] + prev_end = end + self._write_text(text) + self._handle_csi(csi, *match.groups()) + self._write_text(data[prev_end:]) + + def _handle_csi(self, csi, params, command): + try: + if command == "m": + p = params.split(";")[0] + if not p: + p = "0" + if p in ANSI_FG: + self.cursor.char.fg = p + elif p in ANSI_BG: + self.cursor.char.bg = p + elif p == ANSI_RESET: + self.cursor.char.reset() + elif p in ANSI_STYLES: + style = ANSI_STYLES[p] + off = style.startswith("/") + if off: + style = style[1:] + self.cursor.char[style] = not off + else: + abcd = { + "A": "cursor_up", + "B": "cursor_down", + "C": "cursor_right", + "D": "cursor_left", + } + cursor_fn = abcd.get(command) + if cursor_fn: + getattr(self, cursor_fn)(int(params) if params else 1) + elif command == "J": + p = params.split(";")[0] + p = int(p) if p else 0 + self.erase_screen(p) + elif command == "K": + p = params.split(";")[0] + p = int(p) if p else 0 + self.erase_line(p) + elif command == "L": + p = int(params) if params else 1 + self.insert_lines(p) + elif command in "Hf": + p = params.split(";") + if len(p) == 2: + p = (int(p[0]), int(p[1])) + elif len(p) == 1: + p = (int(p[0]), 1) + else: + p = (1, 1) + self.cursor_position(*p) + except Exception: + pass + + def _get_line(self, n): + line = self.buffer[n] + line_len = self._get_line_len(n) + # We have to loop through each character in the line and check if foreground, + # background and other attributes (italics, bold, underline, etc) of the ith + # character are different from those of the (i-1)th character. If different, the + # appropriate ascii character for switching the color/attribute should be + # appended to the output string before appending the actual character. This loop + # and subsequent checks can be expensive, especially because 99% of terminal + # output use default colors and formatting. Even in outputs that do contain + # colors and styles, its unlikely that they will change on a per character + # basis. + + # So instead we create a character list without any ascii codes (`out`), and a + # list of all the foregrounds in the line (`fgs`) on which we call np.diff() and + # np.where() to find the indices where the foreground change, and insert the + # ascii characters in the output list (`out`) on those indices. All of this is + # the done only if there are more than 1 foreground color in the line in the + # first place (`if len(set(fgs)) > 1 else None`). Same logic is repeated for + # background colors and other attributes. + + out = [line[i].data for i in range(line_len)] + + # for dynamic insert using original indices + idxs = np.arange(line_len) + insert = lambda i, c: (out.insert(idxs[i], c), idxs[i:].__iadd__(1)) # noqa + + fgs = [int(_defchar.fg)] + [int(line[i].fg) for i in range(line_len)] + [ + insert(i, _get_char(line[int(i)].fg)) for i in np.where(np.diff(fgs))[0] + ] if len(set(fgs)) > 1 else None + bgs = [int(_defchar.bg)] + [int(line[i].bg) for i in range(line_len)] + [ + insert(i, _get_char(line[int(i)].bg)) for i in np.where(np.diff(bgs))[0] + ] if len(set(bgs)) > 1 else None + attrs = { + k: [False] + [line[i][k] for i in range(line_len)] + for k in Char.__slots__[3:] + } + [ + [ + insert(i, _get_char(ANSI_STYLES_REV[k if line[int(i)][k] else "/" + k])) + for i in np.where(np.diff(v))[0] + ] + for k, v in attrs.items() + if any(v) + ] + return "".join(out) + + def read(self): + num_lines = self.num_lines + if self._prev_num_lines is None: + ret = os.linesep.join(map(self._get_line, range(num_lines))) + if ret: + ret += os.linesep + else: + return ret + else: + curr_line = self._get_line(self._prev_num_lines - 1) + if curr_line == self._prev_last_line: + if num_lines == self._prev_num_lines: + return "" + ret = ( + os.linesep.join( + map(self._get_line, range(self._prev_num_lines, num_lines)) + ) + + os.linesep + ) + else: + ret = ( + "\r" + + os.linesep.join( + map(self._get_line, range(self._prev_num_lines - 1, num_lines)) + ) + + os.linesep + ) + if num_lines > self._MAX_LINES: + shift = num_lines - self._MAX_LINES + for i in range(shift, num_lines): + self.buffer[i - shift] = self.buffer[i] + for i in range(self._MAX_LINES, max(self.buffer.keys())): + if i in self.buffer: + del self.buffer[i] + self.cursor.y -= min(self.cursor.y, shift) + self._num_lines = num_lines = self._MAX_LINES + self._prev_num_lines = num_lines + self._prev_last_line = self._get_line(num_lines - 1) + return ret + + +_MIN_CALLBACK_INTERVAL = 2 # seconds + + +class RedirectBase: + def __init__( + self, + src: Literal["stdout", "stderr"], + cbs: Iterable[Callable[[str], None]] = (), + ) -> None: + """# Arguments. + + `src`: Source stream to be redirected. "stdout" or "stderr". + `cbs`: tuple/list of callbacks. Each callback should take exactly 1 argument (bytes). + + """ + assert hasattr(sys, src) + self.src: Literal["stdout", "stderr"] = src + self.cbs = cbs + + @property + def src_stream(self): + return getattr(sys, f"__{self.src}__") + + @property + def src_fd(self): + return self.src_stream.fileno() + + @property + def src_wrapped_stream(self): + return getattr(sys, self.src) + + def install(self) -> None: + pass + + def uninstall(self) -> None: + pass + + +class StreamWrapper(RedirectBase): + """Patches the write method of current sys.stdout/sys.stderr.""" + + def __init__( + self, + src: Literal["stdout", "stderr"], + cbs: Iterable[Callable[[str], None]] = (), + *, + flush_periodically: bool, + ) -> None: + super().__init__(src=src, cbs=cbs) + self._uninstall: Callable[[], None] | None = None + self._emulator = TerminalEmulator() + self._queue: queue.Queue[str] = queue.Queue() + self._stopped = threading.Event() + self._flush_periodically = flush_periodically + + def _emulator_write(self) -> None: + while True: + if self._queue.empty(): + if self._stopped.is_set(): + return + time.sleep(0.5) + continue + + data: list[str] = [] + while not self._queue.empty(): + data.append(self._queue.get()) + + if self._stopped.is_set() and sum(map(len, data)) > 100000: + wandb.termlog("Terminal output too large. Logging without processing.") + self.flush() + + for line in data: + self.flush(line) + + return + + try: + self._emulator.write("".join(data)) + except Exception: + pass + + def _callback(self) -> None: + while not (self._stopped.is_set() and self._queue.empty()): + self.flush() + time.sleep(_MIN_CALLBACK_INTERVAL) + + def _on_write(self, data: str | bytes, written: int, /) -> None: + if isinstance(data, bytes): + written_data = data[:written].decode("utf-8") + else: + written_data = data[:written] + + self._queue.put(written_data) + + def install(self) -> None: + if self._uninstall: + return + + try: + if self.src == "stdout": + self._uninstall = console_capture.capture_stdout(self._on_write) + else: + self._uninstall = console_capture.capture_stderr(self._on_write) + except console_capture.CannotCaptureConsoleError: + logger.exception("failed to install %s hooks", self.src) + wandb.termwarn( + f"Failed to wrap {self.src}. Console logs will not be captured.", + ) + return + + self._emulator_write_thread = threading.Thread(target=self._emulator_write) + self._emulator_write_thread.daemon = True + self._emulator_write_thread.start() + + if self._flush_periodically: + self._callback_thread = threading.Thread(target=self._callback) + self._callback_thread.daemon = True + self._callback_thread.start() + + def flush(self, data: str | None = None) -> None: + if data is None: + try: + data = self._emulator.read().encode("utf-8") + except Exception: + logger.exception("exception reading TerminalEmulator") + + if data: + for cb in self.cbs: + try: + cb(data) + except Exception: + logger.exception("exception in StreamWrapper callback") + + def uninstall(self) -> None: + if not self._uninstall: + return + + self._uninstall() + + self._stopped.set() + self._emulator_write_thread.join(timeout=5) + if self._emulator_write_thread.is_alive(): + wandb.termlog(f"Processing terminal output ({self.src})...") + self._emulator_write_thread.join() + wandb.termlog("Done.") + self.flush() + + +class StreamRawWrapper(RedirectBase): + """Patches the write method of current sys.stdout/sys.stderr. + + Captures data in a raw form rather than using the emulator + """ + + def __init__( + self, + src: Literal["stdout", "stderr"], + cbs: Iterable[Callable[[str], None]] = (), + ) -> None: + super().__init__(src=src, cbs=cbs) + self._uninstall: Callable[[], None] | None = None + + def _on_write(self, data: str | bytes, written: int, /) -> None: + if isinstance(data, bytes): + written_data = data[:written].decode("utf-8") + else: + written_data = data[:written] + + for cb in self.cbs: + try: + cb(written_data) + except Exception: + logger.exception("error in %s callback", self.src) + + def install(self) -> None: + if self._uninstall: + return + + try: + if self.src == "stdout": + self._uninstall = console_capture.capture_stdout(self._on_write) + else: + self._uninstall = console_capture.capture_stderr(self._on_write) + except console_capture.CannotCaptureConsoleError: + logger.exception("failed to install %s hooks", self.src) + wandb.termwarn( + f"Failed to wrap {self.src}. Console logs will not be captured.", + ) + + def uninstall(self) -> None: + if self._uninstall: + self._uninstall() + + +class _WindowSizeChangeHandler: + def __init__(self): + self._fds = set() + + def _register(self): + old_handler = signal.signal(signal.SIGWINCH, lambda *_: None) + + def handler(signum, frame): + if callable(old_handler): + old_handler(signum, frame) + self.handle_window_size_change() + + signal.signal(signal.SIGWINCH, handler) + self._old_handler = old_handler + + def _unregister(self): + signal.signal(signal.SIGWINCH, self._old_handler) + + def add_fd(self, fd): + if not self._fds: + self._register() + self._fds.add(fd) + self.handle_window_size_change() + + def remove_fd(self, fd): + if fd in self._fds: + self._fds.remove(fd) + if not self._fds: + self._unregister() + + def handle_window_size_change(self): + try: + win_size = fcntl.ioctl(0, termios.TIOCGWINSZ, "\0" * 8) + rows, cols, xpix, ypix = struct.unpack("HHHH", win_size) + # Note: IOError not subclass of OSError in python 2.x + except OSError: # eg. in MPI we can't do this. + return + if cols == 0: + return + win_size = struct.pack("HHHH", rows, cols, xpix, ypix) + for fd in self._fds: + fcntl.ioctl(fd, termios.TIOCSWINSZ, win_size) + + +_WSCH = _WindowSizeChangeHandler() + +_redirects: dict[str, Redirect | None] = {"stdout": None, "stderr": None} + + +class Redirect(RedirectBase): + """Redirect low level file descriptors.""" + + def __init__(self, src, cbs=(), *, flush_periodically: bool): + super().__init__(src=src, cbs=cbs) + self._installed = False + self._emulator = TerminalEmulator() + self._flush_periodically = flush_periodically + + def _pipe(self): + if pty: + r, w = pty.openpty() + else: + r, w = os.pipe() + return r, w + + def install(self): + curr_redirect = _redirects.get(self.src) + if curr_redirect and curr_redirect != self: + curr_redirect.uninstall() + _redirects[self.src] = self + + if self._installed: + return + self._pipe_read_fd, self._pipe_write_fd = self._pipe() + if os.isatty(self._pipe_read_fd): + _WSCH.add_fd(self._pipe_read_fd) + self._orig_src_fd = os.dup(self.src_fd) + self._orig_src = os.fdopen(self._orig_src_fd, "wb", 0) + os.dup2(self._pipe_write_fd, self.src_fd) + self._installed = True + self._queue = queue.Queue() + self._stopped = threading.Event() + self._pipe_relay_thread = threading.Thread(target=self._pipe_relay) + self._pipe_relay_thread.daemon = True + self._pipe_relay_thread.start() + self._emulator_write_thread = threading.Thread(target=self._emulator_write) + self._emulator_write_thread.daemon = True + self._emulator_write_thread.start() + if self._flush_periodically: + self._callback_thread = threading.Thread(target=self._callback) + self._callback_thread.daemon = True + self._callback_thread.start() + + def uninstall(self): + if not self._installed: + return + self._installed = False + # If the user printed a very long string (millions of chars) right + # before run.finish(), it will take a while for it to reach pipe relay. + # 1 second is enough time for ~5 million chars. + time.sleep(1) + self._stopped.set() + os.dup2(self._orig_src_fd, self.src_fd) + os.write(self._pipe_write_fd, _LAST_WRITE_TOKEN) + self._pipe_relay_thread.join() + os.close(self._pipe_read_fd) + os.close(self._pipe_write_fd) + + t = threading.Thread( + target=self.src_wrapped_stream.flush + ) # Calling flush() from the current thread does not flush the buffer instantly. + t.start() + t.join(timeout=10) + + self._emulator_write_thread.join(timeout=5) + if self._emulator_write_thread.is_alive(): + wandb.termlog(f"Processing terminal output ({self.src})...") + self._emulator_write_thread.join() + wandb.termlog("Done.") + self.flush() + + _WSCH.remove_fd(self._pipe_read_fd) + + if _redirects[self.src] == self: + _redirects[self.src] = None + + def flush(self, data=None): + if data is None: + try: + data = self._emulator.read().encode("utf-8") + except Exception: + pass + if data: + for cb in self.cbs: + try: + cb(data) + except Exception: + pass # TODO(frz) + + def _callback(self): + while not self._stopped.is_set(): + self.flush() + time.sleep(_MIN_CALLBACK_INTERVAL) + + def _pipe_relay(self): + while True: + try: + brk = False + data = os.read(self._pipe_read_fd, 4096) + if self._stopped.is_set(): + if _LAST_WRITE_TOKEN not in data: + # _LAST_WRITE_TOKEN could have gotten split up at the 4096 border + n = len(_LAST_WRITE_TOKEN) + while n and data[-n:] != _LAST_WRITE_TOKEN[:n]: + n -= 1 + if n: + data += os.read( + self._pipe_read_fd, len(_LAST_WRITE_TOKEN) - n + ) + if _LAST_WRITE_TOKEN in data: + data = data.replace(_LAST_WRITE_TOKEN, b"") + brk = True + i = self._orig_src.write(data) + if i is not None: # python 3 w/ unbuffered i/o: we need to keep writing + while i < len(data): + i += self._orig_src.write(data[i:]) + self._queue.put(data) + if brk: + return + except OSError: + return + + def _emulator_write(self): + while True: + if self._queue.empty(): + if self._stopped.is_set(): + return + time.sleep(0.5) + continue + data = [] + while not self._queue.empty(): + data.append(self._queue.get()) + if self._stopped.is_set() and sum(map(len, data)) > 100000: + wandb.termlog("Terminal output too large. Logging without processing.") + self.flush() + [self.flush(line) for line in data] + return + try: + self._emulator.write(b"".join(data).decode("utf-8")) + except Exception: + pass diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/retry.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/retry.py new file mode 100644 index 0000000000000000000000000000000000000000..d8744abad350b182643903c742129eda7b816ecc --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/retry.py @@ -0,0 +1,399 @@ +from __future__ import annotations + +import abc +import asyncio +import datetime +import functools +import logging +import os +import random +import threading +import time +from collections.abc import Awaitable, Callable +from typing import Any, Generic, TypeVar + +import wandb +import wandb.errors +from wandb.util import CheckRetryFnType + +logger = logging.getLogger(__name__) + + +# To let tests mock out the retry logic's now()/sleep() funcs, this file +# should only use these variables, not call the stdlib funcs directly. +NOW_FN = datetime.datetime.now +SLEEP_FN = time.sleep +SLEEP_ASYNC_FN = asyncio.sleep + + +class RetryCancelledError(wandb.errors.Error): + """A retry did not occur because it was cancelled.""" + + +class TransientError(Exception): + """Exception type designated for errors that may only be temporary. + + Can have its own message and/or wrap another exception. + """ + + def __init__( + self, msg: str | None = None, exc: BaseException | None = None + ) -> None: + super().__init__(msg) + self.message = msg + self.exception = exc + + +_R = TypeVar("_R") + + +class Retry(Generic[_R]): + """Create a retryable version of a function. + + Calling this will call the passed function, retrying if any exceptions in + retryable_exceptions are caught, with exponential backoff. + """ + + MAX_SLEEP_SECONDS = 5 * 60 + + def __init__( + self, + call_fn: Callable[..., _R], + retry_timedelta: datetime.timedelta | None = None, + retry_cancel_event: threading.Event | None = None, + num_retries: int | None = None, + check_retry_fn: CheckRetryFnType = lambda e: True, + retryable_exceptions: tuple[type[Exception], ...] | None = None, + error_prefix: str = "Network error", + retry_callback: Callable[[int, str], Any] | None = None, + ) -> None: + self._call_fn = call_fn + self._check_retry_fn = check_retry_fn + self._error_prefix = error_prefix + self._last_print = datetime.datetime.now() - datetime.timedelta(minutes=1) + self._retry_timedelta = retry_timedelta + self._retry_cancel_event = retry_cancel_event + self._num_retries = num_retries + if retryable_exceptions is not None: + self._retryable_exceptions = retryable_exceptions + else: + self._retryable_exceptions = (TransientError,) + self.retry_callback = retry_callback + + self._num_iter = 0 + + def _sleep_check_cancelled( + self, wait_seconds: float, cancel_event: threading.Event | None + ) -> bool: + if not cancel_event: + SLEEP_FN(wait_seconds) + return False + cancelled = cancel_event.wait(wait_seconds) + return cancelled + + @property + def num_iters(self) -> int: + """The number of iterations the previous __call__ retried.""" + return self._num_iter + + def __call__( + self, + *args: Any, + num_retries: int | None = None, + retry_timedelta: datetime.timedelta | None = None, + retry_sleep_base: float | None = None, + retry_cancel_event: threading.Event | None = None, + check_retry_fn: CheckRetryFnType | None = None, + **kwargs: Any, + ) -> _R: + """Call the wrapped function, with retries. + + Args: + num_retries: The number of retries after which to give up. + retry_timedelta: An amount of time after which to give up. + retry_sleep_base: Number of seconds to sleep for the first retry. + This is used as the base for exponential backoff. + retry_cancel_event: An event that causes this to raise + a RetryCancelledException on the next attempted retry. + check_retry_fn: A custom check for deciding whether an exception + should be retried. Retrying is prevented if this returns a falsy + value, even if more retries are left. This may also return a + timedelta that represents a shorter timeout: retrying is + prevented if the value is less than the amount of time that has + passed since the last timedelta was returned. + """ + if os.environ.get("WANDB_TEST"): + max_retries = 0 + elif num_retries is not None: + max_retries = num_retries + elif self._num_retries is not None: + max_retries = self._num_retries + else: + max_retries = 1000000 + + if retry_timedelta is not None: + timeout = retry_timedelta + elif self._retry_timedelta is not None: + timeout = self._retry_timedelta + else: + timeout = datetime.timedelta(days=365) + + if retry_sleep_base is not None: + initial_sleep = retry_sleep_base + else: + initial_sleep = 1 + + retry_loop = _RetryLoop( + max_retries=max_retries, + timeout=timeout, + initial_sleep=initial_sleep, + max_sleep=self.MAX_SLEEP_SECONDS, + cancel_event=retry_cancel_event or self._retry_cancel_event, + retry_check=check_retry_fn or self._check_retry_fn, + ) + + start_time = NOW_FN() + self._num_iter = 0 + + while True: + try: + result = self._call_fn(*args, **kwargs) + + except self._retryable_exceptions as e: + if not retry_loop.should_retry(e): + raise + + if self._num_iter == 2: + logger.info("Retry attempt failed:", exc_info=e) + self._print_entered_retry_loop(e) + + retry_loop.wait_before_retry() + self._num_iter += 1 + + else: + if self._num_iter > 2: + self._print_recovered(start_time) + + return result + + def _print_entered_retry_loop(self, exception: Exception) -> None: + """Emit a message saying we've begun retrying. + + Either calls the retry callback or prints a warning to console. + + Args: + exception: The most recent exception we will retry. + """ + from requests import HTTPError + + if ( + isinstance(exception, HTTPError) + and exception.response is not None + and self.retry_callback is not None + ): + self.retry_callback( + exception.response.status_code, + exception.response.text, + ) + else: + wandb.termlog( + f"{self._error_prefix}" + + f" ({exception.__class__.__name__}), entering retry loop." + ) + + def _print_recovered(self, start_time: datetime.datetime) -> None: + """Emit a message saying we've recovered after retrying. + + Args: + start_time: When we started retrying. + """ + if not self.retry_callback: + return + + now = NOW_FN() + if now - self._last_print < datetime.timedelta(minutes=1): + return + self._last_print = now + + time_to_recover = now - start_time + self.retry_callback( + 200, + ( + f"{self._error_prefix} resolved after" + f" {time_to_recover}, resuming normal operation." + ), + ) + + +class _RetryLoop: + """An invocation of a Retry instance.""" + + def __init__( + self, + *, + max_retries: int, + timeout: datetime.timedelta, + initial_sleep: float, + max_sleep: float, + cancel_event: threading.Event | None, + retry_check: CheckRetryFnType, + ) -> None: + """Start a new call of a Retry instance. + + Args: + max_retries: The number of retries after which to give up. + timeout: An amount of time after which to give up. + initial_sleep: Number of seconds to sleep for the first retry. + This is used as the base for exponential backoff. + max_sleep: Maximum number of seconds to sleep between retries. + cancel_event: An event that's set when the function is cancelled. + retry_check: A custom check for deciding whether an exception should + be retried. Retrying is prevented if this returns a falsy value, + even if more retries are left. This may also return a timedelta + that represents a shorter timeout: retrying is prevented if the + value is less than the amount of time that has passed since the + last timedelta was returned. + """ + self._max_retries = max_retries + self._total_retries = 0 + + self._timeout = timeout + self._start_time = NOW_FN() + + self._next_sleep_time = initial_sleep + self._max_sleep = max_sleep + self._cancel_event = cancel_event + + self._retry_check = retry_check + self._last_custom_timeout: datetime.datetime | None = None + + def should_retry(self, exception: Exception) -> bool: + """Returns whether an exception should be retried.""" + if self._total_retries >= self._max_retries: + return False + self._total_retries += 1 + + now = NOW_FN() + if now - self._start_time >= self._timeout: + return False + + retry_check_result = self._retry_check(exception) + if not retry_check_result: + return False + + if isinstance(retry_check_result, datetime.timedelta): + if not self._last_custom_timeout: + self._last_custom_timeout = now + + if now - self._last_custom_timeout >= retry_check_result: + return False + + return True + + def wait_before_retry(self) -> None: + """Block until the next retry should happen. + + Raises: + RetryCancelledError: If the operation is cancelled. + """ + sleep_amount = self._next_sleep_time * (1 + random.random() * 0.25) + + if self._cancel_event: + cancelled = self._cancel_event.wait(sleep_amount) + if cancelled: + raise RetryCancelledError("Cancelled while retrying.") + else: + SLEEP_FN(sleep_amount) + + self._next_sleep_time *= 2 + if self._next_sleep_time > self._max_sleep: + self._next_sleep_time = self._max_sleep + + +_F = TypeVar("_F", bound=Callable) + + +def retriable(*args: Any, **kargs: Any) -> Callable[[_F], _F]: + def decorator(fn: _F) -> _F: + retrier: Retry[Any] = Retry(fn, *args, **kargs) + + @functools.wraps(fn) + def wrapped_fn(*args: Any, **kargs: Any) -> Any: + return retrier(*args, **kargs) + + return wrapped_fn # type: ignore + + return decorator + + +class Backoff(abc.ABC): + """A backoff strategy: decides whether to sleep or give up when an exception is raised.""" + + @abc.abstractmethod + def next_sleep_or_reraise(self, exc: Exception) -> datetime.timedelta: + raise NotImplementedError # pragma: no cover + + +class ExponentialBackoff(Backoff): + """Jittered exponential backoff: sleep times increase ~exponentially up to some limit.""" + + def __init__( + self, + initial_sleep: datetime.timedelta, + max_sleep: datetime.timedelta, + max_retries: int | None = None, + timeout_at: datetime.datetime | None = None, + ) -> None: + self._next_sleep = min(max_sleep, initial_sleep) + self._max_sleep = max_sleep + self._remaining_retries = max_retries + self._timeout_at = timeout_at + + def next_sleep_or_reraise(self, exc: Exception) -> datetime.timedelta: + if self._remaining_retries is not None: + if self._remaining_retries <= 0: + raise exc + self._remaining_retries -= 1 + + if self._timeout_at is not None and NOW_FN() > self._timeout_at: + raise exc + + result, self._next_sleep = ( + self._next_sleep, + min(self._max_sleep, self._next_sleep * (1 + random.random())), + ) + + return result + + +class FilteredBackoff(Backoff): + """Re-raise any exceptions that fail a predicate; delegate others to another Backoff.""" + + def __init__(self, filter: Callable[[Exception], bool], wrapped: Backoff) -> None: + self._filter = filter + self._wrapped = wrapped + + def next_sleep_or_reraise(self, exc: Exception) -> datetime.timedelta: + if not self._filter(exc): + raise exc + return self._wrapped.next_sleep_or_reraise(exc) + + +async def retry_async( + backoff: Backoff, + fn: Callable[..., Awaitable[_R]], + *args: Any, + on_exc: Callable[[Exception], None] | None = None, + **kwargs: Any, +) -> _R: + """Call `fn` repeatedly until either it succeeds, or `backoff` decides we should give up. + + Each time `fn` fails, `on_exc` is called with the exception. + """ + while True: + try: + return await fn(*args, **kwargs) + except Exception as e: + if on_exc is not None: + on_exc(e) + await SLEEP_ASYNC_FN(backoff.next_sleep_or_reraise(e).total_seconds()) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/run_messages.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/run_messages.py new file mode 100644 index 0000000000000000000000000000000000000000..c54d69b30154315232d6b2919ad7d103c0f278c9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/run_messages.py @@ -0,0 +1,138 @@ +"""Echoing messages from wandb-core to the terminal.""" + +from __future__ import annotations + +import asyncio +import contextlib +import logging +import time + +from wandb.errors import term +from wandb.proto import wandb_internal_pb2 as pb +from wandb.sdk.interface.interface import InterfaceBase +from wandb.sdk.lib import asyncio_compat, asyncio_manager + +# Patched in tests. +_NOW = time.monotonic +_SLEEP = asyncio.sleep + + +_logger = logging.getLogger(__name__) + + +class RunMessages: + """Polls and prints run messages from wandb-core. + + Messages are scoped to a run. In the future, we may want to switch to + connection-level messages to allow `ServiceApi` operations to print + and replace this by a new ServiceMessages class. + """ + + def __init__( + self, + asyncer: asyncio_manager.AsyncioManager, + interface: InterfaceBase, + *, + poll_interval: float = 10, + ) -> None: + self._asyncer = asyncer + + async def async_init() -> _RunMessagesImpl: + return _RunMessagesImpl(interface, poll_interval=poll_interval) + + self._impl = asyncer.run(async_init) + + def start(self) -> None: + """Start polling for and printing generated messages.""" + self._asyncer.run_soon( + self._impl.loop, + daemon=True, + name="RunMessages.loop", + ) + + def stop(self, *, timeout: float) -> None: + """Stop the polling loop and print any final messages. + + Args: + timeout: How long to wait, in seconds, before giving up. + A warning is printed on timeout; some messages may get + asynchronously printed in the future. + """ + with contextlib.suppress(asyncio_manager.AlreadyJoinedError): + self._asyncer.run(lambda: self._impl.stop(timeout=timeout)) + + +class _RunMessagesImpl: + def __init__( + self, + interface: InterfaceBase, + *, + poll_interval: float, + ) -> None: + self._interface = interface + self._poll_interval = poll_interval + + self._stop_event = asyncio.Event() # stop requested + self._done_event = asyncio.Event() # loop() done + + async def stop(self, *, timeout: float) -> None: + """Stop looping and print any final messages. + + Assumes that `loop` has been or will be called. + + Args: + timeout: How long to wait, in seconds, before giving up. + On timeout, some messages may be missed or may print + asynchronously. + """ + timeout_at = time.monotonic() + timeout + + self._stop_event.set() + try: + await asyncio.wait_for(self._done_event.wait(), timeout) + await self._poll_and_print(timeout=timeout_at - time.monotonic()) + + # NOTE: asyncio.TimeoutError is different from TimeoutError + # until Python 3.11. + except (asyncio.TimeoutError, TimeoutError): + _logger.exception("Timed out waiting for messages.") + + async def loop(self) -> None: + """Print messages until asked to stop.""" + try: + while not self._stop_event.is_set(): + start_time = _NOW() + await self._poll_and_print(timeout=None) + end_time = _NOW() + + remaining = self._poll_interval - (end_time - start_time) + if remaining > 0: + await asyncio_compat.race( + self._stop_event.wait(), # wake up if stopping + _SLEEP(remaining), + ) + finally: + self._done_event.set() + + async def _poll_and_print(self, *, timeout: float | None) -> None: + """Fetch and print messages. + + Args: + timeout: How long to wait for wandb-core to respond. + + Raises: + TimeoutError: if timeout was specified and was exceeded. + If a timeout occurs, some messages may be lost. + """ + request = pb.Record( + request=pb.Request( + internal_messages=pb.InternalMessagesRequest(), + ) + ) + + handle = await self._interface.deliver_async(request) + result = await handle.wait_async(timeout=timeout) + + warnings = result.response.internal_messages_response.messages.warning + for msg in warnings: + term.termwarn(msg) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/run_moment.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/run_moment.py new file mode 100644 index 0000000000000000000000000000000000000000..aa293b5a480382f5b2bb51528be2833c84ce3cdb --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/run_moment.py @@ -0,0 +1,82 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Union +from urllib import parse + + +@dataclass +class RunMoment: + """A moment in a run. + + Defines a branching point in a finished run to fork or resume from. + A run moment is identified by a run ID and a metric value. + Currently, only the metric '_step' is supported. + """ + + run: str + """run ID""" + + value: Union[int, float] + """Value of the metric.""" + + metric: str = "_step" + """Metric to use to determine the moment in the run. + + Currently, only the metric '_step' is supported. + In future, this will be relaxed to be any metric. + """ + + def __post_init__(self): + if self.metric != "_step": + raise ValueError( + f"Only the metric '_step' is supported, got '{self.metric}'." + ) + if not isinstance(self.value, (int, float)): + raise TypeError( + f"Only int or float values are supported, got '{self.value}'." + ) + if not isinstance(self.run, str): + raise TypeError(f"Only string run names are supported, got '{self.run}'.") + + @classmethod + def from_uri(cls, uri: str) -> RunMoment: + parsable = "runmoment://" + uri + parse_err = ValueError( + f"Could not parse passed run moment string '{uri}', " + f"expected format '?='. " + f"Currently, only the metric '_step' is supported. " + f"Example: 'ans3bsax?_step=123'." + ) + + try: + parsed = parse.urlparse(parsable) + except ValueError as e: + raise parse_err from e + + if parsed.scheme != "runmoment": + raise parse_err + + # extract run, metric, value from parsed + if not parsed.netloc: + raise parse_err + + run = parsed.netloc + + if parsed.path or parsed.params or parsed.fragment: + raise parse_err + + query = parse.parse_qs(parsed.query) + if len(query) != 1: + raise parse_err + + metric = list(query.keys())[0] + if metric != "_step": + raise parse_err + value: str = query[metric][0] + try: + num_value = int(value) if value.isdigit() else float(value) + except ValueError as e: + raise parse_err from e + + return cls(run=run, metric=metric, value=num_value) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/run_stopping.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/run_stopping.py new file mode 100644 index 0000000000000000000000000000000000000000..0f272eb3c98975ed1f1320e9e251f544c2d7589a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/run_stopping.py @@ -0,0 +1,117 @@ +"""Stopping a run if requested by wandb-core. + +A run can be stopped manually through the UI or automatically after +a fatal upload error (if configured). "Stopping" a run means killing +its script. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import time +from collections.abc import Callable + +from wandb.agents import pyagent +from wandb.proto import wandb_internal_pb2 as pb +from wandb.sdk.interface.interface import InterfaceBase +from wandb.sdk.lib import asyncio_compat, asyncio_manager + +# Patched in tests. +_NOW = time.monotonic +_SLEEP = asyncio.sleep +_POLL_INTERVAL = 15 + + +class RunStopChecker: + """Kills the script if requested by wandb-core.""" + + def __init__( + self, + asyncer: asyncio_manager.AsyncioManager, + interface: InterfaceBase, + stop_fn: Callable[[], None], + *, + poll_interval: float = _POLL_INTERVAL, + ) -> None: + self._asyncer = asyncer + + async def async_init() -> _RunStopCheckerImpl: + return _RunStopCheckerImpl( + interface, + stop_fn, + poll_interval=poll_interval, + ) + + self._impl = asyncer.run(async_init) + + def start(self) -> None: + """Start checking for whether the run is stopped.""" + self._asyncer.run_soon( + self._impl.loop, + daemon=True, + name="RunStopChecker.loop", + ) + + def stop_soon(self) -> None: + """Stop the polling loop. + + This is best-effort. It is still possible for the status checker to + kill the script for a short time after this function returns. + """ + with contextlib.suppress(asyncio_manager.AlreadyJoinedError): + self._asyncer.run(lambda: self._impl.stop_soon()) + + +class _RunStopCheckerImpl: + def __init__( + self, + interface: InterfaceBase, + stop_fn: Callable[[], None], + *, + poll_interval: float, + ) -> None: + self._interface = interface + self._stop_fn = stop_fn + self._poll_interval = poll_interval + self._stop_event = asyncio.Event() # stop requested + + async def stop_soon(self) -> None: + """Stop looping.""" + self._stop_event.set() + + async def loop(self) -> None: + """Check the run's stop status until we are done.""" + while not self._stop_event.is_set(): + start_time = _NOW() + should_stop = await self._check_should_stop() + end_time = _NOW() + + # Only stop once. + if should_stop: + self._stop_fn() + return + + remaining = self._poll_interval - (end_time - start_time) + if remaining > 0: + await asyncio_compat.race( + self._stop_event.wait(), # wake up if stopping + _SLEEP(remaining), + ) + + async def _check_should_stop(self) -> bool: + """Check whether the run should stop.""" + # TODO: Remove the pyagent.is_running() check if safe to do so. + # See WB-3606. + if pyagent.is_running(): + return False + + request = pb.Record( + request=pb.Request( + stop_status=pb.StopStatusRequest(), + ), + ) + + handle = await self._interface.deliver_async(request) + result = await handle.wait_async(timeout=None) + return result.response.stop_status_response.run_should_stop diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/runid.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/runid.py new file mode 100644 index 0000000000000000000000000000000000000000..7fe5c2f2a7294d2b1b9000d14cae275707f98482 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/runid.py @@ -0,0 +1,38 @@ +"""runid util.""" + +import os +import random +import secrets +from string import ascii_lowercase, digits + +_ID_CHARS = f"{ascii_lowercase}{digits}" + +# Create a dedicated Random instance with its own state so it +# is not affected by global random.seed() calls +_random = random.Random() + + +# Reset the random number generator on forking a new process to avoid multiple processes using the same seed. +# The `random` module basically does this internally for python's global random state. +# This is only necessary on platforms that support the `fork` multiprocessing start method (e.g. POSIX). +if hasattr(os, "fork"): + os.register_at_fork(after_in_child=_random.seed) + + +def generate_id(length: int = 8) -> str: + """Generate a random base-36 string of `length` digits.""" + # There are ~2.8T base-36 8-digit strings. If we generate 210k ids, + # we'll have a ~1% chance of collision. + return "".join(secrets.choice(_ID_CHARS) for _ in range(length)) + + +def generate_fast_id(length: int = 8) -> str: + """Faster alternative to `generate_id` if cryptographic strength isn't needed. + + In local testing at the time of implementation, this is ~30-50x faster than + `generate_id` when generating 128-character IDs. + + Uses a dedicated Random instance to avoid being affected by global + random.seed() calls from user code or libraries. + """ + return "".join(_random.choices(_ID_CHARS, k=length)) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/server.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/server.py new file mode 100644 index 0000000000000000000000000000000000000000..19a234a6f79c5dd683a312c50d4315ef551d4f4c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/server.py @@ -0,0 +1,59 @@ +"""module server.""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any + +from wandb import util + +if TYPE_CHECKING: + from wandb.sdk.wandb_settings import Settings + + +class Server: + def __init__( + self, + settings: Settings, + ) -> None: + from wandb.apis import InternalApi + + self._api = InternalApi(default_settings=settings) + self._viewer: dict[str, Any] = {} + self._flags: dict[str, Any] = {} + self._settings: Settings = settings + + def query_with_timeout(self, timeout: int | float = 5) -> None: + if self._settings.x_disable_viewer: + return + + async_viewer = util.async_call(self._api.viewer_server_info, timeout=timeout) + try: + viewer_tuple, viewer_thread = async_viewer() + except Exception: + return + if viewer_thread.is_alive(): + # this is likely a DNS hang + return + # TODO(jhr): should we kill the thread? + self._viewer, self._serverinfo = viewer_tuple + self._flags = json.loads(self._viewer.get("flags") or "{}") + + @property + def viewer(self) -> dict[str, Any]: + """Returns information about the currently authenticated user. + + If the API key is valid, the following is returned: + - id + - entity + - username + - flags + - teams + + If the API key is not valid or the server is not reachable, + an empty dict is returned. + """ + if not self._viewer and not self._settings._offline: + self.query_with_timeout() + + return self._viewer diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/settings_file.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/settings_file.py new file mode 100644 index 0000000000000000000000000000000000000000..5471702812ec382e78c6d7e6ece96ebd18f33a1c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/settings_file.py @@ -0,0 +1,196 @@ +"""Reading and writing W&B settings files. + +There is usually a "global" settings file at ~/.config/wandb/settings. +A "local" settings file, also referred to as "workspace settings", is created +by the `wandb init` CLI command at ./wandb/settings. Any settings defined in +the local file override settings in the global file. + +These settings files are generally updated by CLI commands like `wandb online`, +`wandb offline` and `wandb login`, but it is possible to modify them manually. +The most common settings found in these files are `base_url` (the W&B server +URL if not using SaaS) and `mode` (online or offline). +""" + +from __future__ import annotations + +import configparser +import logging +import pathlib + +from wandb.errors import Error, term + +# The only section name we recognize in all settings files. +_SECTION_NAME = "default" + + +_logger = logging.getLogger(__name__) + + +class SaveSettingsError(Error): + """Could not update one or more settings files. + + The __str__ representation is written to be printed to a terminal. + """ + + +class SettingsFiles: + """System settings as determined by the settings files.""" + + def __init__( + self, + *, + global_settings: pathlib.Path | None, + local_settings: pathlib.Path, + ) -> None: + """Open system settings file(s) for reading and writing. + + If the files don't exist, they are treated as empty. + If there are problems reading the files, the files are treated as empty + and the problems are logged and printed to the terminal. + + Args: + global_settings: The global settings file path. If None, local + settings are used for everything. + local_settings: The local settings file path. + """ + self._local_modified = False + self._global_modified = False + + self._global_path = global_settings + self._local_path = local_settings + self._sources: list[pathlib.Path] = [] + + if self._global_path and (settings := _try_read(self._global_path)): + self._sources.append(self._global_path) + self._global_settings = settings + else: + self._global_settings = {} + + if settings := _try_read(self._local_path): + self._sources.append(self._local_path) + self._local_settings = settings + else: + self._local_settings = {} + + @property + def sources(self) -> list[pathlib.Path]: + """Returns the list of file paths in which settings were found. + + This does not include files that were empty or did not exist. + """ + return self._sources + + def save(self) -> None: + """Write changes to settings files. + + This is a no-op if neither set() nor clear() were ever called, + or if they made no changes. + + Raises: + SaveSettingsError: If failed to write one or more files. + """ + if self._local_modified: + _write(self._local_path, self._local_settings) + + if self._global_path and self._global_modified: + _write(self._global_path, self._global_settings) + + def all(self) -> dict[str, str]: + """Returns settings as a dictionary.""" + settings = self._global_settings.copy() + settings.update(self._local_settings) + return settings + + def set(self, key: str, value: str, *, globally: bool = False) -> None: + """Set a new value for a setting. + + Args: + key: The name of the setting. + value: The setting's new value. + globally: If false or if there's no global settings file, + update only the local settings file. + Otherwise, remove this setting from local settings and update + global settings. + """ + if not globally or not self._global_path: + old_value = self._local_settings.get(key) + self._local_settings[key] = value + if old_value != value: + self._local_modified = True + + else: + old_value = self._local_settings.pop(key, None) + if old_value is not None: + self._local_modified = True + + old_value = self._global_settings.get(key) + self._global_settings[key] = value + if old_value != value: + self._global_modified = True + + def clear(self, key: str, *, globally: bool = False) -> None: + """Clear a setting. + + Args: + key: The name of the setting. + globally: If false, update only the local settings file. + If true, update both local and global settings. + """ + old_value = self._local_settings.pop(key, None) + if old_value is not None: + self._local_modified = True + + if globally: + old_value = self._global_settings.pop(key, None) + if old_value is not None: + self._global_modified = True + + +def _try_read(path: pathlib.Path) -> dict[str, str]: + """Try to read the settings file at the given path. + + Returns an empty dictionary if the file doesn't exist or if there's + any problem reading the file. In the latter case, prints a warning as well. + """ + try: + # The exists() check can hit a permission error. + if not path.exists(): + return {} + except OSError as e: + _logger.exception(f"Error reading settings at {path}") + term.termwarn(f"Error reading settings at {path}: {e}", repeat=False) + + parser = configparser.ConfigParser() + + try: + parser.read(path) + except (OSError, configparser.Error) as e: + _logger.exception(f"Error reading settings at {path}") + term.termwarn(f"Error reading settings at {path}: {e}", repeat=False) + return {} + + try: + return dict(parser.items(section=_SECTION_NAME)) + except configparser.NoSectionError: + return {} + + +def _write(path: pathlib.Path, settings: dict[str, str]) -> None: + """Try to update the settings file at the path. + + Raises: + SaveSettingsError: If unable to remove or update the file. + """ + parser = configparser.ConfigParser() + parser.add_section(_SECTION_NAME) + for key, value in settings.items(): + parser.set(_SECTION_NAME, key, value) + + try: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w") as f: + parser.write(f) + except (OSError, configparser.Error) as e: + raise SaveSettingsError(f"Error updating settings at {path}: {e}") from e + + term.termlog(f"Updated settings file {path}") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/sparkline.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/sparkline.py new file mode 100644 index 0000000000000000000000000000000000000000..1c1454c4d8c327a37cd7804503c8538ea91ece63 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/sparkline.py @@ -0,0 +1,44 @@ +# +# From pysparklines (BSD License): https://pypi.python.org/pypi/pysparklines +from __future__ import annotations + +import math + +spark_chars = "▁▂▃▄▅▆▇█" + + +# math.isfinite doesn't exist in python2, so provider our own +def isfinite(f): + return not (math.isinf(f) or math.isnan(f)) + + +def sparkify(series: list[float | int]) -> str: + """Convert to a sparkline string. + + Example: + >>> sparkify([0.5, 1.2, 3.5, 7.3, 8.0, 12.5, 13.2, 15.0, 14.2, 11.8, 6.1, 1.9]) + u'▁▁▂▄▅▇▇██▆▄▂' + + >>> sparkify([1, 1, -2, 3, -5, 8, -13]) + u'▆▆▅▆▄█▁' + + Raises ValueError if input data cannot be converted to float. + Raises TypeError if series is not an iterable. + """ + series = [float(i) for i in series] + finite_series = [x for x in series if isfinite(x)] + if not finite_series: + return "" + minimum = min(finite_series) + maximum = max(finite_series) + data_range = maximum - minimum + if data_range == 0.0: + # Graph a baseline if every input value is equal. + return "".join([spark_chars[0] if isfinite(x) else " " for x in series]) + coefficient = (len(spark_chars) - 1.0) / data_range + return "".join( + [ + spark_chars[int(round((x - minimum) * coefficient))] if isfinite(x) else " " + for x in series + ] + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/telemetry.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/telemetry.py new file mode 100644 index 0000000000000000000000000000000000000000..b515f148841af8f1718df0d213ab211ac61c8272 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/telemetry.py @@ -0,0 +1,103 @@ +from __future__ import annotations + +import re +import sys +from contextlib import AbstractContextManager +from types import TracebackType +from typing import TYPE_CHECKING + +import wandb +from wandb.proto.wandb_telemetry_pb2 import Imports as TelemetryImports +from wandb.proto.wandb_telemetry_pb2 import TelemetryRecord + +# avoid cycle, use string type reference + +if TYPE_CHECKING: + from .. import wandb_run + + +_LABEL_TOKEN: str = "@wandbcode{" + + +class _TelemetryObject: + _run: wandb_run.Run | None + _obj: TelemetryRecord + + def __init__( + self, + run: wandb_run.Run | None = None, + obj: TelemetryRecord | None = None, + ) -> None: + self._run = run or wandb.run + self._obj = obj or TelemetryRecord() + + def __enter__(self) -> TelemetryRecord: + return self._obj + + def __exit__( + self, + exctype: type[BaseException] | None, + excinst: BaseException | None, + exctb: TracebackType | None, + ) -> None: + if not self._run: + return + self._run._telemetry_callback(self._obj) + + +def context( + run: wandb_run.Run | None = None, obj: TelemetryRecord | None = None +) -> AbstractContextManager[TelemetryRecord]: + return _TelemetryObject(run=run, obj=obj) + + +MATCH_RE = re.compile(r"(?P[a-zA-Z0-9_-]+)[,}](?P.*)") + + +def _parse_label_lines(lines: list[str]) -> dict[str, str]: + seen = False + ret = {} + for line in lines: + idx = line.find(_LABEL_TOKEN) + if idx < 0: + # Stop parsing on first non token line after match + if seen: + break + continue + seen = True + label_str = line[idx + len(_LABEL_TOKEN) :] + + # match identifier (first token without key=value syntax (optional) + # Note: Parse is fairly permissive as it does not enforce strict syntax + r = MATCH_RE.match(label_str) + if r: + ret["code"] = r.group("code").replace("-", "_") + label_str = r.group("rest") + + # match rest of tokens on one line + tokens = re.findall( + r'([a-zA-Z0-9_]+)\s*=\s*("[a-zA-Z0-9_-]*"|[a-zA-Z0-9_-]*)[,}]', label_str + ) + for k, v in tokens: + ret[k] = v.strip('"').replace("-", "_") + return ret + + +def list_telemetry_imports(only_imported: bool = False) -> set[str]: + import_telemetry_set = { + desc.name + for desc in TelemetryImports.DESCRIPTOR.fields + if desc.type == desc.TYPE_BOOL + } + if only_imported: + imported_modules_set = set(sys.modules) + return imported_modules_set.intersection(import_telemetry_set) + return import_telemetry_set + + +__all__ = [ + "TelemetryImports", + "TelemetryRecord", + "context", + "list_telemetry_imports", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/timed_input.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/timed_input.py new file mode 100644 index 0000000000000000000000000000000000000000..6ea4568e49c3db78871c4b519ad99eaf980c6ccd --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/timed_input.py @@ -0,0 +1,140 @@ +"""timed_input: add a timeout to standard input. + +Approach was inspired by: https://github.com/johejo/inputimeout +""" + +import sys +import threading + +import wandb + +SP = " " +CR = "\r" +LF = "\n" +CRLF = CR + LF + + +def _echo(prompt: str, *, err: bool) -> None: + stream = sys.stderr if err else sys.stdout + stream.write(prompt) + stream.flush() + + +def _posix_timed_input(prompt: str, timeout: float, err: bool) -> str: + _echo(prompt, err=err) + sel = selectors.DefaultSelector() + sel.register(sys.stdin, selectors.EVENT_READ, data=sys.stdin.readline) + events = sel.select(timeout=timeout) + + for key, _ in events: + input_callback = key.data + input_data: str = input_callback() + if not input_data: # end-of-file - treat as timeout + raise TimeoutError + return input_data.rstrip(LF) + + _echo(LF, err=err) + termios.tcflush(sys.stdin, termios.TCIFLUSH) + raise TimeoutError + + +def _windows_timed_input(prompt: str, timeout: float, err: bool) -> str: + interval = 0.1 + + _echo(prompt, err=err) + begin = time.monotonic() + end = begin + timeout + line = "" + + while time.monotonic() < end: + if msvcrt.kbhit(): # type: ignore[attr-defined] + c = msvcrt.getwche() # type: ignore[attr-defined] + if c in (CR, LF): + _echo(CRLF, err=err) + return line + if c == "\003": + raise KeyboardInterrupt + if c == "\b": + line = line[:-1] + cover = SP * len(prompt + line + SP) + _echo("".join([CR, cover, CR, prompt, line]), err=err) + else: + line += c + time.sleep(interval) + + _echo(CRLF, err=err) + raise TimeoutError + + +def _jupyter_timed_input(prompt: str, timeout: float, err: bool) -> str: + clear = True + try: + from IPython.core.display import clear_output # type: ignore + except ImportError: + clear = False + wandb.termwarn( + "Unable to clear output, can't import clear_output from ipython.core" + ) + + _echo(prompt, err=err) + + user_inp = None + event = threading.Event() + + def get_input() -> None: + nonlocal user_inp + raw = input() + if event.is_set(): + return + user_inp = raw + + t = threading.Thread(target=get_input) + t.start() + t.join(timeout) + event.set() + if user_inp: + return user_inp + if clear: + clear_output() + raise TimeoutError + + +def timed_input( + prompt: str, + timeout: float, + show_timeout: bool = True, + jupyter: bool = False, + err: bool = False, +) -> str: + """Behaves like builtin `input()` but adds timeout. + + Args: + prompt: Prompt to output to stdout. + timeout: Timeout to wait for input. + show_timeout: Show timeout in prompt + jupyter: If True, use jupyter specific code. + err: If True, use stderr instead of stdout. + + Raises: + TimeoutError: If a timeout occurred. + KeyboardInterrupt: If the user aborted by pressing Ctrl+C. + """ + if show_timeout: + prompt = f"{prompt}({timeout:.0f} second timeout) " + if jupyter: + return _jupyter_timed_input(prompt=prompt, timeout=timeout, err=err) + + return _timed_input(prompt=prompt, timeout=timeout, err=err) + + +try: + import msvcrt +except ImportError: + import selectors + import termios + + _timed_input = _posix_timed_input +else: + import time + + _timed_input = _windows_timed_input diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/timer.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/timer.py new file mode 100644 index 0000000000000000000000000000000000000000..14b162c9d33f2f883f815de3a1e655b8cae192db --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/timer.py @@ -0,0 +1,21 @@ +import time +from typing import Any + +from typing_extensions import Self + + +class Timer: + def __init__(self) -> None: + self.start_time: float = time.time() + self.start: float = time.perf_counter() + self.stop: float = self.start + + def __enter__(self) -> Self: + return self + + def __exit__(self, *args: Any) -> None: + self.stop = time.perf_counter() + + @property + def elapsed(self) -> float: + return self.stop - self.start diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/urls.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/urls.py new file mode 100644 index 0000000000000000000000000000000000000000..8831c42717c536ed6e435bdf64c734822a30dbf3 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/urls.py @@ -0,0 +1,26 @@ +"""Validation for URLs.""" + +from pydantic_core import SchemaValidator, core_schema + +_URL_VALIDATOR = SchemaValidator( + core_schema.url_schema( + allowed_schemes=["http", "https"], + strict=True, + ) +) + + +def validate_url(url: object) -> None: + """Validate a URL. + + Args: + url: The URL to validate. + + Raises: + ValueError: If the URL is invalid. + TypeError: If given something other than a string. + """ + if not isinstance(url, str): + raise TypeError(f"Expected a string, got {type(url)}") + + _URL_VALIDATOR.validate_python(url) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/wb_logging.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/wb_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..cd243d4aecc4fdefa4f3d2f7c6a677d72a1547ac --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/lib/wb_logging.py @@ -0,0 +1,162 @@ +"""Logging configuration for the "wandb" logger. + +Most log statements in wandb are made in the context of a run and should be +redirected to that run's log file (usually named 'debug.log'). This module +provides a context manager to temporarily set the current run ID and registers +a global handler for the 'wandb' logger that sends log statements to the right +place. + +All functions in this module are threadsafe. + +NOTE: The pytest caplog fixture will fail to capture logs from the wandb logger +because they are not propagated to the root logger. +""" + +from __future__ import annotations + +import contextlib +import contextvars +import logging +import pathlib +from collections.abc import Iterator + + +class _NotRunSpecific: + """Sentinel for `not_run_specific()`.""" + + +_NOT_RUN_SPECIFIC = _NotRunSpecific() + + +_run_id: contextvars.ContextVar[str | _NotRunSpecific | None] = contextvars.ContextVar( + "_run_id", + default=None, +) + +_logger = logging.getLogger("wandb") + + +def configure_wandb_logger() -> None: + """Configures the global 'wandb' logger. + + The wandb logger is not intended to be customized by users. Instead, it is + used as a mechanism to redirect log messages into wandb run-specific log + files. + + This function is idempotent: calling it multiple times has the same effect. + """ + # Send all DEBUG and above messages to registered handlers. + # + # Per-run handlers can set different levels. + _logger.setLevel(logging.DEBUG) + + # Do not propagate wandb logs to the root logger, which the user may have + # configured to point elsewhere. All wandb log messages should go to a run's + # log file. + _logger.propagate = False + + # If no handlers are configured for the 'wandb' logger, don't activate the + # "lastResort" handler which sends messages to stderr with a level of + # WARNING by default. + # + # This occurs in wandb code that runs outside the context of a Run and + # not as part of the CLI. + # + # Most such code uses the `termlog` / `termwarn` / `termerror` methods + # to communicate with the user. When that code executes while a run is + # active, its logger messages go to that run's log file. + if not _logger.handlers: + _logger.addHandler(logging.NullHandler()) + + +@contextlib.contextmanager +def log_to_run(run_id: str | None) -> Iterator[None]: + """Direct all wandb log messages to the given run. + + Args: + id: The current run ID, or None if actions in the context manager are + not associated to a specific run. In the latter case, log messages + will go to all runs. + + Usage: + + with wb_logging.run_id(...): + ... # Log messages here go to the specified run's logger. + """ + token = _run_id.set(run_id) + try: + yield + finally: + _run_id.reset(token) + + +@contextlib.contextmanager +def log_to_all_runs() -> Iterator[None]: + """Direct wandb log messages to all runs. + + Unlike `log_to_run(None)`, this indicates an intentional choice. + This is often convenient to use as a decorator: + + @wb_logging.log_to_all_runs() + def my_func(): + ... # Log messages here go to the specified run's logger. + """ + token = _run_id.set(_NOT_RUN_SPECIFIC) + try: + yield + finally: + _run_id.reset(token) + + +def add_file_handler(run_id: str, filepath: pathlib.Path) -> logging.Handler: + """Direct log messages for a run to a file. + + Args: + run_id: The run for which to create a log file. + filepath: The file to write log messages to. + + Returns: + The added handler which can then be configured further or removed + from the 'wandb' logger directly. + + The default logging level is INFO. + """ + handler = logging.FileHandler(filepath) + handler.setLevel(logging.INFO) + handler.addFilter(_RunIDFilter(run_id)) + handler.setFormatter( + logging.Formatter( + "%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d" + " [%(filename)s:%(funcName)s():%(lineno)s]%(run_id_tag)s" + " %(message)s" + ) + ) + + _logger.addHandler(handler) + return handler + + +class _RunIDFilter: + """Filters out messages logged for a different run.""" + + def __init__(self, run_id: str) -> None: + """Create a _RunIDFilter. + + Args: + run_id: Allows messages when the run ID is this or None. + """ + self._run_id = run_id + + def filter(self, record: logging.LogRecord) -> bool: + """Modify a log record and return whether it matches the run.""" + run_id = _run_id.get() + + if run_id is None: + record.run_id_tag = " [no run ID]" + return True + elif isinstance(run_id, _NotRunSpecific): + record.run_id_tag = " [all runs]" + return True + else: + record.run_id_tag = "" + return run_id == self._run_id diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/mailbox/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/mailbox/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e89b3d0e3b8d7124ac97264cfa66c5330a2a39a0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/mailbox/__init__.py @@ -0,0 +1,23 @@ +"""A message protocol for the internal service process. + +The core of W&B is implemented by a side process that asynchronously uploads +data. The client process (such as this Python code) sends requests to the +service, and for some requests, the service eventually sends a response. + +The client can send multiple requests before the service provides a response. +The Mailbox handles matching responses to requests. An internal thread +continuously reads data from the service and passes it to the mailbox. +""" + +from .mailbox import Mailbox, MailboxClosedError +from .mailbox_handle import HandleAbandonedError, MailboxHandle +from .wait_with_progress import wait_all_with_progress, wait_with_progress + +__all__ = [ + "Mailbox", + "MailboxClosedError", + "HandleAbandonedError", + "MailboxHandle", + "wait_all_with_progress", + "wait_with_progress", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/mailbox/mailbox.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/mailbox/mailbox.py new file mode 100644 index 0000000000000000000000000000000000000000..7c34271b253990295a1639ee1d838628ab491464 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/mailbox/mailbox.py @@ -0,0 +1,160 @@ +from __future__ import annotations + +import logging +import secrets +import string +import threading +from collections.abc import Awaitable, Callable + +from wandb.proto import wandb_internal_pb2 as pb +from wandb.proto import wandb_server_pb2 as spb +from wandb.sdk.lib import asyncio_manager + +from .mailbox_handle import MailboxHandle +from .response_handle import MailboxResponseHandle + +_logger = logging.getLogger(__name__) + + +class MailboxClosedError(Exception): + """The mailbox has been closed and cannot be used.""" + + +class Mailbox: + """Matches service responses to requests. + + The mailbox can set an address on a server request and create a handle for + waiting for a response to that record. Responses are delivered by calling + `deliver()`. The `close()` method abandons all handles in case the + service process becomes unreachable. + """ + + def __init__( + self, + asyncer: asyncio_manager.AsyncioManager, + cancel: Callable[[str], Awaitable[None]], + ) -> None: + """Create a mailbox. + + Args: + asyncer: Asyncio runner for scheduling async operations. + cancel: A callback that can be used to cancel a request by ID. + """ + self._asyncer = asyncer + self._cancel = cancel + + self._handles: dict[str, MailboxResponseHandle] = {} + self._handles_lock = threading.Lock() + self._closed = False + + def require_response( + self, + request: spb.ServerRequest | pb.Record, + ) -> MailboxHandle[spb.ServerResponse]: + """Set a response address on a request. + + Args: + request: The request on which to set a request ID or mailbox slot. + This is mutated. An address must not already be set. + + Returns: + A handle for waiting for the response to the request. + + Raises: + MailboxClosedError: If the mailbox has been closed, in which case + no new responses are expected to be delivered and new handles + cannot be created. + """ + if isinstance(request, spb.ServerRequest): + if (address := request.request_id) or ( + address := request.record_publish.control.mailbox_slot + ): + raise ValueError(f"Request already has an address ({address})") + + address = self._new_address() + request.request_id = address + if request.HasField("record_publish"): + request.record_publish.control.mailbox_slot = address + if request.HasField("record_communicate"): + request.record_communicate.control.mailbox_slot = address + else: + if address := request.control.mailbox_slot: + raise ValueError(f"Request already has an address ({address})") + + address = self._new_address() + request.control.mailbox_slot = address + + with self._handles_lock: + if self._closed: + raise MailboxClosedError() + + handle = MailboxResponseHandle( + address, + asyncer=self._asyncer, + cancel=self._cancel, + ) + self._handles[address] = handle + + return handle + + def _new_address(self) -> str: + """Returns an unused address for a request. + + Assumes `_handles_lock` is held. + """ + + def generate(): + return "".join( + secrets.choice(string.ascii_lowercase + string.digits) + for _ in range(12) + ) + + address = generate() + + # Being extra cautious. This loop will almost never be entered. + while address in self._handles: + address = generate() + + return address + + async def deliver(self, response: spb.ServerResponse) -> None: + """Deliver a response from the service. + + If the response address is invalid, this does nothing. + It is a no-op if the mailbox has been closed. + """ + address = response.request_id + if not address: + kind: str | None = response.WhichOneof("server_response_type") + if kind == "result_communicate": + result_type = response.result_communicate.WhichOneof("result_type") + kind = f"result_communicate.{result_type}" + + _logger.error(f"Received response with no mailbox slot: {kind}") + return + + with self._handles_lock: + # NOTE: If the mailbox is closed, this returns None because + # we clear the dict. + handle = self._handles.pop(address, None) + + # It is not an error if there is no handle for the address: + # handles can be abandoned if the result is no longer needed. + if handle: + await handle.deliver(response) + + def close(self) -> None: + """Indicate no further responses will be delivered. + + Abandons all handles. + """ + with self._handles_lock: + self._closed = True + + _logger.info( + f"Closing mailbox, abandoning {len(self._handles)} handles.", + ) + + for handle in self._handles.values(): + handle.abandon() + self._handles.clear() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/mailbox/mailbox_handle.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/mailbox/mailbox_handle.py new file mode 100644 index 0000000000000000000000000000000000000000..415a0e552749c357d961330cf9e6969f4a2b5d58 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/mailbox/mailbox_handle.py @@ -0,0 +1,128 @@ +from __future__ import annotations + +import abc +from collections.abc import Callable +from typing import Generic + +from typing_extensions import TypeVar, override + +from wandb.sdk.lib import asyncio_manager + +_T = TypeVar("_T") +_S = TypeVar("_S") + + +class HandleAbandonedError(Exception): + """The handle has no response and has been abandoned.""" + + +class ServerResponseError(Exception): + """The handle received a generic error response. + + In practice, this corresponds to receiving the ServerErrorResponse message. + """ + + +class MailboxHandle(abc.ABC, Generic[_T]): + """A handle for waiting on a response to a request.""" + + def __init__(self, asyncer: asyncio_manager.AsyncioManager) -> None: + self._asyncer = asyncer + + @property + def asyncer(self) -> asyncio_manager.AsyncioManager: + """The asyncio thread to which the handle belongs. + + The handle's async methods must be run using this object. + """ + return self._asyncer + + def map(self, fn: Callable[[_T], _S]) -> MailboxHandle[_S]: + """Returns a transformed handle. + + Methods on the returned handle call methods on this handle, but the + response type is derived using the given function. + + Args: + fn: A function to apply to this handle's result to get the new + handle's result. The function should be pure and fast. + """ + return _MailboxMappedHandle(self, fn) + + @abc.abstractmethod + def cancel(self) -> None: + """Cancel the handle, requesting any associated work to not complete. + + Any calls to `wait_or` or `wait_async` will raise `HandleAbandonedError` + if they aren't resolved within a short time. + + Cancellation is best-effort. Most exceptions are logged and suppressed. + """ + + @abc.abstractmethod + def wait_or(self, *, timeout: float | None) -> _T: + """Wait for a response or a timeout. + + It is an error to call this from an async function. + On error, including KeyboardInterrupt or a timeout, + the handle cancels itself. + + Args: + timeout: A finite number of seconds or None to never time out. + If less than or equal to zero, times out immediately unless + the response is available. + + Returns: + The response if it arrives before the timeout or has already arrived. + + Raises: + TimeoutError: If the timeout is reached. + HandleAbandonedError: If the handle becomes abandoned. + ServerResponseError: If the handle received an error response. + """ + + @abc.abstractmethod + async def wait_async(self, *, timeout: float | None) -> _T: + """Wait for a response or timeout. + + This must run in an `asyncio` event loop. + On error, including asyncio cancellation, KeyboardInterrupt or + a timeout, the handle cancels itself. + + Args: + timeout: A finite number of seconds or None to never time out. + + Returns: + The response if it arrives before the timeout or has already arrived. + + Raises: + TimeoutError: If the timeout is reached. + HandleAbandonedError: If the handle becomes abandoned. + ServerResponseError: If the handle received an error response. + """ + + +class _MailboxMappedHandle(Generic[_S], MailboxHandle[_S]): + """A mailbox handle whose result is derived from another handle.""" + + def __init__( + self, + handle: MailboxHandle[_T], + fn: Callable[[_T], _S], + ) -> None: + super().__init__(handle.asyncer) + self._handle = handle + self._fn = fn + + @override + def cancel(self) -> None: + self._handle.cancel() + + @override + def wait_or(self, *, timeout: float | None) -> _S: + return self._fn(self._handle.wait_or(timeout=timeout)) + + @override + async def wait_async(self, *, timeout: float | None) -> _S: + response = await self._handle.wait_async(timeout=timeout) + return self._fn(response) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/mailbox/response_handle.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/mailbox/response_handle.py new file mode 100644 index 0000000000000000000000000000000000000000..e985f15804c1ba887f6bb21cb4673844b8575e0f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/mailbox/response_handle.py @@ -0,0 +1,133 @@ +from __future__ import annotations + +import asyncio +import logging +import math +from collections.abc import Awaitable, Callable + +from typing_extensions import override + +from wandb.proto import wandb_server_pb2 as spb +from wandb.sdk.lib import asyncio_manager + +from .mailbox_handle import HandleAbandonedError, MailboxHandle, ServerResponseError + +_logger = logging.getLogger(__name__) + + +class MailboxResponseHandle(MailboxHandle[spb.ServerResponse]): + """A general handle for any ServerResponse.""" + + def __init__( + self, + address: str, + *, + asyncer: asyncio_manager.AsyncioManager, + cancel: Callable[[str], Awaitable[None]], + ) -> None: + super().__init__(asyncer) + + self._address = address + self._cancel_fn = cancel + + self._abandoned = False + self._response: spb.ServerResponse | None = None + + # Initialized on first use in the asyncio thread. + self._done_event: asyncio.Event | None = None + + async def deliver(self, response: spb.ServerResponse) -> None: + if self._abandoned: + return + + if self._response: + raise ValueError( + f"A response has already been delivered to {self._address}." + ) + + self._response = response + + if not self._done_event: + self._done_event = asyncio.Event() + self._done_event.set() + + @override + def cancel(self) -> None: + # Cancel on a best-effort basis and ignore exceptions. + async def impl() -> None: + try: + await self._cancel_fn(self._address) + except Exception: + _logger.exception("Failed to cancel request %r", self._address) + + try: + self.abandon() + self.asyncer.run_soon(impl) + except Exception: + _logger.exception( + "Failed to abandon and cancel request %r", + self._address, + ) + + def abandon(self) -> None: + """Indicate the handle will not receive a response. + + This causes any code blocked on `wait_or` or `wait_async` to raise + a `HandleAbandonedError` after a short time. + """ + + async def impl() -> None: + self._abandoned = True + + if not self._done_event: + self._done_event = asyncio.Event() + self._done_event.set() + + self.asyncer.run_soon(impl) + + @override + def wait_or(self, *, timeout: float | None) -> spb.ServerResponse: + return self.asyncer.run(lambda: self.wait_async(timeout=timeout)) + + @override + async def wait_async(self, *, timeout: float | None) -> spb.ServerResponse: + if timeout is not None and not math.isfinite(timeout): + raise ValueError("Timeout must be finite or None.") + + if not self._done_event: + self._done_event = asyncio.Event() + + try: + await asyncio.wait_for(self._done_event.wait(), timeout=timeout) + + except (asyncio.TimeoutError, TimeoutError) as e: + if response := self._response_or_error(): + return response + elif self._abandoned: + raise HandleAbandonedError() + else: + self.cancel() + raise TimeoutError( + f"Timed out waiting for response on {self._address}" + ) from e + + except: + self.cancel() + raise + + else: + if response := self._response_or_error(): + return response + + assert self._abandoned + raise HandleAbandonedError() + + def _response_or_error(self) -> spb.ServerResponse | None: + """Returns self._response, raising on ServerErrorResponse.""" + if not self._response: + return None + + if self._response.HasField("error_response"): + raise ServerResponseError(self._response.error_response.message) + + return self._response diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/mailbox/wait_with_progress.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/mailbox/wait_with_progress.py new file mode 100644 index 0000000000000000000000000000000000000000..2a10c709f952e28e08551c41dd7d2cc9bd23d4d9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/mailbox/wait_with_progress.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +import time +from collections.abc import Callable, Coroutine +from typing import Any, TypeVar, cast + +from wandb.sdk.lib import asyncio_compat + +from .mailbox_handle import MailboxHandle + +_T = TypeVar("_T") + + +def wait_with_progress( + handle: MailboxHandle[_T], + *, + timeout: float | None, + display_progress: Callable[[], Coroutine[Any, Any, None]], +) -> _T: + """Wait for a handle, possibly displaying progress to the user. + + Equivalent to passing a single handle to `wait_all_with_progress`. + """ + return wait_all_with_progress( + [handle], + timeout=timeout, + display_progress=display_progress, + )[0] + + +def wait_all_with_progress( + handle_list: list[MailboxHandle[_T]], + *, + timeout: float | None, + display_progress: Callable[[], Coroutine[Any, Any, None]], +) -> list[_T]: + """Wait for multiple handles, possibly displaying progress to the user. + + Args: + handle_list: The handles to wait for. + timeout: A number of seconds after which to raise a TimeoutError, + or None if this should never timeout. + display_progress: An asyncio function that displays progress to + the user. This function runs using the handles' AsyncioManager. + + Returns: + A list where the Nth item is the Nth handle's result. + + Raises: + ValueError: If the handles live in different asyncio threads. + TimeoutError: If the overall timeout expires. + HandleAbandonedError: If any handle becomes abandoned. + Exception: Any exception from the display function is propagated. + """ + if not handle_list: + return [] + + asyncer = handle_list[0].asyncer + for handle in handle_list: + if handle.asyncer is not asyncer: + raise ValueError("Handles have different AsyncioManagers.") + + start_time = time.monotonic() + + async def progress_loop_with_timeout() -> list[_T]: + async with asyncio_compat.cancel_on_exit(display_progress()): + if timeout is not None: + elapsed_time = time.monotonic() - start_time + remaining_timeout = timeout - elapsed_time + else: + remaining_timeout = None + + return await _wait_handles_async( + handle_list, + timeout=remaining_timeout, + ) + + return asyncer.run(progress_loop_with_timeout) + + +async def _wait_handles_async( + handle_list: list[MailboxHandle[_T]], + *, + timeout: float | None, +) -> list[_T]: + """Asynchronously wait for multiple mailbox handles. + + Just like _wait_handles. + """ + results: list[_T | None] = [None for _ in handle_list] + + async def wait_single(index: int) -> None: + handle = handle_list[index] + results[index] = await handle.wait_async(timeout=timeout) + + async with asyncio_compat.open_task_group() as task_group: + for index in range(len(handle_list)): + task_group.start_soon(wait_single(index)) + + # NOTE: `list` is not subscriptable until Python 3.10, so we use List. + return cast(list[_T], results) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/verify/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/verify/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/verify/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/verify/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f483f80258012c1402562ea32e59f38032d0be97 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/verify/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/verify/__pycache__/verify.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/verify/__pycache__/verify.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db862202a67430731b089955d9a833145309958c Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/verify/__pycache__/verify.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/verify/verify.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/verify/verify.py new file mode 100644 index 0000000000000000000000000000000000000000..1eeb7fd120f87f8672119441b5bbd51616197cd9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/verify/verify.py @@ -0,0 +1,556 @@ +"""Utilities for wandb verify.""" + +from __future__ import annotations + +import contextlib +import getpass +import io +import os +import time +from collections.abc import Callable +from functools import partial +from pathlib import Path +from typing import Any + +import click +import requests +from wandb_gql import gql + +import wandb +from wandb.sdk.artifacts.artifact import Artifact +from wandb.sdk.lib import runid + +from ...apis.internal import Api + +PROJECT_NAME = "verify" +GET_RUN_MAX_TIME = 10 +MIN_RETRYS = 3 +CHECKMARK = "\u2705" +RED_X = "\u274c" +ID_PREFIX = runid.generate_id() + + +def nice_id(name): + return ID_PREFIX + "-" + name + + +def print_results(failed_test_or_tests: str | list[str] | None, warning: bool) -> None: + if warning: + color = "yellow" + else: + color = "red" + if isinstance(failed_test_or_tests, str): + print(RED_X) # noqa: T201 + print(click.style(failed_test_or_tests, fg=color, bold=True)) # noqa: T201 + elif isinstance(failed_test_or_tests, list) and len(failed_test_or_tests) > 0: + print(RED_X) # noqa: T201 + print( # noqa: T201 + "\n".join( + [click.style(f, fg=color, bold=True) for f in failed_test_or_tests] + ) + ) + else: + print(CHECKMARK) # noqa: T201 + + +def check_host(host: str) -> bool: + if host in ("api.wandb.ai", "http://api.wandb.ai", "https://api.wandb.ai"): + print_results("Cannot run wandb verify against api.wandb.ai", False) + return False + return True + + +def check_logged_in(api: Api, host: str) -> bool: + print("Checking if logged in".ljust(72, "."), end="") # noqa: T201 + login_doc_url = "https://docs.wandb.ai/models/ref/cli/wandb-login" + fail_string = None + if api.api_key is None: + fail_string = ( + "Not logged in. Please log in using `wandb login`. See the docs: {}".format( + click.style(login_doc_url, underline=True, fg="blue") + ) + ) + # check that api key is correct + # TODO: Better check for api key is correct + else: + res = api.api.viewer() + if not res: + fail_string = ( + "Could not get viewer with default API key. " + f"Please relogin using `WANDB_BASE_URL={host} wandb login --relogin` and try again" + ) + + print_results(fail_string, False) + return fail_string is None + + +def check_secure_requests(url: str, test_url_string: str, failure_output: str) -> None: + # check if request is over https + print(test_url_string.ljust(72, "."), end="") # noqa: T201 + fail_string = None + if not url.startswith("https"): + fail_string = failure_output + print_results(fail_string, True) + + +def check_cors_configuration(url: str, origin: str) -> None: + print("Checking CORs configuration of the bucket".ljust(72, "."), end="") # noqa: T201 + fail_string = None + res_get = requests.options( + url, headers={"Origin": origin, "Access-Control-Request-Method": "GET"} + ) + + if res_get.headers.get("Access-Control-Allow-Origin") is None: + fail_string = ( + "Your object store does not have a valid CORs configuration, " + f"you must allow GET and PUT to Origin: {origin}" + ) + + print_results(fail_string, True) + + +def check_run(api: Api) -> bool: + print( # noqa: T201 + "Checking logged metrics, saving and downloading a file".ljust(72, "."), end="" + ) + failed_test_strings = [] + + # set up config + n_epochs = 4 + string_test = "A test config" + dict_test = {"config_val": 2, "config_string": "config string"} + list_test = [0, "one", "2"] + config = { + "epochs": n_epochs, + "stringTest": string_test, + "dictTest": dict_test, + "listTest": list_test, + } + # create a file to save + filepath = "./test with_special-characters.txt" + f = open(filepath, "w") + f.write("test") + f.close() + + with wandb.init( + id=nice_id("check_run"), + reinit=True, + config=config, + project=PROJECT_NAME, + ) as run: + run_id = run.id + entity = run.entity + logged = True + try: + for i in range(1, 11): + run.log({"loss": 1.0 / i}, step=i) + log_dict = {"val1": 1.0, "val2": 2} + run.log({"dict": log_dict}, step=i + 1) + except Exception: + logged = False + failed_test_strings.append( + "Failed to log values to run. Contact W&B for support." + ) + + try: + run.log({"HT%3ML ": wandb.Html('Link')}) + except Exception: + failed_test_strings.append( + "Failed to log to media. Contact W&B for support." + ) + + run.save(filepath) + public_api = wandb.Api() + prev_run = public_api.run(f"{entity}/{PROJECT_NAME}/{run_id}") + # raise Exception(prev_run.__dict__) + if prev_run is None: + failed_test_strings.append( + "Failed to access run through API. Contact W&B for support." + ) + print_results(failed_test_strings, False) + return False + for key, value in config.items(): + if prev_run.config.get(key) != value: + failed_test_strings.append( + "Read config values don't match run config. Contact W&B for support." + ) + break + if logged and ( + prev_run.history_keys["keys"]["loss"]["previousValue"] != 0.1 + or prev_run.history_keys["lastStep"] != 11 + or prev_run.history_keys["keys"]["dict.val1"]["previousValue"] != 1.0 + or prev_run.history_keys["keys"]["dict.val2"]["previousValue"] != 2 + ): + failed_test_strings.append( + "History metrics don't match logged values. Check database encoding." + ) + + if logged and prev_run.summary["loss"] != 1.0 / 10: + failed_test_strings.append( + "Read summary values don't match expected value. Check database encoding, or contact W&B for support." + ) + # TODO: (kdg) refactor this so it doesn't rely on an exception handler + try: + read_file = retry_fn(partial(prev_run.file, filepath)) + # There's a race where the file hasn't been processed in the queue, + # we just retry until we get a download + read_file = retry_fn(partial(read_file.download, replace=True)) + except Exception: + failed_test_strings.append( + "Unable to download file. Check SQS configuration, topic configuration and bucket permissions." + ) + + print_results(failed_test_strings, False) + return False + contents = read_file.read() + if contents != "test": + failed_test_strings.append( + "Contents of downloaded file do not match uploaded contents. Contact W&B for support." + ) + print_results(failed_test_strings, False) + return len(failed_test_strings) == 0 + + +def verify_manifest( + downloaded_manifest: dict[str, Any], + computed_manifest: dict[str, Any], + fails_list: list[str], +) -> None: + try: + for key in computed_manifest: + assert ( + computed_manifest[key]["digest"] == downloaded_manifest[key]["digest"] + ) + assert computed_manifest[key]["size"] == downloaded_manifest[key]["size"] + except AssertionError: + fails_list.append( + "Artifact manifest does not appear as expected. Contact W&B for support." + ) + + +def verify_digest( + downloaded: Artifact, computed: Artifact, fails_list: list[str] +) -> None: + if downloaded.digest != computed.digest: + fails_list.append( + "Artifact digest does not appear as expected. Contact W&B for support." + ) + + +def artifact_with_path_or_paths( + name: str, verify_dir: str | None = None, singular: bool = False +) -> Artifact: + art = wandb.Artifact(type="artsy", name=name) + # internal file + with open("verify_int_test.txt", "w") as f: + f.write("test 1") + f.close() + art.add_file(f.name) + if singular: + return art + if verify_dir is None: + verify_dir = "./" + with art.new_file("verify_a.txt") as f: + f.write("test 2") + if not os.path.exists(verify_dir): + os.makedirs(verify_dir) + with open(f"{verify_dir}/verify_1.txt", "w") as f: + f.write("1") + art.add_dir(verify_dir) + file3 = Path(verify_dir) / "verify_3.txt" + file3.write_text("3") + + # reference to local file + art.add_reference(file3.resolve().as_uri()) + + return art + + +def log_use_download_artifact( + artifact: Artifact, + alias: str, + name: str, + download_dir: str, + failed_test_strings: list[str], + add_extra_file: bool, +) -> tuple[bool, Artifact | None, list[str]]: + with wandb.init( + id=nice_id("log_artifact"), + reinit=True, + project=PROJECT_NAME, + config={"test": "artifact log"}, + ) as log_art_run: + if add_extra_file: + with open("verify_2.txt", "w") as f: + f.write("2") + f.close() + artifact.add_file(f.name) + + try: + log_art_run.log_artifact(artifact, aliases=alias) + except Exception as e: + failed_test_strings.append(f"Unable to log artifact. {e}") + return False, None, failed_test_strings + + with wandb.init( + id=nice_id("use_artifact"), + project=PROJECT_NAME, + config={"test": "artifact use"}, + ) as use_art_run: + try: + used_art = use_art_run.use_artifact(f"{name}:{alias}") + except Exception as e: + failed_test_strings.append(f"Unable to use artifact. {e}") + return False, None, failed_test_strings + try: + used_art.download(root=download_dir) + except Exception: + failed_test_strings.append( + "Unable to download artifact. Check bucket permissions." + ) + return False, None, failed_test_strings + + return True, used_art, failed_test_strings + + +def check_artifacts() -> bool: + print("Checking artifact save and download workflows".ljust(72, "."), end="") # noqa: T201 + failed_test_strings: list[str] = [] + + # test checksum + sing_art_dir = "./verify_sing_art" + alias = "sing_art1" + name = nice_id("sing-artys") + singular_art = artifact_with_path_or_paths(name, singular=True) + cont_test, download_artifact, failed_test_strings = log_use_download_artifact( + singular_art, alias, name, sing_art_dir, failed_test_strings, False + ) + if not cont_test or download_artifact is None: + print_results(failed_test_strings, False) + return False + try: + download_artifact.verify(root=sing_art_dir) + except ValueError: + failed_test_strings.append( + "Artifact does not contain expected checksum. Contact W&B for support." + ) + + # test manifest and digest + multi_art_dir = "./verify_art" + alias = "art1" + name = nice_id("my-artys") + art1 = artifact_with_path_or_paths(name, "./verify_art_dir", singular=False) + cont_test, download_artifact, failed_test_strings = log_use_download_artifact( + art1, alias, name, multi_art_dir, failed_test_strings, True + ) + if not cont_test or download_artifact is None: + print_results(failed_test_strings, False) + return False + if set(os.listdir(multi_art_dir)) != { + "verify_a.txt", + "verify_2.txt", + "verify_1.txt", + "verify_3.txt", + "verify_int_test.txt", + }: + failed_test_strings.append( + "Artifact directory is missing files. Contact W&B for support." + ) + + computed = wandb.Artifact("computed", type="dataset") + computed.add_dir(multi_art_dir) + verify_digest(download_artifact, computed, failed_test_strings) + + computed_manifest = computed.manifest.to_manifest_json()["contents"] + downloaded_manifest = download_artifact.manifest.to_manifest_json()["contents"] + verify_manifest(downloaded_manifest, computed_manifest, failed_test_strings) + + print_results(failed_test_strings, False) + return len(failed_test_strings) == 0 + + +def check_graphql_put(api: Api, host: str) -> tuple[bool, str | None]: + # check graphql endpoint using an upload + print("Checking signed URL upload".ljust(72, "."), end="") # noqa: T201 + failed_test_strings = [] + gql_fp = "gql_test_file.txt" + f = open(gql_fp, "w") + f.write("test2") + f.close() + with wandb.init( + id=nice_id("graphql_put"), + reinit=True, + project=PROJECT_NAME, + config={"test": "put to graphql"}, + ) as run: + run.save(gql_fp) + public_api = wandb.Api() + prev_run = public_api.run(f"{run.entity}/{PROJECT_NAME}/{run.id}") + if prev_run is None: + failed_test_strings.append( + "Unable to access previous run through public API. Contact W&B for support." + ) + print_results(failed_test_strings, False) + return False, None + # TODO: (kdg) refactor this so it doesn't rely on an exception handler + try: + read_file = retry_fn(partial(prev_run.file, gql_fp)) + url = read_file.url + read_file = retry_fn(partial(read_file.download, replace=True)) + except Exception: + failed_test_strings.append( + "Unable to read file successfully saved through a put request. Check SQS configurations, bucket permissions and topic configs." + ) + print_results(failed_test_strings, False) + return False, None + contents = read_file.read() + try: + assert contents == "test2" + except AssertionError: + failed_test_strings.append( + "Read file contents do not match saved file contents. Contact W&B for support." + ) + + print_results(failed_test_strings, False) + return len(failed_test_strings) == 0, url + + +def check_large_post() -> bool: + print( # noqa: T201 + "Checking ability to send large payloads through proxy".ljust(72, "."), end="" + ) + descy = "a" * int(10**7) + + username = getpass.getuser() + failed_test_strings = [] + query = gql( + """ + query Project($entity: String!, $name: String!, $runName: String!, $desc: String!){ + project(entityName: $entity, name: $name) { + run(name: $runName, desc: $desc) { + name + summaryMetrics + } + } + } + """ + ) + public_api = wandb.Api() + client = public_api._base_client + + try: + client._get_result( + query, + variable_values={ + "entity": username, + "name": PROJECT_NAME, + "runName": "", + "desc": descy, + }, + timeout=60, + ) + except Exception as e: + if ( + isinstance(e, requests.HTTPError) + and e.response is not None + and e.response.status_code == 413 + ): + failed_test_strings.append( + 'Failed to send a large payload. Check nginx.ingress.kubernetes.io/proxy-body-size is "0".' + ) + else: + failed_test_strings.append( + f"Failed to send a large payload with error: {e}." + ) + print_results(failed_test_strings, False) + return len(failed_test_strings) == 0 + + +def check_wandb_version(api: Api) -> None: + print("Checking wandb package version is up to date".ljust(72, "."), end="") # noqa: T201 + _, server_info = api.viewer_server_info() + fail_string = None + warning = False + max_cli_version = server_info.get("cliVersionInfo", {}).get("max_cli_version", None) + min_cli_version = server_info.get("cliVersionInfo", {}).get( + "min_cli_version", "0.0.1" + ) + + from packaging.version import parse + + if parse(wandb.__version__) < parse(min_cli_version): + fail_string = f"wandb version out of date, please run pip install --upgrade wandb=={max_cli_version}" + elif parse(wandb.__version__) > parse(max_cli_version): + fail_string = ( + "wandb version is not supported by your local installation. This could " + "cause some issues. If you're having problems try: please run `pip " + f"install --upgrade wandb=={max_cli_version}`" + ) + warning = True + + print_results(fail_string, warning) + + +def check_sweeps(api: Api) -> bool: + print("Checking sweep creation and agent execution".ljust(72, "."), end="") # noqa: T201 + failed_test_strings: list[str] = [] + + sweep_config = { + "method": "random", + "metric": {"goal": "minimize", "name": "score"}, + "parameters": { + "x": {"values": [0.01, 0.05, 0.1]}, + "y": {"values": [1, 2, 3]}, + }, + "name": "verify_sweep", + } + + try: + with contextlib.redirect_stdout(io.StringIO()): + sweep_id = wandb.sweep( + sweep=sweep_config, project=PROJECT_NAME, entity=api.default_entity + ) + except Exception as e: + failed_test_strings.append(f"Failed to create sweep: {e}") + print_results(failed_test_strings, False) + return False + + if not sweep_id: + failed_test_strings.append("Sweep creation returned an invalid ID.") + print_results(failed_test_strings, False) + return False + + try: + + def objective(config): + score = config.x**3 + config.y + return score + + def main(): + with wandb.init(project=PROJECT_NAME) as run: + score = objective(run.config) + run.log({"score": score}) + + wandb.agent(sweep_id, function=main, count=10) + except Exception as e: + failed_test_strings.append(f"Failed to run sweep agent: {e}") + print_results(failed_test_strings, False) + return False + + print_results(failed_test_strings, False) + return len(failed_test_strings) == 0 + + +def retry_fn(fn: Callable) -> Any: + ini_time = time.time() + res = None + i = 0 + while i < MIN_RETRYS or time.time() - ini_time < GET_RUN_MAX_TIME: + i += 1 + try: + res = fn() + break + except Exception: + time.sleep(1) + continue + return res diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_alerts.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_alerts.py new file mode 100644 index 0000000000000000000000000000000000000000..072547ab219e907efede3399d660817926074490 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_config.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_config.py new file mode 100644 index 0000000000000000000000000000000000000000..36be894b6c0e474797be643380567e36a3d26fa3 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_config.py @@ -0,0 +1,327 @@ +"""config.""" + +from __future__ import annotations + +import logging + +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.ai/models/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 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: set | None = 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) + and (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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_helper.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..5c5e5250f71b2b96db0e1300653ba1f94d62d682 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_init.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_init.py new file mode 100644 index 0000000000000000000000000000000000000000..704791c7bd0abf3ae35f39cb530e6ce14d8bbeee --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_init.py @@ -0,0 +1,1613 @@ +"""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/platform/launch). +""" + +from __future__ import annotations + +import contextlib +import dataclasses +import functools +import json +import logging +import os +import pathlib +import platform +import sys +import tempfile +import time +from collections.abc import Iterable, Iterator, Sequence +from typing import TYPE_CHECKING, Literal + +from typing_extensions import Any, Protocol, Self + +import wandb +import wandb.env +from wandb import env, trigger +from wandb.analytics import get_sentry +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_telemetry_pb2 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 .lib import SummaryDisabled, filesystem, module, paths, printer, telemetry +from .lib.deprecation import UNSET, DoNotSet, warn_and_record_deprecation +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: + from .interface.interface import InterfaceBase + +# Used to avoid printing the same notice repeatedly +# for multiple runs in the same process. +_shared_service_notice_shown = False + + +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._interface: InterfaceBase | None = None + + self._teardown_hooks: list[TeardownHook] = [] + self.notebook: wandb.jupyter.Notebook | None = None + + self.deprecated_features_used: list[tuple[Deprecated, str]] = [] + + @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 + + # Only pass an explicit key when the key was provided directly + # to ensure correct messaging in _login(). + explicit_key = init_settings.api_key + + wandb_login._login( + host=run_settings.base_url, + force=run_settings.force, + _silent=run_settings.quiet or run_settings.silent, + key=explicit_key, + update_api_key=explicit_key is None, + ) + + 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() + and 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.append( + ( + Deprecated(init__config_exclude_keys=True), + "config_exclude_keys is deprecated. Use" + " `config=wandb.helper.parse_config(config_object," + " exclude=('key',))` instead.", + ) + ) + if config_include_keys: + self.deprecated_features_used.append( + ( + Deprecated(init__config_include_keys=True), + "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._interface: + 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) + + self._logger.info("pausing backend") + self._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._interface is None: + return + + self._logger.info("resuming backend") + self._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", + "write_logs", + "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._interface = 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() + + global _shared_service_notice_shown + if not service.owns_service: + self._logger.info( + "Connected to an existing wandb-core service via WANDB_SERVICE" + ) + if not _shared_service_notice_shown: + run_printer.display( + "Using an existing wandb-core service via WANDB_SERVICE." + ) + _shared_service_notice_shown = True + + self._logger.info("sending inform_init request") + interface = service.inform_init( + settings=settings.to_proto(), + run_id=settings.run_id, # type: ignore + ) + 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: + warn_and_record_deprecation( + feature=deprecated_feature, + message=msg, + run=run, + ) + + self._logger.info("updated telemetry") + + run._set_library(self._wl) + run._set_backend(interface) + run._set_teardown_hooks(self._teardown_hooks) + + 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 = interface.deliver_run(run) + + try: + with progress.progress_printer( + run_printer, + default_text="Waiting for wandb.init()...", + ) as progress_printer: + result = wait_with_progress( + run_init_handle, + timeout=timeout, + display_progress=functools.partial( + progress.loop_printing_operation_stats, + progress_printer, + interface, + ), + ) + + except TimeoutError: + # 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))`." + ) from None + + 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") + + run_start_handle = 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 + + 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._interface = interface + + 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`" + ) + + _wl = wandb_setup.singleton() + logger = _wl._get_logger() + + service = _wl.ensure_service() + + try: + attach_settings, interface = 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, + } + ) + + 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(interface) + + attach_handle = 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, + 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, + anonymous: DoNotSet = UNSET, +) -> 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 `run.finish()` to + end the run, or use the run as a context manager to call it automatically: + + with wandb.init() as run: + ... # run.finish() executes at the end of the block + + 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. + 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}) + ``` + """ + 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 UNSET: + init_settings.anonymous = anonymous + 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.append( + ( + Deprecated(run__reinit_bool=True), + "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.finish_timeout > 0: + init_telemetry.feature.finish_timeout = True + if run_settings.finish_timeout_raises: + init_telemetry.feature.finish_timeout_raises = 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) + try_create_root_dir(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) + + 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) + + get_sentry().reraise(e) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_login.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_login.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bde7ef4da976a2db07b784a013ebe5136873f3 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_login.py @@ -0,0 +1,342 @@ +"""Log in to Weights & Biases. + +This authenticates your machine to log data to your account. +""" + +from __future__ import annotations + +import click + +import wandb +from wandb.errors import AuthenticationError, term +from wandb.sdk import wandb_setup +from wandb.sdk.lib import settings_file, wbauth +from wandb.sdk.lib.deprecation import UNSET, DoNotSet + +from ..apis import InternalApi + + +def login( + key: str | None = None, + relogin: bool | None = None, + host: str | None = None, + force: bool | None = None, + timeout: int | None = None, + verify: bool = False, + referrer: str | None = None, + anonymous: DoNotSet = UNSET, +) -> bool: + """Log into W&B. + + You generally don't have to use this because most W&B methods that need + authentication can log in implicitly. This is the programmatic counterpart + to the `wandb login` CLI. + + This updates global credentials for the session (affecting all wandb usage + in the current Python process after this call) and possibly the .netrc file. + + If the identity_token_file setting is set, like through the + WANDB_IDENTITY_TOKEN_FILE environment variable, then this is a no-op. + + Otherwise, if an explicit API key is provided, it is used and written to + the system .netrc file. If no key is provided, but the session is already + authenticated, then the session key is used for verification (if verify + is True) and the .netrc file is not updated. + + If none of the above is true, then this gets the API key from the first of: + + - The WANDB_API_KEY environment variable + - The api_key setting in a system or workspace settings file + - The .netrc file (either ~/.netrc, ~/_netrc or the path specified by the + NETRC environment variable) + - An interactive prompt (if available) + + Args: + key: The API key to use. + relogin: If true, get the API key from an interactive prompt, skipping + reading .netrc, environment variables, etc. + host: The W&B server URL to connect to. + force: If true, disallows selecting offline mode in the interactive + prompt. + timeout: Number of seconds to wait for user input in the interactive + prompt. This can be used as a failsafe if an interactive prompt + is incorrectly shown in a non-interactive environment. + verify: Verify the credentials with the W&B server and raise an + AuthenticationError on failure. + referrer: The referrer to use in the URL login request for analytics. + + 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. + """ + if anonymous is not UNSET: + term.termwarn( + "The anonymous parameter to wandb.login() has no effect and will" + + " be removed in future versions.", + repeat=False, + ) + + if wandb.run is not None: + term.termwarn("Calling wandb.login() after wandb.init() has no effect.") + return False + + global_settings = wandb_setup.singleton().settings + if global_settings._noop: + return False + if global_settings._offline and not global_settings.x_cli_only_mode: + term.termwarn("Unable to verify login in offline mode.") + return False + + if host: + host = host.rstrip("/") + + _update_system_settings( + global_settings.read_system_settings(), + host=host, + ) + + logged_in, _ = _login( + key=key, + relogin=relogin, + host=host, + force=force, + timeout=timeout, + verify=verify, + referrer=referrer or "models", + ) + return logged_in + + +def _update_system_settings( + system_settings: settings_file.SettingsFiles, + *, + host: str | None, +) -> None: + """Update the user's system settings files.""" + # 'anonymous' is deprecated; we clear it automatically for now. + system_settings.clear("anonymous", globally=True) + + if host: + if host == "https://api.wandb.ai": + system_settings.clear("base_url", globally=True) + else: + system_settings.set("base_url", host, globally=True) + + try: + system_settings.save() + except settings_file.SaveSettingsError as e: + wandb.termwarn(str(e)) + + +def _login( + *, + key: str | None = None, + relogin: bool | None = None, + host: str | None = None, + force: bool | None = None, + timeout: float | None = None, + verify: bool = False, + referrer: str = "models", + update_api_key: bool = True, + _silent: bool | None = None, +) -> tuple[bool, str | None]: + """Log in to W&B. + + Arguments are the same as for wandb.login() with the following additions: + + Args: + update_api_key: If true and an explicit API key is given, it will be + saved to the .netrc file. + _silent: If true, will not print any messages to the console. + + Returns: + A pair (is_successful, key). + """ + settings = wandb_setup.singleton().settings + + if host is None: + host_url = wbauth.HostUrl(settings.base_url, app_url=settings.app_url) + else: + host_url = wbauth.HostUrl(host) + + if relogin is None: + relogin = settings.relogin + if force is None: + force = settings.force + if timeout is None: + timeout = settings.login_timeout + if _silent is None: + _silent = settings.silent + + if wandb.util._is_kaggle() and not wandb.util._has_internet(): + term.termerror( + "To use W&B in kaggle you must enable internet in the settings" + + " panel on the right." + ) + return False, None + + if key: + auth: wbauth.Auth | None = _use_explicit_key( + key, + host=host_url, + settings=settings, + update_api_key=update_api_key, + silent=_silent, + ) + else: + auth = _find_or_prompt_for_key( + settings, + host=host_url, + force=force, + relogin=relogin, + referrer=referrer, + input_timeout=timeout, + ) + + if verify and isinstance(auth, wbauth.AuthApiKey): + _verify_login(key=auth.api_key, base_url=auth.host.url) + + wandb_setup.singleton().update_user_settings() + if not _silent: + _print_logged_in_message(settings, host=str(host_url)) + + if auth is None: + return False, None + elif isinstance(auth, wbauth.AuthApiKey): + return True, auth.api_key + else: + return True, None + + +def _use_explicit_key( + key: str, + settings: wandb.Settings, + *, + host: wbauth.HostUrl, + update_api_key: bool, + silent: bool, +) -> wbauth.Auth: + """Log in with an explicit key. + + Same arguments as `_login()`. + """ + if settings._notebook and not silent: + term.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." + ) + + auth = wbauth.AuthApiKey(host=host, api_key=key) + wbauth.use_explicit_auth(auth, source="wandb.login()") + + if update_api_key: + try: + wbauth.write_netrc_auth( + host=auth.host.url, + api_key=auth.api_key, + ) + except wbauth.WriteNetrcError as e: + wandb.termwarn(str(e)) + + return auth + + +def _find_or_prompt_for_key( + settings: wandb.Settings, + *, + host: wbauth.HostUrl, + force: bool, + relogin: bool, + referrer: str, + input_timeout: float | None, +) -> wbauth.Auth | None: + """Log in without an explicit key. + + Same arguments as `_login()`. + """ + timed_out = False + auth: wbauth.Auth | None = None + + try: + auth = wbauth.authenticate_session( + host=host, + source="wandb.login()", + no_offline=force, + no_create=force, + referrer=referrer, + input_timeout=input_timeout, + relogin=relogin, + ) + + except TimeoutError: + timed_out = True + + if not auth: + if timed_out: + term.termwarn("W&B disabled due to login timeout.") + settings.mode = "disabled" + else: + term.termlog("Using W&B in offline mode.") + settings.mode = "offline" + + return auth + + +def _verify_login(key: str, base_url: str) -> None: + from requests.exceptions import ConnectionError + + api = InternalApi( + api_key=key, + default_settings={"base_url": base_url}, + ) + + try: + is_api_key_valid = api.validate_api_key() + except ConnectionError as e: + raise AuthenticationError( + f"Unable to connect to {base_url} to verify API token." + ) from e + 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." + ) + + +def _print_logged_in_message(settings: wandb.Settings, *, host: str) -> None: + """Print a message telling the user they are logged in.""" + singleton = wandb_setup.singleton() + username = singleton._get_username() + + if username: + host_str = f" to {click.style(host, fg='green')}" if host else "" + + # check to see if we got an entity from the setup call or from the user + entity = settings.entity or singleton._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 singleton._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" + ) + term.termlog( + f"{login_state_str}. {login_info_str}", + repeat=False, + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_metric.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..5c42f74630bf0a15615461c24616d3038af8073d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_metric.py @@ -0,0 +1,114 @@ +"""metric.""" + +from __future__ import annotations + +import logging +from collections.abc import Callable, Sequence + +from wandb.proto import wandb_internal_pb2 as pb + +logger = logging.getLogger("wandb") + + +class Metric: + """Metric object.""" + + _callback: Callable[[pb.MetricRecord], None] | None + _name: str + _step_metric: str | None + _step_sync: bool | None + _hidden: bool | None + _summary: Sequence[str] | None + _goal: str | None + _overwrite: bool | None + + def __init__( + self, + name: str, + step_metric: str | None = None, + step_sync: bool | None = None, + hidden: bool | None = None, + summary: Sequence[str] | None = None, + goal: str | None = None, + overwrite: bool | None = 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) -> str | None: + return self._step_metric + + @property + def step_sync(self) -> bool | None: + return self._step_sync + + @property + def summary(self) -> tuple[str, ...] | None: + if self._summary is None: + return None + return tuple(self._summary) + + @property + def hidden(self) -> bool | None: + return self._hidden + + @property + def goal(self) -> str | None: + 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_require.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_require.py new file mode 100644 index 0000000000000000000000000000000000000000..e8935a71ceabea4cbec9e094753263b42269b004 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/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 collections.abc 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_require_helpers.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_require_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..bfb9f0c4f0bb74ca6278b4fcfe0ac1f02b3f8bc6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_require_helpers.py @@ -0,0 +1,45 @@ +import os +from collections.abc import Callable +from functools import wraps +from typing import Any, 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_run.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_run.py new file mode 100644 index 0000000000000000000000000000000000000000..4f1a38c4cc8f4e958fc1c543c23eea2e6c0c7bd9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_run.py @@ -0,0 +1,4095 @@ +from __future__ import annotations + +import contextlib +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 Callable, Mapping, Sequence +from dataclasses import dataclass, field +from datetime import datetime, timedelta, timezone +from enum import IntEnum +from types import TracebackType +from typing import TYPE_CHECKING, Concatenate, Literal, TextIO, TypeVar + +from typing_extensions import Any, NamedTuple, ParamSpec + +import wandb +import wandb.env +import wandb.util +from wandb import trigger +from wandb.analytics import get_sentry +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.wandb_internal_pb2 import ( + MetricRecord, + PollExitResponse, + Result, + RunRecord, +) +from wandb.proto.wandb_telemetry_pb2 import Deprecated +from wandb.sdk.lib import ( + asyncio_manager, + logger_capture, + run_messages, + run_stopping, + wb_logging, +) +from wandb.sdk.lib.filesystem import ( + FilesDict, + GlobStr, + LinkStats, + PolicyName, + link_or_copy_with_policy, + unlink_path, + validate_glob_path, +) +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 .data_types._dtypes import TypeRegistry +from .interface.interface import InterfaceBase +from .interface.summary_record import SummaryRecord +from .lib import ( + config_util, + deprecation, + 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_setup import _WandbSetup + +if TYPE_CHECKING: + from typing import TypedDict + + import torch # type: ignore [import-not-found] + + from wandb.apis.public import Api as PublicApi + from wandb.proto.wandb_internal_pb2 import ( + GetSummaryResponse, + SampledHistoryResponse, + ) + + from .artifacts.artifact import Artifact + from .interface.interface_queue import InterfaceQueue + from .wandb_settings import Settings + + 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. + """ + + _network_status_lock: threading.Lock + _network_status_handle: MailboxHandle[Result] | None + + def __init__( + self, + run_id: str, + asyncer: asyncio_manager.AsyncioManager, + interface: InterfaceBase, + settings: Settings, + retry_polling_interval: int = 5, + internal_messages_polling_interval: int = 10, + ) -> None: + self._run_id = run_id + self._interface = interface + 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._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._stop_checker = run_stopping.RunStopChecker( + asyncer, + interface, + settings.stop_fn or interrupt.interrupt_main, + ) + self._internal_messages = run_messages.RunMessages(asyncer, interface) + + def start(self) -> None: + self._stop_checker.start() + self._network_status_thread.start() + self._internal_messages.start() + + @staticmethod + def _abandon_status_check( + lock: threading.Lock, + handle: MailboxHandle[Result] | None, + ): + with lock: + if handle: + handle.cancel() + + 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 stop(self) -> None: + self._join_event.set() + self._abandon_status_check( + self._network_status_lock, + self._network_status_handle, + ) + + def join(self) -> None: + self.stop() + + self._stop_checker.stop_soon() + self._network_status_thread.join() + self._internal_messages.stop(timeout=5) # TODO: use finish timeout + + +_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: _P.args, **kwargs: _P.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: _P.args, **kwargs: _P.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: _P.args, **kwargs: _P.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/models/ref/python/functions/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/models/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/models/track/create-an-experiment) or + [`wandb.init`](https://docs.wandb.ai/models/ref/python/functions/init) API reference page + or more information. + + There is a another `Run` object in the + [`wandb.apis.public`](https://docs.wandb.ai/models/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/models/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] + + _interface: InterfaceBase | None + _internal_run_interface: 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 + + _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._interface = None + self._internal_run_interface = None + self._wl = None + # Avoid calling wandb.Api() repeatedly in _public_api() + self._cached_public_api: PublicApi | None = 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._poll_exit_handle = None + self._finish_timed_out = False + + # 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. + get_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._interface: + serialized = self._telemetry_obj.SerializeToString() + if serialized == self._telemetry_obj_flushed: + return + self._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._interface: + self._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._interface: + self._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._interface: + self._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/models/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. + + + """ + deprecation.warn_and_record_deprecation( + feature=Deprecated(run__project_name=True), + 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. + + + """ + deprecation.warn_and_record_deprecation( + feature=Deprecated(run__get_project_url=True), + 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 + """ + from wandb.sdk.artifacts._internal_artifact import InternalArtifact + + 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. + + + """ + deprecation.warn_and_record_deprecation( + feature=Deprecated(run__get_sweep_url=True), + 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. + + + """ + deprecation.warn_and_record_deprecation( + feature=Deprecated(run__get_url=True), + 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() or ipython.in_vscode_notebook(): + 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. + + If the run is being displayed in a VSCode notebook, + the string representation of the run is returned instead. + + + """ + if ipython.in_vscode_notebook(): + import html + + return html.escape(str(self)) + + 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._interface: + self._interface.publish_config(key=key, val=val, data=data) + + @_log_to_run + def _config_artifact_callback( + self, key: str, val: str | Artifact | dict + ) -> Artifact: + from wandb.apis import public + + # 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 = public_api._artifact_from_id(val["id"]) + + 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 = public_api._artifact_from_id(artifact_string) + 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 + @_attach + def pin_config_keys(self, keys: Sequence[str] = ()) -> None: + """Pin config keys to display in the References section on Run Overview. + + Pinned keys appear prominently above Notes on the Run Overview page. + String values are rendered as markdown; non-strings are rendered as + plain text. Calling this again replaces the previously pinned list. + + Args: + keys: Config key names to pin, matching keys set via + ``run.config``. These are exact key strings (dots and + slashes are treated literally, not as path separators). + Order is preserved and determines display order. + """ + self._set_config_wandb("pinned_keys", list(keys)) + + @_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._interface: + self._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._interface: + return {} + handle = self._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._interface: + self._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._interface: + return + files: FilesDict = dict(files=[(GlobStr(fname), "now")]) + self._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._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._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: + if self._interface: + # nowait=True so that this can be called from an asyncio context. + self._interface.publish_output(name, data, nowait=True) + + @_log_to_run + @_raise_if_finished + def _console_raw_callback(self, name: str, data: str) -> None: + # 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._interface: + # nowait=True so that this can be called from an asyncio context. + self._interface.publish_output_raw(name, data, nowait=True) + + @_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._interface: + self._interface.publish_tbdata(logdir, save, root_logdir) + + def _set_library(self, library: _WandbSetup) -> None: + self._wl = library + + def _set_backend(self, backend: InterfaceBase) -> None: + self._interface = backend + + def _set_internal_run_interface(self, interface: 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 + + get_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): + 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/models/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/platform/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/models/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/models/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/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". + + `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/models/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, commit=True) + ``` + + 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.ai/models/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 + @_attach + def write_logs(self, text: str) -> None: + """Write text to the run's Logs tab. + + Use `write_logs` to directly write text to the Logs tab instead of + relying on automatic stdout/stderr capture. Calls after the run has + finished are silently ignored. + + Consider using the `capture_loggers` setting which integrates with + Python's `logging` module. + + Args: + text: The text to write. A trailing newline is added if not present. + """ + if self._is_finished or not self._interface: + return + + if not text.endswith("\n"): + text += "\n" + + # nowait=True is needed because we may be in the asyncio thread. + # + # write_logs() is called by LoggerHandler, which could be attached + # to the root logger, which may get logs in an asyncio context. + self._interface.publish_output_logger(text, nowait=True) + + @_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]: + """Materialize matched files into the run's files/ dir for syncing. + + Strategy: + 1) If settings.symlink is True, try symlink. + 2) Else (or if symlink fails), try hardlink (same-volume files). + 3) Else copy and, if requested policy == "live", downgrade those files to "now". + + Args: + glob_path: Absolute path glob pattern for files to save. + base_path: Base path to determine relative directory structure. + policy: Upload policy - "live", "now", or "end". + + Returns: + List of absolute paths to files in the wandb run directory. + + Raises: + ValueError: If glob_path is invalid relative to base_path. + """ + validate_glob_path(glob_path, base_path) + + relative_glob = glob_path.relative_to(base_path) + relative_glob_str = GlobStr(str(relative_glob)) + + with telemetry.context(run=self) as tel: + tel.feature.save = True + + files_root = pathlib.Path(self._settings.files_dir) + preexisting = set(files_root.glob(relative_glob_str)) + + # Expand sources deterministically. + src_paths = [ + pathlib.Path(p).absolute() + for p in sorted(glob.glob(GlobStr(str(base_path / relative_glob_str)))) + ] + + stats = LinkStats() + publish_entries = [] + created_targets = set() + + for src in src_paths: + # Preserve directory structure under base_path. + rel = pathlib.Path(*src.parts[len(base_path.parts) :]) + dst = files_root / rel + created_targets.add(dst) + + # If already the same file, just publish with requested policy. + with contextlib.suppress(OSError): + if dst.exists() and src.samefile(dst): + publish_entries.append( + (GlobStr(str(dst.relative_to(files_root))), policy) + ) + continue + + dst.parent.mkdir(parents=True, exist_ok=True) + unlink_path(dst) + + effective_policy = link_or_copy_with_policy( + self._settings, src, dst, policy, stats + ) + publish_entries.append( + (GlobStr(str(dst.relative_to(files_root))), effective_policy) + ) + + # Include pre-existing matches we didn't touch. + for p in sorted(preexisting): + if p not in created_targets: + publish_entries.append( + (GlobStr(str(p.relative_to(files_root))), policy) + ) + + stats.emit_warnings() + + files_dict: FilesDict = {"files": publish_entries} + if self._interface: + self._interface.publish_files(files_dict) + + abs_targets = {files_root / pathlib.Path(g) for (g, _pol) in publish_entries} + return [str(p) for p in sorted(abs_targets)] + + @_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: + deprecation.warn_and_record_deprecation( + feature=Deprecated(run__finish_quiet=True), + message=( + "The `quiet` argument to `wandb.run.finish()` is deprecated, " + "use `wandb.Settings(quiet=...)` to set this instead." + ), + run=self, + ) + + self._finish(exit_code) + + @_log_to_run + def _finish( + self, + exit_code: int | None = None, + ) -> None: + """Finish the run and clean up all its resources. + + Raises: + TimeoutError: If a finish timeout was set and the run timed out + before uploading fully. + """ + 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() + get_sentry().end_session() + + if self._finish_timed_out and self.settings.finish_timeout_raises: + # NOTE: A timeout is theoretically possible in offline mode, so + # it's best not to assume what it implies (like "didn't finish + # uploading data"). + raise TimeoutError("Timed out finishing run.") + + @_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._interface: + return RunStatus() + + handle_run_status = self._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._interface 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 and 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, + 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 _begin_capturing_loggers(self) -> None: + """Begin capturing logger output if configured.""" + capture_loggers = self._settings.capture_loggers + if not capture_loggers: + return + + for name, level in capture_loggers.items(): + handler = logger_capture.LoggerHandler(self, level) + logger = logging.getLogger(name) + logger.addHandler(handler) + + def unregister( + logger: logging.Logger = logger, + handler: logging.Handler = handler, + ) -> None: + logger.removeHandler(handler) + + self._teardown_hooks.append( + TeardownHook( + call=unregister, + stage=TeardownStage.EARLY, + ) + ) + + def _on_start(self) -> None: + assert self._wl + + 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 and self._interface: + from wandb.util import working_set + + logger.debug( + "Saving list of pip packages installed into the current environment" + ) + self._interface.publish_python_packages(working_set()) + + if self._interface and not self._settings._offline: + assert self._settings.run_id + self._run_status_checker = RunStatusChecker( + self._settings.run_id, + asyncer=self._wl.asyncer, + interface=self._interface, + settings=self._settings, + ) + self._run_status_checker.start() + + self._console_start() + self._begin_capturing_loggers() + 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) and 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: + from wandb.sdk.artifacts._internal_artifact import InternalArtifact + from wandb.sdk.internal import job_builder + + 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 + + def _on_finish(self) -> None: + """Shut down the run. + + This sends and waits for an exit record to mark the run complete. + It also shuts down the run status checker, fetches some final + info like the run summary and any messages (storing the results + as attributes), and unregisters telemetry import hooks. + + Sets `_finish_timed_out` if a finish timeout was set and the run + timed out before uploading completely. + + TODO: Refactor this method, it does too much and not enough (some + shutdown steps happen outside it). + """ + 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._interface + + exit_handle = self._interface.deliver_exit(self._exit_code) + + with progress.progress_printer( + self._printer, + default_text="Finishing up...", + ) as progress_printer: + # Wait for the run to complete. + result = wait_with_progress( + exit_handle, + timeout=None, + display_progress=functools.partial( + progress.loop_printing_operation_stats, + progress_printer, + self._interface, + ), + ) + + self._finish_timed_out = result.exit_result.timed_out + + poll_exit_handle = self._interface.deliver_poll_exit() + result = poll_exit_handle.wait_or(timeout=None) + self._poll_exit_response = result.response.poll_exit_response + + # dispatch all our final requests + + final_summary_handle = self._interface.deliver_get_summary() + sampled_history_handle = self._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._interface: + self._interface.join() + + 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: + deprecation.warn_and_record_deprecation( + feature=Deprecated(run__define_metric_copy=True), + message="define_metric(summary='copy') is deprecated and will be removed.", + run=self, + ) + + if (summary and "best" in summary) or goal is not None: + deprecation.warn_and_record_deprecation( + feature=Deprecated(run__define_metric_best_goal=True), + message="define_metric(summary='best', goal=...) is deprecated and will be removed. " + "Use define_metric(summary='min') or define_metric(summary='max') instead.", + run=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 artifact to a collection. + + The term “link” refers to pointers that connect where W&B stores the + artifact and where the artifact is accessible in the registry. W&B + does not duplicate artifacts when you link an artifact to a collection. + + View linked artifacts in the Registry UI for the specified collection. + + Args: + artifact: The artifact object to link to the collection. + target_path: The path of the collection. Path consists of the prefix + "wandb-registry-" along with the registry name and the + collection name `wandb-registry-{REGISTRY_NAME}/{COLLECTION_NAME}`. + aliases: Add one or more aliases to the linked artifact. The + "latest" alias is automatically applied to the most recent artifact + you link. + + Returns: + The linked artifact. + + """ + from .artifacts._validators import ArtifactPath + + 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 + ("entity" or "entity/project"). 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() + ``` + + """ + from wandb.apis import internal + from wandb.sdk.artifacts.artifact import Artifact + + 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: + deprecation.warn_and_record_deprecation( + feature=Deprecated(run__use_artifact_use_as=True), + 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._interface: + self._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: + from .artifacts._validators import validate_aliases, validate_tags + + 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 + ) + + artifact.metadata = {**artifact.metadata} # triggers validation + + artifact.distributed_id = distributed_id + self._assert_can_log_artifact(artifact) + if self._interface: + if not self._settings._offline: + handle = self._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._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: + if self._cached_public_api is not None: + return self._cached_public_api + + # NOTE: PublicApi is only for type checking, still need to import + from wandb.apis import public + + 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 "" + overrides["base_url"] = self._settings.base_url + + self._cached_public_api = public.Api(overrides, api_key=self._settings.api_key) + return self._cached_public_api + + # TODO(jhr): annotate this + def _assert_can_log_artifact(self, artifact) -> None: # type: ignore + import requests + + from wandb.sdk.artifacts.artifact import Artifact + + 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]]: + from wandb.sdk.artifacts.artifact import Artifact + + 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, 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._interface: + self._interface.publish_alert(title, text, level_str, wait_duration) + + def __enter__(self) -> Run: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + 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) + + @_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._interface: + self._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._interface: + return {} + + handle = self._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)}", + ) + + # ------------------------------------------------------------------------------ + # 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, + *, + 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) + + @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:") + + +# 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. + """ + from wandb.apis import public + + 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 and 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_settings.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..1a0cfd7a044b1de75e4b657a4dfa2699dcc9d33f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_settings.py @@ -0,0 +1,2293 @@ +from __future__ import annotations + +import json +import logging +import os +import pathlib +import platform +import re +import shutil +import socket +import sys +import traceback +from collections.abc import Sequence +from datetime import datetime +from typing import Any, Dict, List, Literal, Optional, Tuple, Union +from urllib.parse import quote, unquote + +from google.protobuf.wrappers_pb2 import BoolValue, DoubleValue, Int32Value, StringValue +from pydantic import BaseModel, ConfigDict, Field +from typing_extensions import Callable, Self + +import wandb +from wandb import env, util +from wandb._pydantic import ( + AliasChoices, + ValidationError, + computed_field, + field_validator, + model_validator, +) +from wandb.errors import UsageError +from wandb.proto import wandb_settings_pb2 +from wandb.sdk.lib import deprecation, settings_file, urls + +from .lib import credentials, filesystem, ipython +from .lib.run_moment import RunMoment + + +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 = ( + "anonymous", + "app_url_override", + "capture_loggers", + "files_dir", + "finish_timeout_raises", + "max_end_of_run_history_metrics", + "max_end_of_run_summary_metrics", + "reinit", + "stop_fn", + "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_media_symlink: bool = False + """Whether to symlink media files to the run directory. + + If true, media files will be symlinked or hardlinked to the + run directory instead of copied. This may result in faster + logging and reduced disk usage. However, deleting or modifying + the original files before upload to the W&B server will be + reflected in the uploaded data. + """ + + 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: deprecation.DoNotSet = Field( + default=deprecation.UNSET, + exclude=True, + ) + """Deprecated and will be removed.""" + + 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.""" + + app_url_override: Optional[str] = None + """Override for the 'app' URL for the W&B UI. + + The `app_url` is normally computed based on `base_url`, but this can be + used to set it explicitly. + + WANDB_APP_URL is the corresponding environment variable. + """ + + 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 + """Enable multipart console logging. + + When True, the SDK writes console output to timestamped files + under the `logs/` directory instead of a single `output.log`. + + Each part is uploaded as soon as it is closed, giving users live + access to logs while the run is active. Rollover cadence is + controlled by `console_chunk_max_bytes` and/or `console_chunk_max_seconds`. + If both limits are `0`, all logs are uploaded once at run finish. + + Note: Uploaded chunks are immutable; terminal control sequences + that modify previous lines (e.g., progress bars using carriage returns) + only affect the current chunk. + """ + + console_chunk_max_bytes: int = 0 + """Size-based rollover threshold for multipart console logs, in bytes. + + Starts a new console log file when the current part reaches this + size. Has an effect only when `console_multipart` is `True`. + Can be combined with `console_chunk_max_seconds`; whichever limit is + hit first triggers the rollover. A value of `0` disables the + size-based limit. + """ + + console_chunk_max_seconds: int = 0 + """Time-based rollover threshold for multipart console logs, in seconds. + + Starts a new console log file after this many seconds have elapsed + since the current part began. Requires `console_multipart` to be + `True`. May be used with `console_chunk_max_bytes`; the first limit + reached closes the part. A value of `0` disables the time-based + limit. + """ + + capture_loggers: Optional[dict[str, str]] = None + """Names of Python loggers to capture into the run's Logs tab. + + A mapping of logger name to minimum log level. When set, wandb installs a + logging.Handler on each named logger and removes it when the run finishes. + Log records emitted by those loggers are published as console output to the + run, similar to stdout/stderr capture. + + Log records are formatted the same as `logging.basicConfig()`, like + `INFO:my_module:Some message.` This is not currently customizable. + + To capture all logs, pass the name of the root logger, which is 'root'. + + This is independent of the `console` setting: both can be active + simultaneously. + + Example: + ```python + wandb.init( + settings=wandb.Settings( + console="off", + capture_loggers={ + "my_app": "INFO", + "my_app.training": "ERROR", + }, + ), + ) + ``` + """ + + 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_git_fork_point: bool = True + """Whether to disable inferring fork point from remote branches + + When set to True, the SDK will use the latest commit from the upstream + branch, if one is set. Otherwise skip generating the diff patch. + + When set to False, the SDK will try to use the latest commit from the upstream branch, + if one is set. + Otherwise, it will find the closest commit from all remote branches. + This may impact performance for repos with many upstream branches. + """ + + 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.""" + + finish_timeout: float = 0.0 + """Time in seconds to wait for data to upload at the end of a run. + + Setting this can limit costs caused by slow uploads to W&B at the end of a + run, with the trade-off that the run will be marked crashed and may be + missing some data. The default is for `run.finish()` to block until all + data finishes uploading. + + If this is set to a number greater than zero, W&B gives up on uploading a + run's data after this many seconds at the end of a run, unblocking your + script. After some time, the run becomes Crashed or Failed in the UI. Any + unuploaded data is still stored on disk and can be uploaded with `wandb + sync`. + + Use the `finish_timeout_raises` setting to raise an error in addition to + printing a warning message. + + Runs shut down by `wandb.teardown()` (which automatically runs at the end + of a script in an atexit hook) will also respect this setting. + """ + + finish_timeout_raises: bool = False + """Whether to raise a TimeoutError if finish_timeout expires. + + Using this together with the `finish_timeout` setting causes `run.finish()` + to raise a TimeoutError after a timeout in addition to printing a message. + + Note that `run.finish()` is called implicitly when using a Run as a context + manager: + + with wandb.init() as run: + ... # run.finish() executes at the end of the `with` block + + This does not cause `wandb.teardown()` to raise an error (since it runs + at the end of a script anyway). + """ + + 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.""" + + stop_fn: Optional[Callable[[], None]] = None + """A callback to execute to stop the run. + + A run can be stopped through the web UI, or after a fatal error + (if configured via a setting). + + By default, to stop a run, W&B sends a SIGINT to the main thread. + Set this callback to override this behavior, like to use a different + signal or to take some other action before interrupting. + + The callback runs in a separate thread. It runs soon after a stop is + requested, but not immediately. + """ + + 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. + + """ + + stop_on_fatal_error: bool = False + """Whether to stop the run after a fatal error. + + After W&B hits an unrecoverable error while uploading data, it prints + a message and stops uploading, but still allows logging more data. + This is usually desirable: your training metrics get stored on disk + and can be recovered using `wandb sync`, even if they aren't uploaded. + + This is not useful if your files get deleted after training. + In that case, setting this to True will stop the run after a fatal error, + as if the stop button was pressed in the web UI. + """ + + 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: platform.system() != "Windows") + """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.""" + + use_dot_wandb: Optional[bool] = None + """Whether to use a hidden `.wandb` or visible `wandb` directory for run data. + + If True, the SDK uses `.wandb`. If False, `wandb`. + If not set, defaults to `.wandb` if it already exists, otherwise `wandb`. + """ + + 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_stats_no_cgroup: bool = False + """Disable cgroup v2 CPU and memory limits for system metric percentages.""" + + 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 + + @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 + + # Field validators. + @field_validator("anonymous", mode="after") + @classmethod + def validate_anonymous(cls, value: object) -> object: + if value is not deprecation.UNSET: + wandb.termwarn( + "The anonymous setting has no effect and will be removed" + + " in a future version.", + repeat=False, + ) + + return value + + @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. + + + """ + urls.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("console_chunk_max_bytes", mode="after") + @classmethod + def validate_console_chunk_max_bytes(cls, value): + """Validate the console_chunk_max_bytes value. + + + """ + if value < 0: + raise ValueError("console_chunk_max_bytes must be non-negative") + + return value + + @field_validator("console_chunk_max_seconds", mode="after") + @classmethod + def validate_console_chunk_max_seconds(cls, value): + """Validate the console_chunk_max_seconds value. + + + """ + if value < 0: + raise ValueError("console_chunk_max_seconds must be non-negative") + + return value + + @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) + + values = values.data + + 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 + urls.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 + urls.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) + + values = values.data + + 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): + urls.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() + return not ( + not lambda_bootstrap + or not hasattr(lambda_bootstrap, "handle_event_request") + ) + + @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 app_url(self) -> str: + """The URL for the W&B UI, usually https://wandb.ai. + + This is different from `base_url` (like https://api.wandb.ai) which + is used to access W&B APIs programmatically. + """ + return self.app_url_override or util.api_to_app_url(self.base_url) + + @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 "" + + return project_url + + @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 "" + + # 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)}" + + @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 "" + + return f"{project_url}/sweeps/{quote(self.sweep_id or '')}" + + @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.""" + if self.use_dot_wandb is None: + use_dot = pathlib.Path(self.root_dir, ".wandb").exists() + else: + use_dot = self.use_dot_wandb + + dirname = ".wandb" if use_dot else "wandb" + return str(pathlib.Path(self.root_dir, dirname).expanduser()) + + # 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 read_system_settings(self) -> settings_file.SettingsFiles: + """Read settings from the workspace and global settings files. + + The files are determined by the settings_system and settings_workspace + settings. + + The resulting object is a snapshot of the system settings at the time + this function is used and does not reflect the settings on this Settings + object. It can be used to update the files, and it should be short-lived + since it does not reflect external changes to the files. + + Updating the settings files does not update this Settings instance + and vice versa. + + + """ + local_settings = pathlib.Path(self.settings_workspace) + + if self.settings_system: + global_settings = pathlib.Path(self.settings_system) + else: + global_settings = None + + return settings_file.SettingsFiles( + global_settings=global_settings, + local_settings=local_settings, + ) + + def update_from_system_settings(self) -> None: + """Load settings from the settings files. + + If settings files contain invalid settings, prints and suppresses + the error. + + + """ + system_settings = self.read_system_settings() + + if len(system_settings.sources) == 0: + return + elif len(system_settings.sources) == 1: + source_string = str(system_settings.sources[0]) + else: + source_string = "\n" + "\n".join( + f" {source}" for source in system_settings.sources + ) + + # Print at the start so that users can diagnose uncaught exceptions. + if not self.quiet and not self.silent and not env.is_silent(): + printed_sources = True + wandb.termlog(f"Loading settings from {source_string}") + else: + printed_sources = False + + try: + parsed_settings = _parse_system_settings(system_settings) + except Exception as e: + if not printed_sources: + wandb.termerror(f"Failed to load settings from {source_string}") + + if isinstance(e, ValidationError): + # Pydantic ValidationErrors have detailed messages that we can + # print without a stack trace. + wandb.termerror(str(e)) + + else: + # For all other errors, we need to dump a stack trace to make + # sure they're debuggable. + tb = traceback.format_exception(type(e), e, e.__traceback__) + wandb.termerror("".join(tb)) + + return + + # We parse and set in different steps so that we do not partially + # apply a broken settings file. + # + # Note that this runs validation functions a second time, but we expect + # them to succeed. + self.update_from_settings(parsed_settings) + + 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 = { + env.APP_URL: "app_url_override", + "WANDB_SERVICE_TRANSPORT": "x_service_transport", + env.DIR: "root_dir", + env.NAME: "run_name", + env.NOTES: "run_notes", + env.TAGS: "run_tags", + env.JOB_TYPE: "run_job_type", + env.HTTP_TIMEOUT: "x_graphql_timeout_seconds", + env.FILE_PUSHER_TIMEOUT: "x_file_transfer_timeout_seconds", + env.USER_EMAIL: "email", + } + + 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 not in self.__dict__: + continue + + if key in ("ignore_globs", "run_tags"): + value = value.split(",") + + if value is None: + continue + + 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: + self._setup_code_paths(program) + 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 filesystem.are_paths_on_same_drive( + pathlib.Path(root), pathlib.Path(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 + + def _project_url_base(self) -> str: + """Construct the base URL for the project.""" + if not all([self.entity, self.project]): + return "" + + return f"{self.app_url}/{quote(self.entity or '')}/{quote(self.project or '')}" + + @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) + + def _setup_code_paths(self, program: str): + """Sets the program_abspath and program_relpath settings.""" + if self._jupyter and self.x_jupyter_root: + self._infer_code_paths_for_jupyter(program) + else: + self._infer_code_path_for_program(program) + + def _infer_code_path_for_program(self, program: str): + """Finds the program's absolute and relative paths.""" + from .lib.gitlib import GitRepo + + 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 + + def _infer_code_paths_for_jupyter(self, program: str): + """Find the notebook's absolute and relative paths. + + Since the notebook's execution environment + is not the same as the current working directory. + We utilize the metadata provided by the jupyter server. + """ + if not self.x_jupyter_root or not program: + return None + + self.program_abspath = os.path.abspath( + os.path.join(self.x_jupyter_root, program) + ) + self.program_relpath = program + + +def _parse_system_settings( + system_settings: settings_file.SettingsFiles, +) -> Settings: + """Validate settings from a settings file. + + Returns: + A validated Settings object. + + Raises: + ValidationError: on invalid data. + Exception: arbitrary errors can occur when constructing Settings. + """ + fields: dict[str, Any] = dict() + + value: object # Can be transformed arbitrarily. + for key, value in system_settings.all().items(): + if key == "ignore_globs": + fields[key] = value.split(",") + + elif key == "anonymous": + wandb.termwarn( + "Deprecated setting 'anonymous' has no effect and will be" + + " removed in a future version of wandb." + + " Please delete it manually or by running `wandb login`" + + " to avoid errors.", + repeat=False, + ) + fields[key] = deprecation.UNSET + + elif key in ("settings_system", "root_dir"): + wandb.termwarn( + f"Ignoring setting {key!r} which is not allowed in a settings file." + + " Please delete it manually to avoid errors in the future." + ) + + else: + fields[key] = value + + # NOTE: Field validators must raise ValueError for Pydantic to wrap them + # in a ValidationError. Other kinds of errors will bubble up unaltered. + # + # Unfortunately, some validators return a UsageError, which has special + # handling in the CLI and may require care to change. + return Settings(**fields) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_setup.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..42a4f43601f2638491eaac678395b41c403d16d2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_setup.py @@ -0,0 +1,597 @@ +"""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 + +import wandb +import wandb.integration.sagemaker as sagemaker +from wandb.env import CONFIG_DIR +from wandb.errors import UsageError +from wandb.sdk.lib import asyncio_manager, import_hooks, wb_logging + +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 = 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._connection_lock = threading.Lock() + + 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. + """ + from wandb.sdk.wandb_settings import Settings + + self._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() + ) + self._settings.update_from_system_settings() + + # 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 + + 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) -> 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) -> 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 + + with self._connection_lock: + 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 + + # Update after configuring the _singleton. + # + # Do not hold the lock while updating credentials, as it writes back + # to settings. + if settings: + _maybe_update_credentials(settings) + + return current_singleton + + +def _maybe_update_credentials(settings: Settings) -> None: + """Update session credentials if they're set on settings. + + This is a refactoring step for moving credentials into a separate module + and out of settings. If a user calls `wandb.setup()` explicitly with an + api_key or other credential, this overwrites credentials that might have + been set by a call to `wandb.login()`. + """ + if settings.api_key and settings.identity_token_file: + raise UsageError( + "The api_key and identity_token_file settings cannot be used together." + ) + + from wandb.sdk.lib import wbauth + + if settings.api_key: + wbauth.use_explicit_auth( + wbauth.AuthApiKey( + host=wbauth.HostUrl(settings.base_url, app_url=settings.app_url), + api_key=settings.api_key, + ), + source="wandb.setup()", + ) + + elif settings.identity_token_file: + wbauth.use_explicit_auth( + wbauth.AuthIdentityTokenFile( + host=wbauth.HostUrl(settings.base_url, app_url=settings.app_url), + path=settings.identity_token_file, + credentials_file=settings.credentials_file, + ), + source="wandb.setup()", + ) + + +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 + + from wandb.sdk.lib import wbauth + + with _singleton_lock: + orig_singleton = _singleton + _singleton = None + + if orig_singleton: + orig_singleton._teardown(exit_code=exit_code) + + wbauth.unauthenticate_session(update_settings=False) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_summary.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..26d9a3147890c0877cab334199957807ca4fcda8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_summary.py @@ -0,0 +1,149 @@ +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() 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: dict): + 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: 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_sweep.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_sweep.py new file mode 100644 index 0000000000000000000000000000000000000000..40fcc7e6bcc495a6064aad8221e300e8a76e27ab --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_sweep.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +import urllib.parse +from collections.abc import Callable +from typing import TYPE_CHECKING + +import wandb +from wandb import env + +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: dict | Callable, + entity: str | None = None, + project: str | None = None, + prior_runs: list[str] | None = 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/models/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. + """ + from wandb.apis import InternalApi + from wandb.sdk.launch.sweeps.utils import handle_sweep_config_violations + + 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: str | dict | None = None, + entity: str | None = None, + project: str | None = 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_watch.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_watch.py new file mode 100644 index 0000000000000000000000000000000000000000..b768e1937a11f51a14dee5a671d9e8ecd0091a01 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sdk/wandb_watch.py @@ -0,0 +1,147 @@ +"""watch.""" + +from __future__ import annotations + +import logging +from collections.abc import Sequence +from typing import TYPE_CHECKING + +try: + from typing import Literal +except ImportError: + from typing 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/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sync/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sync/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..92213239a7fd075123dfe49928241b99640abc0b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sync/__init__.py @@ -0,0 +1,3 @@ +"""module sync.""" + +from .sync import SyncManager, get_run_from_path, get_runs diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sync/sync.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sync/sync.py new file mode 100644 index 0000000000000000000000000000000000000000..e1dc3b2bc7215d57d0497e1aa0db77a57458e983 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/sync/sync.py @@ -0,0 +1,456 @@ +"""sync.""" + +from __future__ import annotations + +import atexit +import datetime +import fnmatch +import os +import queue +import sys +import tempfile +import threading +import time +from urllib.parse import quote as url_quote + +import wandb +from wandb.proto import wandb_internal_pb2 # type: ignore +from wandb.sdk.interface.interface_queue import InterfaceQueue +from wandb.sdk.internal import context, datastore, handler, sender, tb_watcher +from wandb.sdk.internal.settings_static import SettingsStatic +from wandb.sdk.lib import filesystem +from wandb.util import check_and_warn_old + +WANDB_SUFFIX = ".wandb" +SYNCED_SUFFIX = ".synced" +TFEVENT_SUBSTRING = ".tfevents." + + +class _LocalRun: + def __init__(self, path, synced=None): + self.path = path + self.synced = synced + self.offline = os.path.basename(path).startswith("offline-") + self.datetime = datetime.datetime.strptime( + os.path.basename(path).split("run-")[1].split("-")[0], "%Y%m%d_%H%M%S" + ) + + def __str__(self): + return self.path + + +class SyncThread(threading.Thread): + def __init__( + self, + sync_list, + project=None, + entity=None, + run_id=None, + job_type=None, + view=None, + verbose=None, + mark_synced=None, + app_url=None, + sync_tensorboard=None, + log_path=None, + append=None, + skip_console=None, + replace_tags=None, + ): + threading.Thread.__init__(self) + self._sync_list = sync_list + self._project = project + self._entity = entity + self._run_id = run_id + self._job_type = job_type + self._view = view + self._verbose = verbose + self._mark_synced = mark_synced + self._app_url = app_url + self._sync_tensorboard = sync_tensorboard + self._log_path = log_path + self._append = append + self._skip_console = skip_console + self._replace_tags = replace_tags or {} + + self._tmp_dir = tempfile.TemporaryDirectory() + atexit.register(self._tmp_dir.cleanup) + + def _parse_pb(self, data, exit_pb=None): + pb = wandb_internal_pb2.Record() + pb.ParseFromString(data) + record_type = pb.WhichOneof("record_type") + if self._view: + if self._verbose: + print("Record:", pb) # noqa: T201 + else: + print("Record:", record_type) # noqa: T201 + return pb, exit_pb, True + if record_type == "run": + if self._run_id: + pb.run.run_id = self._run_id + if self._project: + pb.run.project = self._project + if self._entity: + pb.run.entity = self._entity + if self._job_type: + pb.run.job_type = self._job_type + # Replace tags if specified + if self._replace_tags: + new_tags = [self._replace_tags.get(tag, tag) for tag in pb.run.tags] + pb.run.ClearField("tags") + pb.run.tags.extend(new_tags) + pb.control.req_resp = True + elif record_type in ("output", "output_raw") and self._skip_console: + return pb, exit_pb, True + elif record_type == "exit": + exit_pb = pb + return pb, exit_pb, True + elif record_type == "final": + assert exit_pb, "final seen without exit" + pb = exit_pb + exit_pb = None + return pb, exit_pb, False + + def _find_tfevent_files(self, sync_item): + tb_event_files = 0 + tb_logdirs = [] + tb_root = None + if self._sync_tensorboard: + if os.path.isdir(sync_item): + files = [] + for dirpath, _, _files in os.walk(sync_item): + for f in _files: + if TFEVENT_SUBSTRING in f: + files.append(os.path.join(dirpath, f)) + for tfevent in files: + tb_event_files += 1 + tb_dir = os.path.dirname(os.path.abspath(tfevent)) + if tb_dir not in tb_logdirs: + tb_logdirs.append(tb_dir) + if len(tb_logdirs) > 0: + tb_root = os.path.dirname(os.path.commonprefix(tb_logdirs)) + + elif TFEVENT_SUBSTRING in sync_item: + tb_root = os.path.dirname(os.path.abspath(sync_item)) + tb_logdirs.append(tb_root) + tb_event_files = 1 + return tb_event_files, tb_logdirs, tb_root + + def _setup_tensorboard(self, tb_root, tb_logdirs, tb_event_files, sync_item): + """Return true if this sync item can be synced as tensorboard.""" + if tb_root is not None: + if tb_event_files > 0 and sync_item.endswith(WANDB_SUFFIX): + wandb.termwarn("Found .wandb file, not streaming tensorboard metrics.") + else: + print(f"Found {tb_event_files} tfevent files in {tb_root}") # noqa: T201 + if len(tb_logdirs) > 3: + wandb.termwarn( + f"Found {len(tb_logdirs)} directories containing tfevent files. " + "If these represent multiple experiments, sync them " + "individually or pass a list of paths." + ) + return True + return False + + def _send_tensorboard(self, tb_root, tb_logdirs, send_manager): + if self._entity is None: + viewer, _ = send_manager._api.viewer_server_info() + self._entity = viewer.get("entity") + proto_run = wandb_internal_pb2.RunRecord() + proto_run.run_id = self._run_id or wandb.util.generate_id() + proto_run.project = self._project or wandb.util.auto_project_name(None) + proto_run.entity = self._entity + proto_run.telemetry.feature.sync_tfevents = True + + url = ( + f"{self._app_url}" + f"/{url_quote(proto_run.entity)}" + f"/{url_quote(proto_run.project)}" + f"/runs/{url_quote(proto_run.run_id)}" + ) + print(f"Syncing: {url} ...") # noqa: T201 + sys.stdout.flush() + # using a handler here automatically handles the step + # logic, adds summaries to the run, and handles different + # file types (like images)... but we need to remake the send_manager + record_q = queue.Queue() + sender_record_q = queue.Queue() + new_interface = InterfaceQueue(record_q) + context_keeper = context.ContextKeeper() + send_manager = sender.SendManager( + settings=send_manager._settings, + record_q=sender_record_q, + result_q=queue.Queue(), + interface=new_interface, + context_keeper=context_keeper, + ) + record = send_manager._interface._make_record(run=proto_run) + settings = wandb.Settings( + root_dir=self._tmp_dir.name, + run_id=proto_run.run_id, + x_start_time=time.time(), + ) + + settings_static = SettingsStatic(dict(settings)) + + handle_manager = handler.HandleManager( + settings=settings_static, + record_q=record_q, + result_q=None, + stopped=False, + writer_q=sender_record_q, + interface=new_interface, + context_keeper=context_keeper, + ) + + filesystem.mkdir_exists_ok(settings.files_dir) + send_manager.send_run(record, file_dir=settings.files_dir) + watcher = tb_watcher.TBWatcher( + settings_static, + proto_run, + new_interface, + True, + ) + + for tb in tb_logdirs: + watcher.add(tb, True, tb_root) + sys.stdout.flush() + watcher.finish() + + # send all of our records like a boss + progress_step = 0 + spinner_states = ["-", "\\", "|", "/"] + line = " Uploading data to wandb\r" + while len(handle_manager) > 0: + data = next(handle_manager) + handle_manager.handle(data) + while len(send_manager) > 0: + data = next(send_manager) + send_manager.send(data) + + print_line = spinner_states[progress_step % 4] + line + wandb.termlog(print_line, newline=False, prefix=True) + progress_step += 1 + + # finish sending any data + while len(send_manager) > 0: + data = next(send_manager) + send_manager.send(data) + sys.stdout.flush() + handle_manager.finish() + send_manager.finish() + + def _robust_scan(self, ds): + """Attempt to scan data, handling incomplete files.""" + try: + return ds.scan_data() + except AssertionError as e: + if ds.in_last_block(): + wandb.termwarn( + f".wandb file is incomplete ({e}), be sure to sync this run again once it's finished" + ) + return None + else: + raise + + def run(self): + if self._log_path is not None: + print(f"Find logs at: {self._log_path}") # noqa: T201 + for sync_item in self._sync_list: + tb_event_files, tb_logdirs, tb_root = self._find_tfevent_files(sync_item) + if os.path.isdir(sync_item): + files = os.listdir(sync_item) + filtered_files = list(filter(lambda f: f.endswith(WANDB_SUFFIX), files)) + if tb_root is None and ( + check_and_warn_old(files) or len(filtered_files) != 1 + ): + print(f"Skipping directory: {sync_item}") # noqa: T201 + continue + if len(filtered_files) > 0: + sync_item = os.path.join(sync_item, filtered_files[0]) + sync_tb = self._setup_tensorboard( + tb_root, tb_logdirs, tb_event_files, sync_item + ) + # If we're syncing tensorboard, let's use a tmp dir for images etc. + root_dir = self._tmp_dir.name if sync_tb else os.path.dirname(sync_item) + + # When appending we are allowing a possible resume, ie the run + # does not have to exist already + resume = "allow" if self._append else None + + sm = sender.SendManager.setup(root_dir, resume=resume) + if sync_tb: + self._send_tensorboard(tb_root, tb_logdirs, sm) + continue + + ds = datastore.DataStore() + try: + ds.open_for_scan(sync_item) + except AssertionError as e: + print(f".wandb file is empty ({e}), skipping: {sync_item}") # noqa: T201 + continue + + # save exit for final send + exit_pb = None + finished = False + shown = False + while True: + data = self._robust_scan(ds) + if data is None: + break + pb, exit_pb, cont = self._parse_pb(data, exit_pb) + if exit_pb is not None: + finished = True + if cont: + continue + sm.send(pb) + # send any records that were added in previous send + while not sm._record_q.empty(): + data = sm._record_q.get(block=True) + sm.send(data) + + if pb.control.req_resp: + result = sm._result_q.get(block=True) + result_type = result.WhichOneof("result_type") + if not shown and result_type == "run_result": + r = result.run_result.run + # TODO(jhr): hardcode until we have settings in sync + url = ( + f"{self._app_url}" + f"/{url_quote(r.entity)}" + f"/{url_quote(r.project)}" + f"/runs/{url_quote(r.run_id)}" + ) + print(f"Syncing: {url} ... ", end="") # noqa: T201 + sys.stdout.flush() + shown = True + sm.finish() + # Only mark synced if the run actually finished + if self._mark_synced and not self._view and finished: + synced_file = f"{sync_item}{SYNCED_SUFFIX}" + with open(synced_file, "w"): + pass + print("done.") # noqa: T201 + + +class SyncManager: + def __init__( + self, + project=None, + entity=None, + run_id=None, + job_type=None, + mark_synced=None, + app_url=None, + view=None, + verbose=None, + sync_tensorboard=None, + log_path=None, + append=None, + skip_console=None, + replace_tags=None, + ): + self._sync_list = [] + self._thread = None + self._project = project + self._entity = entity + self._run_id = run_id + self._job_type = job_type + self._mark_synced = mark_synced + self._app_url = app_url + self._view = view + self._verbose = verbose + self._sync_tensorboard = sync_tensorboard + self._log_path = log_path + self._append = append + self._skip_console = skip_console + self._replace_tags = replace_tags or {} + + def status(self): + pass + + def add(self, p): + self._sync_list.append(os.path.abspath(str(p))) + + def start(self): + # create a thread for each file? + self._thread = SyncThread( + sync_list=self._sync_list, + project=self._project, + entity=self._entity, + run_id=self._run_id, + job_type=self._job_type, + view=self._view, + verbose=self._verbose, + mark_synced=self._mark_synced, + app_url=self._app_url, + sync_tensorboard=self._sync_tensorboard, + log_path=self._log_path, + append=self._append, + skip_console=self._skip_console, + replace_tags=self._replace_tags, + ) + self._thread.start() + + def is_done(self): + return not self._thread.is_alive() + + def poll(self): + time.sleep(1) + return False + + +def get_runs( + include_offline: bool = True, + include_online: bool = True, + include_synced: bool = False, + include_unsynced: bool = True, + exclude_globs: list[str] | None = None, + include_globs: list[str] | None = None, +): + # TODO(jhr): grab dir info from settings + base = ".wandb" if os.path.exists(".wandb") else "wandb" + if not os.path.exists(base): + return () + all_dirs = os.listdir(base) + dirs = [] + if include_offline: + dirs += filter(lambda _d: _d.startswith("offline-run-"), all_dirs) + if include_online: + dirs += filter(lambda _d: _d.startswith("run-"), all_dirs) + # find run file in each dir + fnames = [] + dirs.sort() + for d in dirs: + paths = os.listdir(os.path.join(base, d)) + if exclude_globs: + paths = set(paths) + for g in exclude_globs: + paths = paths - set(fnmatch.filter(paths, g)) + paths = list(paths) + if include_globs: + new_paths = set() + for g in include_globs: + new_paths = new_paths.union(fnmatch.filter(paths, g)) + paths = list(new_paths) + for f in paths: + if f.endswith(WANDB_SUFFIX): + fnames.append(os.path.join(base, d, f)) + filtered = [] + for f in fnames: + dname = os.path.dirname(f) + # TODO(frz): online runs are assumed to be synced, verify from binary log. + if os.path.exists(f"{f}{SYNCED_SUFFIX}") or os.path.basename(dname).startswith( + "run-" + ): + if include_synced: + filtered.append(_LocalRun(dname, True)) + else: + if include_unsynced: + filtered.append(_LocalRun(dname, False)) + return tuple(filtered) + + +def get_run_from_path(path): + return _LocalRun(path) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/vendor/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/wandb/vendor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391